C++

C++ Decision Making

C++ Decision Making

Let us deep dive into C++ decision making constructs. At every important point of time, one has to take right decisions, be it life or a C++ program. In programming, flow is never completely sequential and  we need to make some decisions, evaluate some condition and based on the result, we execute the next block of code or skip it. For example if we need to search an element in a given list then if have to compare each element of list with the given number and if they are equal, we print it and exit else we move to the next element.

Decision-making statements in C++ mark the direction of the flow of program execution. Decision-making statements in C/C++ are as follows:

  1. if statement
  2. if..else statements
  3. nested if statements
  4. if-else-if ladder
  5. switch statements
  6. Jump Statements: 
    1. break
    2. continue
    3. goto
    4. return

if statement is the most basic and most used decision-making statement of the entire set. It evaluates a condition in if statement and if it is true then  executes the block else skip that block. Its syntax is as follows 

if(condition) 
{
   // Statements to execute if
   // condition is true
}

For e.g. 

if(status == true)
{
	...
}

if-else is the next decision making construct. It evaluates a condition in if statement and if it is true then executes the block immediately after if and if the condition is false then it executes the block immediately after else statement. Its syntax is 

if(condition) 
{
   	// Statements to execute if
   	// condition is true
}
else
{
	// Statements to execute if
    	// condition is false
	
For e.g. 

if(status == true)
{
	...
}
else
{
	...
}

nested if conditional is complex hierarchy of if conditionals. Here one if statement is the target of another if statement. Its syntax is as follows :

if (condition1) 
{
   // Executes when condition1 is true
   if (condition2) 
   {
      	// Executes when condition2 is true
      	if (condition3) 
   		{  
   			// Executes when condition3 is true
   		}
}

if-else-if ladder is used when user has to make a cascade of choices. Here the evaluation starts from the top if statement. The moment one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the C else-if ladder is bypassed. If no condition is true, then the final else statement will be executed. Its syntax is as follows

if (condition)
{
	... 
}
else if (condition)
{
    ...
}
.
.
else
{
	...
}

Let us give its practical demonstration. The following program gives grade of student depending upon the marks Copy the following code in a file say ifelseifLadder.cpp.

#include <iostream>
using namespace std;

int main()
{
	string grade;
    float percentage;

	//take percentage as input from user
    cout<<"Enter your final percentage: ";
    cin>>percentage;
	
	if (percentage > 90.0)
	{
		grade = "A1";
		cout<<"You have got "<<grade<<"."<<endl;
	}	 
	else if(percentage > 80.0)
	{
		grade = "A2";
		cout<<"You have got "<<grade<<"."<<endl;
	} 
	else if(percentage > 70.0)
	{
		grade = "B1";
		cout<<"You have got "<<grade<<"."<<endl;
	} 
	else if(percentage > 60.0)
	{
		grade = "B2";
		cout<<"You have got "<<grade<<"."<<endl;
	} 
	else if(percentage > 50.0)
	{
		grade = "C1";
		cout<<"You have got "<<grade<<"."<<endl;
	} 
	else if(percentage > 40.0)
	{
		grade = "C2";
		cout<<"You have got "<<grade<<"."<<endl;
	} 
	else
	{
		grade = "F";
		cout<<"You have got "<<grade<<"."<<endl;	
	} 
}//end main ()

Now compile it and run it to see the output.

(base) 22:35:42:~ % g++ ifelseifLadder.cpp 

(base) 22:36:11:~ % ./a.out 

Enter your final percentage: 98

You have got A1.

Jump Statements in C/C++ are used to hop on the flow to some other random statement without evaluating any condition. C++ has four types of jump statements that are given below:

break

continue

go to

return

break statement is used to terminate the loop. As soon as the break statement is encountered from within a loop, the loop iterations stops, and control returns from the loop immediately to the first statement after the loop. Its syntax is 

break;

continue is just opposite to that of the break statement meaning instead of terminating the loop, it forces to execute the next iteration of the loop. The continue statement forces the loop to continue or execute the next iteration. When the continue statement is executed in the loop, the code inside the loop following the continue statement will be skipped and the next iteration of the loop will begin. Its syntax is 

continue;

return statement marks end of execution of called function and returns the flow of the execution back to the parent function. This statement may or may not need any conditional statements. The return statement may or may not return anything for a void function, but for a non-void function, a return value is returned for sure. Its syntax is 

return[expression];

goto statement is an unconditional jump statement where in code jumps to the satement marked by label. Its syntax is shown below :

....
goto label;  

...

label: 
...

Here the first line tells the compiler to go to or jump to the statement marked as a label. The label is a user-defined identifier that marks the target statement. The statement immediately followed after ‘label:’ is the destination statement.

The ternary operator of ? : --> this operator is used as a single line replace of if else loop. It has the following general form −

exp1 ? exp2 : exp3;

where exp1, exp2, and Exp3 are expressions. The evaluation pattern is that first exp1 is evaluated. If it is true, then exp2 is evaluated and that becomes the final value. If exp1 is false, then exp3 is evaluated and its value becomes the final value of the expression. Let us see its application in a small program. Copy the following code in a file say ternaryOpDemo.cpp.

#include <iostream>
#include <string>

#define THRESHOLD 6000
using namespace std;

int main() 
{
	int salary;

  	// take input from users
  	cout << "Enter your monthly salary: ";
  	cin >> salary;

  	// ternary operator checks if
  	// marks is greater than 40
  	string result = (salary <= THRESHOLD) ? "below Poverty line" : "above poverty line";

  	cout << "You are " << result << "."<<endl;

  	return 0;
}//end main ()

Now compile and execute the program. You can see we have replaced the if else statement with ternary operator

(base) 22:08:56:~ % g++ ternaryDemo.cpp
(base) 22:08:57:~ % ./a.out            
Enter your monthly salary: 5000
You are below Poverty line.