Comparison of Conditional Statements
Let's look at the execution flow of different conditional statements using the debugger.
We'll cover the following...
In this lesson, we’ll look at the execution flow of different conditional statements (if, if-else, and switch) by executing the code line-by-line using the debugger.
We’ll use the same program example for all conditional statements. This might appear repetitive, but the goal is to understand how each conditional statement executes and to bring more clarity on how it’s different from the others.
Instruction: Run and execute the codes step-by-step for all conditional statements (if, if-else, and switch).
Without removing the default breakpoint, click the restart button (
), and then to execute the code line-by-line, click the next button (
) to go to the next line.
Execution using the if statement
Even when the if condition is true, all the remaining if conditions are still checked.
Run the code below and see how it works.
#include<iostream>
using namespace std;
int main()
{
int marks;
cout << "The marks: ";
cin >> marks;
if(marks>=0 && marks<=100)
{
int G = marks/10;
if(G==10 || G==9)
cout << "A+" << endl;
if(G==8)
cout << "A" << endl;
if(G==7)
cout << "B+" << endl;
if(G==6)
cout << "B" << endl;
if(G==5)
cout << "C" << endl;
if(G==4)
cout << "D" << endl;
if(G<4)
cout << "F" << endl;
}
else
cout << "Invalid Input."<<endl;
return 0;
}
Execution using the if-else statement
When an if condition is true, the remaining else statements that follow that specific if condition are no longer checked.
Run the code below and see how it works.
#include<iostream>
using namespace std;
int main()
{
int marks;
cout << "The marks: ";
cin >> marks;
if(marks>=0 && marks<=100)
{
int G = marks/10;
if(G==10 || G==9)
cout << "A+" << endl;
else if(G==8)
cout << "A" << endl;
else if(G==7)
cout << "B+" << endl;
else if(G==6)
cout << "B" << endl;
else if(G==5)
cout << "C" << endl;
else if(G==4)
cout << "D" << endl;
else
cout << "F" << endl;
}
else
cout << "Invalid Input."<<endl;
return 0;
}
Execution using the switch statement
The control goes directly to the case that matches with the expression, and the statements are executed until a break statement is found. When found, the break statment returns the control to the statement right after the switch statement ends.
Run the code below and see how it works.
#include<iostream>
using namespace std;
int main()
{
int marks;
cout << "The marks: ";
cin >> marks;
if(marks>=0 && marks<=100)
{
switch(marks / 10)
{
case 10:
case 9:
{
cout << "A+" << endl;
break;
}
case 8:
{
cout << "A" << endl;
break;
}
case 7:
{
cout << "B+" << endl;
break;
}
case 6:
{
cout << "B" << endl;
break;
}
case 5:
{
cout << "C" << endl;
break;
}
case 4:
{
cout << "D" << endl;
break;
}
case 3:
case 2:
case 1:
case 0:
{
cout << "F" << endl;
break;
}
}
}
else
cout << "Invalid Input."<<endl;
return 0;
}