Level 1 : Project 1


In a list of integers, the existence of at least two even elements consecutively forrms "an even sequence".

We propose to write a Dart program which allows to fill a list T by N postive integers(with 3≤ N ≤20) and display the number of even sequences of this table as well as the integers of each of these sequences.

Example:

For N = 15 and the following table T :
example of a table
Output :
The number of even sequences is 3.
The sequences of even integers are:
[18, 4]
[6, 24, 10]
[18, 4]


Solution:


import 'dart:io';

 

List fill(int n) {

  var x, tab = [];

  for (int i = ; i < n; i++) {

    do {

      print("Enter the element number ${i + 1}");

      x = int.tryParse(stdin.readLineSync());

      if (x != null) {

        if (x < 0) x = null;

      }

    } while (x == null);

    tab.add(x);

  }

  return tab;

}

 

void display(List tab) {

  var sum = 0, i = 0;

  var listOfSequence = "", sequence = [];

  while (i < tab.length - 1) {

    if ((tab[i] % 2 == 0) && (tab[i + 1] % 2 == 0)) {

      sequence = [tab[i], tab[i + 1]];

      for (int j = i + 2; j < tab.length; j++) {

        if (tab[j] % 2 == 0) {

          sequence.add(tab[j]);

        } else {

          i = j;

          break;

        }

      }

      listOfSequence += sequence.toString() + "\n";

      sequence = [];

      sum++;

    } else

      i++;

  }

  print("The number of even sequences is $sum");

  print("The sequences of even integers are:");

  print(listOfSequence);

}

 

void main() {

  var n;

  //reading n (with 3≤ n ≤20)

  do {

    print("Enter n (with 3≤ n ≤20)");

    n = int.tryParse(stdin.readLineSync());

    if (n != null) {

      if (!((n >= 3) && (n <= 20))) n = null;

    }

  } while (n == null);

  // //filling the list

  var t = fill(n);

  //display the number of even sequences of this table

  //and the integers of each of these sequences

  display(t);

}



Enter n (with 3≤ n ≤20)
15
Enter the element number 1
3
Enter the element number 2
18
Enter the element number 3
4
Enter the element number 4
7
Enter the element number 5
5
Enter the element number 6
6
Enter the element number 7
24
Enter the element number 8
10
Enter the element number 9
1
Enter the element number 10
8
Enter the element number 11
3
Enter the element number 12
18
Enter the element number 13
4
Enter the element number 14
11
Enter the element number 15
8
The number of even sequences is 3
The sequences of even integers are:
[18, 4]
[6, 24, 10]
[18, 4]