Exercises

Note: we don't interest in controlling user input.

  • Exercise 1: (if..else)
  • Write a program to get a number from the user and print whether it is positive or negative.




    Solution:


    import 'dart:io';

     

    void main() {

      print("Enter a number");

      var input = int.tryParse(stdin.readLineSync());

      if (input == null)

        print("Invalid Input");

      else if (input > 0)

        print("Positive");

      else if (input < 0)

        print("Negative");

      else

        print("You entred 0");

    }



    Enter a number
    -3
    Negative

    Enter a number
    s
    Invalid Input

    Enter a number
    23
    Positive


  • Exercise 2: (if..else)
  • Write a program to solve quadratic equations.

    Example:

         Input :
              a=2
              b=5
              c=3
         Expected Output :
              x1 = -1.5 and x2 = -1.0

         Input :
              a=1
              b=2
              c=1
         Expected Output :
              x = -1.0

         Input :
              a=1
              b=9
              c=30
         Expected Output :
              Roots are complex


    To get the positive square root of the value:
    1- Write import 'dart:math' ; before void main().
    2- Use sqrt(num x) .

    Quadratic Equation solving rules




    Solution:


    import 'dart:io';

    import 'dart:math';

     

    void main() {

      print("enter a");

      var a = int.tryParse(stdin.readLineSync());

      print("enter b");

      var b = int.tryParse(stdin.readLineSync());

      print("enter c");

      var c = int.tryParse(stdin.readLineSync());

      var d = b * b - 4 * a * c;

      if (d > 0) {

        var x1 = (-b - (sqrt(d))) / (2 * a);

        var x2 = (-b + (sqrt(d))) / (2 * a);

        print("x1 = $x1  and x2 = $x2");

      } else if (d == 0) {

        var x = -b / (2 * a);

        print("x = $x");

      } else {

        print("Roots are complex");

      }

    }



    enter a
    1
    enter c
    2
    x1 = -3.414213562373095 and x2 = -0.5857864376269049

    enter a
    1
    enter b
    2
    enter c
    9
    Roots are complex

    enter a
    1
    enter b
    2
    enter c
    1
    x = -1.0


  • Exercise 3: (if..else)
  • Write a program that accepts three numbers from the user and prints "increasing" if the numbers are in increasing order, "decreasing" if the numbers are in decreasing order, and "Neither increasing or decreasing order" otherwise.




    Solution:


    import 'dart:io';

     

    void main() {

      print("Enter a :");

      var a = int.tryParse(stdin.readLineSync());

      print("Enter b :");

      var b = int.tryParse(stdin.readLineSync());

      print("Enter c :");

      var c = int.tryParse(stdin.readLineSync());

      if (a > b && b > c)

        print("decreasing");

      else if (c > b && b > a)

        print("increasing");

      else

        print("Neither increasing or decreasing order");

    }



    Enter a :
    2
    Enter b :
    5
    Enter c :
    9
    increasing

    Enter a :
    8
    Enter b :
    7
    Enter c :
    4
    decreasing

    Enter a :
    4
    Enter b :
    7
    Enter c :
    2
    Neither increasing or decreasing order

  • Exercise 4: (for)
  • Write a program to calculate the sum of first 10 natural number.




    Solution:


    void main() {

      int sum = 0;

      for (int i = 1; i < 10; i++) sum += i;

      print("the sum of first 10 natural number is $sum");

    }



    the sum of first 10 natural number is 45

  • Exercise 5: (for)
  • Write a program that prompts the user to input an integer and then outputs the number with the digits reversed. For example, if the input is 12345, the output should be 54321.


    Solution:




    import 'dart:io';

     

    void main() {

      print("enter a number");

      var input = stdin.readLineSync();

      int number = int.tryParse(input);

      int reversed = 0;

      for (int i = 1; i <= input.length; i++) {

        reversed = reversed * 10 + number % 10;

        number ~/= 10;

      }

      print(reversed);

    }



    enter a number
    21983154
    45138912

  • Exercise 6: (for)
  • Write a program that prompts the user to input a positive integer. It should then output a message indicating whether the number is a prime number.


    A prime number is a number which is divisible by only two numbers: 1 and itself.
    So, if any number is divisible by any other number, it is not a prime number.
    Note that you can loop until number/2. It is because a number is not divisible by more than its half.




    Solution:


    import 'dart:io';

     

    void main() {

      bool prime = true;

      print("enter a number");

      var input = int.tryParse(stdin.readLineSync());

      for (int i = 2; i < input ~/ 2; i++) {

        if (input % i == 0) {

          print("Not Prime Number");

          prime = false;

          break;

        }

      }

      if (prime) print("Prime Number");

    }



    enter a number
    24
    Not Prime Number

    enter a number
    19
    Prime Number

  • Exercise 7: (for)
  • Write a program that determine and print the number of times the character ‘a’ appears in the input entered by the user.




    Solution:


    import 'dart:io';

     

    void main() {

      print("write something");

      var input = stdin.readLineSync();

      var apps = 0;

      for (int i = 0; i < input.length; i++) if (input[i] == 'a') apps++;

      print("'a' appears $apps times");

    }



    write something
    i am learning dart today
    'a' appears 4 times

  • Exercise 8: (for)
  • Write a program to calculate the factorial value of given number.
    Factorial x = x * x-1 * x-2 * … *1

    Example: factorial 4 = 4 * 3 * 2 * 1 = 24




    Solution:


    import 'dart:io';

     

    void main() {

      print("enter a number");

      var input = int.tryParse(stdin.readLineSync());

      var fac = 1;

      for (int i = input; i > 1; i--) fac *= i;

      print("the factorial of $input is $fac");

    }



    enter a number
    7
    the factorial of 7 is 5040

  • Exercise 9: (for)
  • Write a program that onvert a name into initials. You can assume the program takes in two words with one space in between them. The output should be two capital letters with a dot separating them.
    Example:
         Program Starts:
         Please enter name:
         Sam Smith
         
         Output:
         S.S


    Solution:


    import 'dart:io';

     

    void main() {

      print("enter a name");

      var name = stdin.readLineSync();

      var initals = name[0].toUpperCase() + '.';

      for (int i = 0; i < name.length; i++) {

        if (name[i] == ' ') {

          initals += name[i + 1].toUpperCase();

          break;

        }

      }

      print(initals);

    }



    enter a name
    Cristiano Ronaldo
    C.R

  • Exercise 10: (while)
  • Write a program to find the first 80 numbers starting from 100 where each digit of a number is an even number(ex: 242). The numbers obtained should be printed in a list.




    Solution:


    void main() {

      var list = [];

      int i = 100;

      while (list.length < 80) {

        if ((i % 2 == 0) && ((i ~/ 10) % 2 == 0) && ((i ~/ 100) % 2 == 0))

          list.add(i);

        i++;

      }

      print(list);

    }



    [200, 202, 204, 206, 208, 220, 222, 224, 226, 228, 240, 242, 244, 246, 248, 260, 262, 264, 266, 268, 280, 282, 284, 286, 288, 400, 402, 404, 406, 408, 420, 422, 424, 426, 428, 440, 442, 444, 446, 448, 460, 462, 464, 466, 468, 480, 482, 484, 486, 488, 600, 602, 604, 606, 608, 620, 622, 624, 626, 628, 640, 642, 644, 646, 648, 660, 662, 664, 666, 668, 680, 682, 684, 686, 688, 800, 802, 804, 806, 808]

  • Exercise 11: (while)
  • Write a program to check the validity of password input by users.

    Validation :

    • At least 1 letter between [a-z] and 1 letter between [A-Z].

    • At least 1 number between [0-9].

    • Minimum length 6 characters.

    • Maximum length 16 characters.


    ASCII is a code that uses numbers to represent characters.
    Each letter is assigned a number between 0 and 127.
    A upper and lower case character are assigned different numbers.
    For example the character A is assigned the decimal number 65, while a is assigned decimal 97.
    ASCII Full Table
    In Dart, you can use codeUnitAt(index)to get the ascii code of character.




    Solution:


    import 'dart:io';

     

    void main() {

      bool upperLetter = false;

      bool lowerLetter = false;

      bool number = false;

      print("enter a password");

      var psw = stdin.readLineSync();

      if (psw.length >= 6 && psw.length < 16) {

        int i = 0;

     

        while (i < psw.length && !(number && upperLetter && lowerLetter)) {

          if (psw.codeUnitAt(i) >= 'A'.codeUnitAt(0) &&

              psw.codeUnitAt(i) <= "Z".codeUnitAt(0))

            upperLetter = true;

          else if (psw.codeUnitAt(i) >= 'a'.codeUnitAt(0) &&

              psw.codeUnitAt(i) <= "z".codeUnitAt(0))

            lowerLetter = true;

          else if (psw.codeUnitAt(i) >= '0'.codeUnitAt(0) &&

              psw.codeUnitAt(i) <= "9".codeUnitAt(0)) number = true;

          i++;

        }

        if (number && upperLetter && lowerLetter)

          print("Valid");

        else

          print("not Valid");

      } else

        print("not Valid");

    }



    enter a password
    testABD123
    Valid

    enter a password
    test123
    not Valid

  • Exercise 12: (do..while)
  • Write a program that calculate the average of given numbers from user and ask the user every time for more numbers.
    If user say "yes" ask him for another number and if "No" give the average.


    Solution:


    import 'dart:io';

     

    void main() {

      int average = 0;

      int numbers = 0;

      bool again;

      do {

        again = false;

        print("Enter a number :");

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

        average += x;

        numbers++;

        print("say Yes to add more and No to print the average");

        var answer = stdin.readLineSync().toUpperCase();

        if (answer == "YES") again = true;

      } while (again);

      print("the average is ${average / numbers}");

    }



    Enter a number :
    14
    say Yes to add more and No to print the average
    YES
    Enter a number :
    13
    say Yes to add more and No to print the average
    YES
    Enter a number :
    20
    say Yes to add more and No to print the average
    YES
    Enter a number :
    8
    say Yes to add more and No to print the average
    NO
    the average is 13.75

  • Exercise 13: (do..while)

  • Generate a random number between 1 and 10. The user have 3 tries to guess the number.
    Print "Hard Luck ---- the number is ..." if he lose and "Good Job" if he win.


    To generate a random number in dart:
    - Write import 'dart:math'; before void main().
    - Use Random().nextInt(x)
    For Example : Random().nextInt(5) may give 0 or 1 or 2 or 3 or 4




    Solution:


    import 'dart:io';

    import 'dart:math';

     

    void main() {

      int rand = Random().nextInt(10) + 1;

      bool answer = false;

      int tries = 3;

      do {

        print("Guess a number between 1 and 10");

        var guess = int.tryParse(stdin.readLineSync());

        answer = guess == rand;

        tries--;

      } while (!answer && tries > 0);

      if (answer)

        print("Good Job");

      else

        print("Hard Luck  --- the number is $rand");

    }



    Guess a number between 1 and 10
    4
    Guess a number between 1 and 10
    7
    Guess a number between 1 and 10
    3
    Hard Luck --- the number is 10

    Guess a number between 1 and 10
    1
    Guess a number between 1 and 10
    2
    Good Job

  • Exercise 14: (switch)
  • Write a program to accept a grade and display the equivalent description:

    Grade description
    E Excellent
    V Very Good
    G Good
    A Average
    F Fail




    Solution:


    import 'dart:io';

     

    void main() {

      print("Enter a grade");

      var grade = stdin.readLineSync().toUpperCase();

      switch (grade) {

        case 'E':

          print('Excellent');

          break;

        case 'V':

          print('Very Good');

          break;

        case 'G':

          print('Good');

          break;

        case 'A':

          print("Average");

          break;

        case 'F':

          print("Fail");

          break;

        default:

          print("Invalid Grade");

          break;

      }

    }



    Enter a grade
    A
    Average

    Enter a grade
    C
    Invalid Grade

  • Exercise 15: (switch)
  • Write a program that print the number of days in month (input : 1..12).
    Note: Here we are not checking leap year, so we fixed 28 days for February.


    To set a multiple case statement in a switch / case dart, you can list cases one after the other to get the following code execute on either one of those cases.


    Example :

    switch (mark) {
        case 0 :
           print( "mark is 0") ;
           break;
        case 1:
        case 2:
        case 3:
           print("mark is either 1, 2 or 3") ;
           break;
        default :
           print( "mark is not 0, 1, 2 or 3" );
           break;
    }

    Solution:


    import 'dart:io';

     

    void main() {

      print("enter a mounth number");

      var month = int.tryParse(stdin.readLineSync());

      switch (month) {

        case 1:

        case 3:

        case 5:

        case 7:

        case 8:

        case 10:

        case 12:

          print("31 days");

          break;

        case 4:

        case 6:

        case 9:

        case 11:

          print("30 days");

          break;

        case 2:

          print("28 days");

          break;

        default:

          print("Invalid Month");

          break;

      }

    }



    enter a mounth number
    4
    30 days

    enter a mounth number
    2
    28 days