While executing a program, decision making plays a crucial part. This decision making can be handled with four different conditional statements. They are
If
If-else
if-else-if
Switch
Decision-making statements are those statements which allow the programmers to decide which statement should run in different conditions. There are four ways to achieve this:
The purpose of if statement is it'll check whether the condition is true or false. if it satisfies the condition, Statement gets executed or else it won't.
syntax:
if(condition) {
// Body or line of statements will be executed, when the condition is true
}
Eg:
void main(){
int a =10;
if(a%2 == 0){
print('A is an even number');
}
}
//Output = A is an even number
This statement works on true or false of a condition. If the condition is true then IF statement will be executed or else, Else else statement will executed.
Syntax:
if(condition) {
// Body or line of statements will be executed, when the condition is true
}else {
// This block will be executed when the if condition is false
}
Ex:
void main(){
int a =11;
if(a%2 == 0){
print('The given number is Even');
}else{
print('The given number is Odd');
}
}
// Output: print('The given number is Odd');
This type of statement simply checks the condition and if it is true the statements within it is executed but if it in is not then other if conditions are checked, if they are true then they are executed and if not then the other if conditions are checked. This process is continued until the ladder is completed.
Ex:
void main(){
int marks =5;
if(marks > 90){
print('Outstanding performance, Achieved O');
}else if(marks<90 && marks>70){
print('Distinction, Achieved A');
}else if(marks < 70 && marks >60){
print('First class, Achieved B');
}else{
print('You\'re failed');
}
}
Conditional operators can also be called Ternary Operators. These operators are the short form of If-else statements. In dart, we have two kinds of ternary operators, They're one for conditional expressions check and the other for validating null-safety.
Let's discuss conditional operators in detail.
Syntax:
condition? expressionForTrue: expressionForFalse
Eg:
void main(){
int a = 10;
int b = 5;
bool c = a>b ? true : false;
print(c);
// Output: true
}
Now discuss the second case where we use ternary operators for null safety
Syntax:
expression 1?? expression 2
The major difference between both the syntaxes is, In the first syntax it is purely based on the condition of the statement if the condition is true it'll execute the first expression, or else the second expression will get executed. whereas in the second syntax it'll check whether the given expression is null or not. if it is null it'll execute the second expression or else it'll continue with the first expression. Let's take a look on the second syntax
Eg:
void main(){
var a = null;
var b = 'a is null, Hence b executed';
var c = a ?? b;
print(c);
// Output: a is null, Hence b executed
}