Introduction To Dart Programming Language
- Overview
- Environment
- Variables
- Operators
Explanations to week content
Taking input from a user through the console
In Dart programming language, you can take standard input from the user through the console by the use of .readLineSync() function. To take input from the console you need to import a library, named dart:io from libraries of Dart.
Example
Taking string input from user
The code below asks a user to enter the name then a welcome to Flutter Moble App. Development course is display to the username.
// importing dart:io file
import 'dart:io';
void main()
{
print("Enter your name");
// Reading name of the user
String name = stdin.readLineSync();
// Printing the name
print("Hello, ${name}! \nWelcome toFlutter Mobile App. Development. Hope you are having fun!!");
}
Result
Enter your name
Godwin Ashong
Hello, Godwin Ashong!
Welcome to Flutter Mobile App. Development. Hope you are having fun!!
NOTE: The \n is added to the text to make the text that follows move to the next line.
Taking integer input from user
To take an integer value from the user, you have to convert the string to integer using the parse function. For integer values int.parse(string comes here) is used. In this case our string is the stdin.readLineSync()
Example
The sample code below ask a user to enter the age and displays the entered age to the user
// Importing dart:io file
import 'dart:io';
void main()
{
// Asking for age
print("Enter your age:");
// Scanning number
int age = int.parse(stdin.readLineSync());
// Printing the age
print("You are ${age} yearsold");
}
Result
Enter your age:
17
You are 17 years old
Taking fraction/decimal (double) input
Taking double input is similar to the integer input except we use the double.parse function instead.
Example
// Importing dart:io file
import 'dart:io';
void main()
{
// Asking for age
print("Enter your salary:");
// Scanning number
double salary = double.parse(stdin.readLineSync());
// Printing the age
print("You salary is Ghc ${salary}");
}
Result
Enter your salary:
3500
You salary is Ghc 3500.0
Conditionals –Making Decisions
A computer can process a program in one of the following ways: in sequence; selectively, by making a choice, which is also called a branch; repetitively, by executing a statement over and over, using a structure called a loop; or by calling a function. The figure below illustrates the first three types of program flow.
If Statement
The if statement is in this format:
if(condition is true){
Run this block of codes
}
If a block of code(s) needs to be run if the condition is false, the else is included as shown below:
if(condition is true){
Run this block of codes
}else{
Run this block of codes
}
Examples
1. if (score is greater than or equal to 90)
grade is A
2. if (hours worked are less than or equal to 40)
wages = rate *hours
else
wages = (rate *40) + 1.5 *(rate *(hours – 40))
3. if (temperature is greater than 70 degrees and it is not raining)
Go golfing!
Relational Operators
Operator | Description |
---|---|
== | Equal to (NB: is two equal to signs) |
!= | Not equal to |
> | Greater than |
>= | Greater than or equal to |
< | Less than |
<= | Less than or equal to |
Code Examples
Let's us modify our input samples to make decisions.
We will modify the code that takes the age of a person. If the age is 18 or more, you inform the user that he is qualified to drink but he should drink wisely otherwise we tell the user not qualified to drink because he/she is under age
// Importing dart:io file
import 'dart:io';
void main()
{
// Asking for age
print("Enter your age:");
// Scanning number
int age = int.parse(stdin.readLineSync());
// Check if user is 18 or more
if(age>=18){
print("You are ${age} years old. You are qualified to drink but please drink wisely");
}else{
print("You are ${age} years old. You are under age and not qualify to drink so you are not allowed enter the bar");
}
}
Results
Enter your age:
24
You are 24 years old. You are qualified to drink but please drink wisely
Enter your age:
16
You are 16 years old. You are under age and not qualify to drink so you are not allowed enter the bar
Write a program which determines whether an integer entered is an even number or not
Sample Code
Concept.
An even number is a number divisible by 2 without are remainder. The operator for calculating a remainder of a number divided by another number is modulus (%) as explained earlier. If the remainder is 0,then it means the number is an even number. Hence the sample code below.
// Importing dart:io file
import 'dart:io';
void main()
{
// Asking for number
print("Enter an integer:");
// Scanning number
int num = int.parse(stdin.readLineSync());
// Check if number is even or not
if(num%2==0){
print("${num} is an even number");
}else{
print("${num} is an odd number");
}
}
Results
Enter an integer:
3
3 is an odd number
Enter an integer:
4
4 is an even number
Conditions and Meaning
Condition | Meaning |
---|---|
Condition 1 && Condition 2 e.g int a = 2; int b = 3; if((a%2==0)&&(b>=3)){ ………….. } If((!(a%2==0))&&(!(b%2==0))){ …………… } | && means and If both condition 1 and condition 2 are true, the Boolean will be true, else if at least one of the conditions is false, the Boolean will be false. This if statement will be true because a%2 =0 and b is equal to 3. Since both conditions are true, the Boolean of the if statement will be true. NOTE: ! means not. Hence !(a%2==0) means a modulus 2 not equal to 0. This conditional statement will be false since a is 2 and 2%2 is 0. !(b%2==0) means b modulus 2 not equal to 0. This conditional statement will be true since b is 3 and 3%2 is 1 which is not equal to 0. But since one of the condition is false in the && operation, the entire if statement will be false. |
Condition 1 || condition 2 e.g int a = 2; int b = 3; if((a%2==0)||(b>=3)){ ………….. } If((!(a%2==0))||(!(b%2==0))){ …………… } | || means or This means if Condition 1 is true or Condition 2 is true. In this case if any of the conditions is true, the Boolean will be true. The Boolean will be true because at least one of the conditions is true. Since a = 2 and b =3, 2%2 is 0 and 3 is equal to 3. Both statements are true. The Boolean for (!(a%2==0)) will be false. The Boolean for (!(b%2==0)) will be true. Since one of the conditions is true, the Boolean for the if statement will also be true for the || operation. |
Else if
The else if is used for multiple if statements. It is written in the following format.
if(statement 1 is true){
run this block of code
}else if(statement 1 is false and statement 2 is true){
run this block of code
}else if(statement 2 is false and statement 3 is true){
run this block of code.
}
.
.
.
else if(statement n-1 is false and statement n is true){
run this block of code.
}else{
if none of the above statements is true, run this block of code
}
Thus after option 1, the other options before the last option will have else if and the last option will have else
Example
The following is the grading system in a school.
90 – 100 | A |
---|---|
80 – 89…. | B |
50 – 79… | C |
0 – 49…. | FAIL |
Write a program to take the percentage score and output the grade to a user.
// Importing dart:io file
import 'dart:io';
void main()
{
// Asking for score
print("Enter your percentage score:");
// Scanning number
double score = double.parse(stdin.readLineSync());
// Calculate the grade
if(score>=90){
print("${score} is grade A");
}else if(score>=80){
print("${score} is grade B");
}else if(score>=50){
print("${score} is grade C");
}else{
print("${score} is Fail");
}
}
Results
Enter your percentage score:
75
75.0 is grade C
Enter your percentage score:
49
49.0 is Fail
Switch
There are two selection, or branch. The first selection structure, which is implemented with if and if. . .else statements, usually requires the evaluation of a (logical)expression. The second selection structure, which does not require the evaluation of a logical expression, is called the switch structure.
switch structure gives the computer the power to choose from among many alternatives.
A general syntax of the switch statement is:
switch(expression or value)
{
case value1:
statements1
break;
case value2:
statements2
break;
.
.
.
case valuen:
statementsn
break;
default:
statements
}
switch, case, break, and default are reserved words. The default statement is run when none of the case values is the expression.
The switch statement executes according to the following rules:
1.
When the value of the expression is matched against a case value (also called a label), the statements execute until either a break statement is found or the end of the switch structure is reached.
2.
If the value of the expression does not match any of the case values, the statements following the default label execute. If the switch structure has no default label and if the value of the expression does not match any of the case values, the entire switch statement is skipped.
3.
A break statement causes an immediate exit from the switch structure.
This is illustrated in the figure below.
Example
Let's modify our age drinking program so this time we use a switch statement instead for the condition checking
// Importing dart:io file
import 'dart:io';
void main()
{
// Asking for age
print("Enter your age");
// Scanning number
int age = int.parse(stdin.readLineSync());
// Check if number is even or not
switch(age>=18){
case true:
print("Your age is ${age}. You are an adult. You can drink");
break;
case false:
print("Your age is ${age}. You are under age. You can't' drink");
break;
default:
print("Invalid input");
}
}
Results
Enter your age
14
Your age is 14. You are under age. You can't' drink
Nested If
When one control statement is located within another, it is said to be nested.
Nested if is therefore an if statement in another if statement.
Example
Write a program that determine if a number is an even or not and if even, determine whether is divisible by 10 or not.
// Importing dart:io file
import 'dart:io';
void main()
{
// Asking for number
print("Enter an integer");
// Scanning number
int num = int.parse(stdin.readLineSync());
if(num%2==0){
if(num%10==0){
print("${num} is an even number and divisible by 10");
}else{
print("${num} is an even number but not divisible by 10");
}
}else{
print("${num} is not an even number");
}
}
Results
Enter an integer
20
20 is an even number and divisible by 10
Enter an integer
5
5 is not an even number
Enter an integer
26
26 is an even number but not divisible by 10
LOOP
Branch statements allow you to direct the flow of a program’s execution down one path or another.
The While Statement
The simplest form of looping statement is the while loop.Here’s what the while loop looks like:
while(condition)
{
// ...repeatedly executed as long as condition is true
}
From the above state, the block of code in the while repeats over and over again until the condition in the while loop is false.
The variable in the condition that makes it true is updated at each cycle of the loop in order to be false at a particular point.
Example
Let's modify our even number determination program so that the program repeats over and over again until a user enters the letter q to quit the program.
// Importing dart:io file
import 'dart:io';
void main()
{
String quit = "e";
while(quit.toLowerCase() !="q"){
print("Enter an integer");
// Scanning number
int num = int.parse(stdin.readLineSync());
if(num%2==0){
print("${num} is an even number");
}else{
print("${num} is an odd number");
}
print("Enter q to quit or any other input to run again");
quit = stdin.readLineSync();
//quit is the control variable. Once the value is q, the loop ends
}
}
Results
Enter an integer
4
4 is an even number
Enter q to quit or any other input to run again
a
Enter an integer
3
3 is an odd number
Enter q to quit or any other input to run again
p
Enter an integer
5
5 is an odd number
Enter q to quit or any other input to run again
q
Quit with Q Result
Enter an integer
4
4 is an even number
Enter q to quit or any other input to run again
b
Enter an integer
6
6 is an even number
Enter q to quit or any other input to run again
b
Enter an integer
9
9 is an odd number
Enter q to quit or any other input to run again
Q
The variable to control the loop is quit. In order for the while loop to run at least once, the variable that controls the loop should be initialized with a value that makes the condition to be true.
From the above code, quit is initialized to e to make the condition quit.ToLower() != "q" true.
quit is converted to lower case in order to match q in case user enters Q. We will consider more of these String functions in this week's lesson.
NOTE: != means not equal to
After the program task is completed, the user is asked to enter q to quit or any other input to continue. If user enters q, the condition will then be false since q !=q is false since q is equal to q. Once the condition is false, the loop ends.
Decreasing or increasing an integer value
To increase an integer value, you can use any of these methods:
To increase an integer value, you can use any of these methods:
1. variable= variable + 1;
2. variable++;
1 is added to the old value of the variable and the result is assigned to the variable.
To decrease an integer value, you can use any of these methods:
1. variable= variable - 1;
2. variable--;
1 is subtracted from the old value of the variable and the result is assigned to the variable.
Write a program that prints out the numbers from 1 to 10
// Importing dart:io file
import 'dart:io';
void main()
{
int i = 1;
while(i<=10){
//Print out the value of i
print("${i}");
//Increase the value of i to quit the loop at a point in time
i++;
}
}
Result
1
2
3
4
5
6
7
8
9
10
The while loop will keep on repeating so far as the condition i<=10 is true. i needs to be initialized to make the condition true in order for the block of code in the while loop to start execution. The repetition ends when i<=10 is false. Thus when i is more than 10. i++; increases the i anytime that line of code is executed. i++; is the same as i = i+1;
Detail Explanation
Repetition | Value of i | Condition | Boolean | Loop Status |
---|---|---|---|---|
0 | i = 1 | 1 <= 10 | True | While loop continues |
1 | i++; i = 2 same as i = 1+1 | 2 <= 10 | True | While loop continues |
2 | i++; i = 3 same as i = 2+1 | 3 <=10 | True | While loop continues |
3 | i++; i = 4 same as i = 3+1 | 4 <=10 | True | While loop continues |
4 | i++; i = 5 same as i = 4+1 | 5 <=10 | True | While loop continues |
5 | i++; i = 6 same as i = 5+1 | 6 <=10 | True | While loop continues |
6 | i++; i = 7 same as i = 6+1 | 7 <=10 | True | While loop continues |
7 | i++; i = 8 same as i = 7+1 | 8 <=10 | True | While loop continues |
8 | i++; i = 9 same as i = 8+1 | 9 <=10 | True | While loop continues |
9 | i++; i = 10 same as i = 9+1 | 10 <=10 | True | While loop continues |
10 | i++; i = 11 same as i = 10+1 | 11 <=10 | False | While loop then ends |
In summary while loop is written in the form below:
//initialize the loop control variable(s). The expression must be true to start the loop.
while(expression)
{
.
.
.
//update the loop control variable(s). This will make the expression to be false at a point in time.
.
.
.
}
NOTE: If your loop control variable(s)update doesn’t make the expression false at certain point in time, you will end up with an endless loop.
The Do … while statement
A separate, less frequently used version of the while loop known as the do … while appears identical except the condition isn’t tested until the bottom of the loop:
do
{
// ...the inside of the loop
} while (condition);
Because the condition isn’t tested until the end, the body of the do … while is always executed at least once. Thus since the condition is tested at the bottom, the block of code in the do{} is run at least once before the condition is tested. If the condition is true, the loop continues and if not it is not repeated.
Example
// Importing dart:io file
import 'dart:io';
void main()
{
int i = 1;
do{
//Print out the value of i
print("${i}");
//Increase the value of i to quit the loop at a point in time
i++;
}while(i>2);
}
Result
1
Even i which at the time the loop begins has a value of 1 and is less than 2, the code in the block of the do while loop is executed until the while(i>2) line which is false since 1 is not greater than 2 and the loop ends.
A do...while loop can be used for input validation. Suppose that a program prompts a user to enter a test score, which must be greater than or equal to 0 and less than or equal to 100. If the user enters a score less than 0 or greater than 100, the user should be prompted to re-enter the score. The following do...while loop can be used to accomplish this objective:
// Importing dart:io file
import 'dart:io';
void main()
{
// Grade calculator
double score;
do{
// Asking for the score
print("Enter your percentage score:");
// Scanning number
score = double.parse(stdin.readLineSync());
//Only calculate grade when input is valid
if((score>0)&&(score<=100)){
if(score>=90){
print("${score} is grade A");
}else if(score>=80){
print("${score} is grade B");
}else if(score>=50){
print("${score} is grade C");
}else{
print("${score} is Fail");
}
}
}while((score<0)||(score>100)); //Repeat loop until input is valid
}
Results
Enter your percentage score:
-70
Enter your percentage score:
120
Enter your percentage score:
92
92.0 is grade A
The for loop
The most common form of loop is the for loop. The for loop is preferred over the more basic
while loop because it’s generally easier to read (there’s really no other advantage).
The for loop has the following format:
for (initialization; conditional; increment or decrement)
{
// ...body of the loop
}
The for loop is equivalent to the following while loop:
initialization;
while(conditional)
{
// ...body of the loop
increment or decrement;
}
Examples
Write a program that takes an integer from the user and output the multiplication table fo rthat user. For instance if a user enters 2, the output should look something like this:
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
2 x 4 = 8
2 x 5 = 10
2 x 6 = 12
2 x 7 = 14
2 x 8 = 16
2 x 9 = 18
2 x 10 = 20
2 x 11 = 22
2 x 12 = 24
// Importing dart:io file
import 'dart:io';
void main()
{
print("Enter the number to compute the multiplication table");
int num = int.parse(stdin.readLineSync());
for(int i=1;i<=12;i++){
print("$num x $i = ${i*num}");
}
}
Results
Enter the number to compute the multiplication table
2
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
2 x 4 = 8
2 x 5 = 10
2 x 6 = 12
2 x 7 = 14
2 x 8 = 16
2 x 9 = 18
2 x 10 = 20
2 x 11 = 22
2 x 12 = 24
The continue and break statement
When the break command is encountered, it causes control to exit the current loop immediately. The control passes from the break statement to the statement immediately following the closed brace at the end of the loop.
The format of the break commands is as follows:
while(condition) // break works equally well in for loop
{
if (condition)
{
break; // exit the loop
}
. // control passes here
. // control passes here
. // control passes here
}
// The control moves immediately here (after the closed brace at the end of the loop)
Example
Write a program that sum positive integers entered by a user continuously until a negative number is entered.
// Importing dart:io file
import 'dart:io';
void main()
{
int sum = 0;
while(true){
print("Enter a positive number");
int num = int.parse(stdin.readLineSync());
if(num>=0){
sum = sum+num;
}else{
break;
}
}
print("Total: ${sum}");
}
Result
Enter a positive number
5
Enter a positive number
6
Enter a positive number
8
Enter a positive number
-2
Total: 19
If negative number is entered the condition, (num>=0) will be false and hence the break in the else curly braces will move the control to outside the loop;
Continue
The continue statement is used in while, for, and do. . .while structures. When the continue statement is executed in a loop, it skips the remaining syntax in the loop and proceeds with the next iteration of the loop.
Example
// Importing dart:io file
import 'dart:io';
void main()
{
int sum = 0;
while(true){
print("Enter a positive number");
int num = int.parse(stdin.readLineSync());
if(num>=0){
sum = sum+num;
}else{
continue;
}
print("Total: ${sum}");
}
}
Result
Enter a positive number
4
Total: 4
Enter a positive number
5
Total: 9
Enter a positive number
-2
Enter a positive number
4
Total: 13
Enter a positive number
-5
Enter a positive number
2
Total: 15
Enter a positive number
5
Total: 20
Enter a positive number
When the continue is executed, the print("Total: ${sum}"); part is skipped and the loop is repeated.
Nested loops
A loop in another loop.
Example
Write a program that outputs the multiple table as shown below:
1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 |
---|---|---|---|---|---|---|---|---|---|---|---|
2 | 4 | 6 | 8 | 10 | 12 | 14 | 16 | 18 | 20 | 22 | 24 |
3 | 6 | 9 | 12 | 15 | 18 | 21 | 24 | 27 | 30 | 33 | 36 |
4 | 8 | 12 | 16 | 20 | 24 | 28 | 32 | 36 | 40 | 44 | 48 |
5 | 10 | 15 | 20 | 25 | 30 | 35 | 40 | 45 | 50 | 55 | 60 |
6 | 12 | 18 | 24 | 30 | 36 | 42 | 48 | 54 | 60 | 66 | 72 |
7 | 14 | 21 | 28 | 35 | 42 | 49 | 56 | 63 | 70 | 77 | 84 |
8 | 16 | 24 | 32 | 40 | 48 | 56 | 64 | 72 | 80 | 88 | 96 |
9 | 18 | 27 | 36 | 45 | 54 | 63 | 72 | 81 | 90 | 99 | 108 |
10 | 20 | 30 | 40 | 50 | 60 | 70 | 80 | 90 | 100 | 110 | 120 |
11 | 22 | 33 | 44 | 55 | 66 | 77 | 88 | 99 | 110 | 121 | 132 |
12 | 24 | 36 | 48 | 60 | 72 | 84 | 96 | 108 | 120 | 132 | 144 |
Solution
NOTE: To print horizontally you have to use stdout.write() which is a method in your dart library you imported when taking input from the user. The print method only displays information on a new line.
// Importing dart:io file
import 'dart:io';
void main()
{
//For the row values
for(int i=1;i<=12;i++){
//For the column values
for(int j=1;j<=12;j++){
stdout.write("${i*j} ");
}
//After 12 columns begin a new row
print("");
}
}
Result
1 2 3 4 5 6 7 8 9 10 11 12
2 4 6 8 10 12 14 16 18 20 22 24
3 6 9 12 15 18 21 24 27 30 33 36
4 8 12 16 20 24 28 32 36 40 44 48
5 10 15 20 25 30 35 40 45 50 55 60
6 12 18 24 30 36 42 48 54 60 66 72
7 14 21 28 35 42 49 56 63 70 77 84
8 16 24 32 40 48 56 64 72 80 88 96
9 18 27 36 45 54 63 72 81 90 99 108
10 20 30 40 50 60 70 80 90 100 110 120
11 22 33 44 55 66 77 88 99 110 121 132
12 24 36 48 60 72 84 96 108 120 132 144
Numbers
Dart numbers can be classified as:
int
Integer of arbitrary size. The int data type is used to represent whole numbers.
double
64-bit (double-precision) floating-point numbers. The double data type is used to represent fractional numbers.
As you have seen to convert a string to an integer we use the int.parse and to convert a string to a double we use the double.parse method.
The following table lists the properties supported by Dart numbers.
Sr.No | Property & Description |
---|---|
1 | hashcode Returns a hash code for a numerical value. |
2 | isFinite True if the number is finite; otherwise, false. |
3 | isInfinite True if the number is positive infinity or negative infinity; otherwise, false. |
4 | isNan True if the number is the double Not-a-Number value; otherwise, false. |
5 | isNegative True if the number is negative; otherwise, false. |
6 | sign Returns minus one, zero or plus one depending on the sign and numerical value of the number. |
7 | isEven Returns true if the number is an even number. |
8 | isOdd Returns true if the number is an odd number. |
Given below are a list of commonly used methods supported by numbers −
Sr.No | Method & Description |
---|---|
1 | abs Returns the absolute value of the number. |
2 | ceil Returns the least integer no smaller than the number. |
3 | compareTo Compares this to other number. |
4 | Floor Returns the greatest integer not greater than the current number. |
5 | remainder Returns the truncated remainder after dividing the two numbers. |
6 | Round Returns the integer closest to the current numbers. |
7 | toDouble Returns the double equivalent of the number. |
8 | toInt Returns the integer equivalent of the number. |
9 | toString Returns the string equivalent representation of the number. |
10 | truncate Returns an integer after discarding any fractional digits. |
Boolean
The keyword bool is used for the boolean data type.
The boolean data type value is either true or false.
To check if a boolean variable is true, we simply write:
if(nameOfBooleanVariable){
statement comes here
}
To check if a boolean variable is not true (false) we simply start with the exclamation mark (!) which means not in programming so the statement will be:
if(!nameOfBooleanVariable){
statement comes here
}
We can also write an expression which result is true or false and assign the result in a boolean variable.
Example:
void main(){
bool is_underage;
int age = 20;
is_underage = age < 18;
print(is_underage);
}
Output
false
We can modify the above code to take the age from the user and check the value of is_underage and display on the screen whether a user can drink or not.
import 'dart:io';
void main(){
print("Enter your age");
int age = int.parse(stdin.readLineSync());
bool is_underage;
is_underage = age < 18;
//If it is not true that the person is under age
if(!is_underage){
print("You can drink but drink wisely");
}else{
//If it is true that the person is under age
print("You are under age. You are not allowed to enter the bar");
}
}
Output
Enter your age
17
You are underage. You are not allowed to enter the bar