1.

Conditions and If Statements

Answer»
  • If statement
if (condition) {
// This block of code will get executed if the condition is True
}

If statement belongs to the category of decision-making statements. These statements make decisions based on a condition. If the condition in the condition block is true, the statements in the curly brackets { } are executed. Let’s see the example given below.

if(2<3){
cout << "2 is less than three";
}
  • If-else statement

If-else is an extension of the if statement. If the conditions provided with if are not true, the statements in the else block are executed.

if(2>3){
cout<< "2 is greater than 3";
}
else{
cout<< "3 is greater than 2";
}
  • else if

if can be paired with else if for additional conditions.

if(2>3){
cout<< "2 is greater than 3";
}
else if(2==3){
cout<< "2 is equal to 3";
}
else{
cout<< "3 is greater than 2";
}
  • Switch case
switch (grade) {
case 9:
cout << "Freshman\n";
break;
case 10:
cout << "Sophomore\n";
break;
case 11:
cout << "Junior\n";
break;
case 12:
cout << "Senior\n";
break;
default:
cout << "Invalid\n";
break;
}

A switch statement allows you to test an expression against a variety of cases. If a match is found, the code within begins to run. A case can be ended with the break keyword. When no case matches, default is used.




Discussion

No Comment Found