Decision making is an integral part of our life, everyday we make some decisions consciously or unconsciously, and all these decisions are based on calculations and comparisons. Similarly, in programming, we need decision-making to control and regulate the execution of our code blocks.
For example, if we want to print the even number from a given array, then we need to decide for each element to print something or not. To deal with these kinds of scenarios in C/C++, we need to know about decision-making in C/C++.
We have various statements for decision making in C/C++ like if ,if-else,nested if,if-else-if. But before getting into the decision making statements in C/C++, we should discuss what is decision making.
Decision-making statements decide the direction and the flow of the program. They are also known as conditional statements because they specify conditions with boolean expressions evaluated to a true or false boolean value. If the condition is true, a given block of code will execute; if the condition is false, the block will not execute.
Need of Conditional Statements
Conditional statements in C/C++ are control structures that allow the program to execute different blocks of code based on different conditions.
Conditional statements are needed for the following reasons:-
Branching: These statements allow the program to take different paths based on certain conditions.
Control flow: They allow you to control the order in which statements are executed. By using conditional statements, you can introduce loops, nested conditions, and other complex control structures in your program.
Handling different cases: Conditional statements provide a mechanism to check for specific conditions and execute the corresponding code block. For example, you might want to handle edge cases, handle errors, or exceptions.
Event-driven programming: In event-driven programming, conditional statements allow you to respond to various user interactions, such as button clicks, by executing specific code based on the events.
Types of Conditional Statements in C/C++
1. If in C/C++
The if statement is the most simple and straightforward decision making a statement. It is used to determine whether a particular block of code will be executed or not. If a particular condition is true, then a block of statements is executed, otherwise not.
Syntax:
if(condition)
{
//Statement to be executed
//if condition is true
Statement 1;
Statement 2;
. .
. .
Statement n;
}
Here the condition after evaluation would be either true or false depending on which block of code inside it would be executed. If we don’t provide the curly braces ‘{ }‘ then by default, it will consider the first line as the body.
Example:
if(condition)
Statement 1;
Statement 2;
The above snippet, only first would consider being inside if and would be executed if the condition is true.
Example:
C:
#include<stdio.h>
int main()
{
int n=20;
if(n>10)
{
printf("Inside if block\n");
printf("N is greater than 10\n");
}
printf("if block ended\n");
}
#include<iostream>
using namespace std;
int main()
{
int n=20;
if(n>10)
{
cout<<"Inside if block"<<endl;
cout<<"N is greater than 10"<<endl;
}
cout<<"if block ended"<<endl;;
}
You can also try this code with Online C++ Compiler
The if statement tells us that if a condition is true, a block of statements will be executed; if the condition is false, the block of statements will not be executed.
But what if the condition is false and we want to do something different? This is where the if-else statement comes into play. When the condition is false, we can use the else statement in conjunction with the if statement to run a code block.
Syntax:
if(condition)
{
//Execute this block
//if condition is true
}
else
{
//Execute this block
//if condition is false
}
Example: Program to check if a given number is even or odd.
C:
#include<stdio.h>
int main()
{
int n;
printf("Enter a number:");
scanf("%d", &n);
if(n%2==0)
{
printf("Given number is even \n");
}
else
{
printf("Given number is odd \n");
}
}
#include<iostream>
using namespace std;
int main()
{
int n;
cout<<"Enter a number:";
cin>>n;
if(n%2==0)
{
cout<<"Given number is even"<<endl;
}
else
{
cout<<"Given number is odd";
}
}
You can also try this code with Online C++ Compiler
In the above example, input 11 is odd, so the else statement is executed. You can try to run the above program for different inputs like 2,5,10 to understand the working of if-else.
3. if-else-if ladder in C/C++
If-else-if is used for decision-making in C/C++ when we have multiple options to choose from. The if statements are executed from the top down. When one of the conditions controlling if is satisfied, the statement associated with that if is executed, and the rest of the ladder is skipped. If none of the conditions is satisfied, the last else statement is executed.
Syntax:
if(condition1) {
// Executes if condition 1 is true
}
else if (condition2) {
// Executes if condition 2 is true
}
else if (condition3) {
// Executes if condition 3 is true
}
...
else {
// Executes if all conditions become false
}
Example: Check whether an integer is positive, negative, or zero.
#include <stdio.h>
int main() {
int number;
scanf("%d",&number);
if (number > 0) {
printf("You entered a positive integer\n");
}
else if (number < 0) {
printf("You entered a negative integer\n");
}
else {
printf("You entered 0.\n");
}
return 0;
}
Suppose we enter -11, then the first condition is checked, and since the number is smaller than 0. Now the next else-if is checked, and the number is smaller than 0 hence the statement inside the else-if is executed.
4. Nested if in C/C++
Nested if statements are the if statements that are inside another if statement. Both C and C++ allow us to use an if statement inside another if statement. Nested if statements come in handy for decision making in C/C++ when we need to make a series of decisions.
Syntax:
if (condition1)
{
// Executes when condition1 is true
if (condition2)
{
// Executes when condition2 is true
}
}
Example:
In this example, we would check if a number is greater than 10 and if it is greater than 10 we will check if it is greater than 20 or not.
C:
#include<stdio.h>
int main()
{
int n=21;
if(n>10)
{
printf("Number is greater than 10 \n");
if(n>20)
{
printf("Number is greater than 20 also \n");
}
}
}
#include<iostream>
using namespace std;
int main()
{
int n=21;
if(n>10)
{
cout<<"Number is greater than 10"<<endl;
if(n>20)
{
cout<<"Number is greater than 20 also"<<endl;
}
}
}
You can also try this code with Online C++ Compiler
A switch case statement is a simplified form of the Nested if-else statement, which is very frequently used for decision-making in C/C++, it helps avoid long chains of if-else-if. A switch-case statement evaluates an expression against multiple cases to identify the block of code to be executed.
switch (expression) {
case constant1:
// code to be executed if the expression equals constant1
break;
case constant2:
// code to be executed if the expression equals constant2
break;
case constant3:
// code to be executed if the expression equals constant3
break;
...
default:
// code to be executed if the expression does not match any constants
}
The expression is evaluated once and must evaluate to a “constant” value and compared with the values of each case label(constant 1, constant 2, .., constant n).
If a match is found corresponding to a case label, then the code following that label is executed until a break statement is encountered or the control flow reaches the end of the switch block.
If there is no match, the code after default is executed.
Note:
The default statement is optional. If there is no match, then no action takes place and the control reaches the end of the switch block in absence of the default statement.
The break statement is also optional, and the code corresponding to all case labels gets executed after the matching case until a break statement is encountered.
Example: Program to identify numbers between 1-5
#include <stdio.h>
int main()
{
int num=10;
switch (num)
{
case 1: printf("Number is 1");
break;
case 2: printf("Number is 2");
break;
case 3: printf("Number is 3");
break;
case 4: printf("Number is 4");
break;
case 5: printf("Number is 5");
break;
default: printf("Invalid input");
break;
}
return 0;
}
#include <iostream>
using namespace std;
int main()
{
int num=3;
switch (num)
{
case 1: cout<<"Number is 1";
break;
case 2: cout<<"Number is 2";
break;
case 3: cout<<"Number is 3";
break;
case 4: cout<<"Number is 4";
break;
case 5: cout<<"Number is 5";
break;
default: cout<<"Invalid input";
break;
}
return 0;
}
You can also try this code with Online C++ Compiler
Conditional Operator is used for executing different lines of code depending on a single condition. This is similar to If-else block, it just makes your code more concise.
Syntax:
(condition) ? execute this if true : execute this if false;
Example:
The following code in C and C++ uses the conditional operator to assign value to an integer.
C:
#include<stdio.h>
int main(void) {
int y = 10;
int x = (y==10) ? 5 : 10;
printf("%i", x);
return 0;
}
You can also try this code with Online C++ Compiler
Jump statements cause an unconditional jump to another statement elsewhere in the code. They are used primarily to interrupt switch statements and loops.
There are four types of jump statements for decision-making in C/C++.
break
continue
goto
return
We will discuss these jump statements for decision-making in C/C++ in the following section.
a. Break Statement
In C/C++, the break statement terminates the loop or switch statement when encountered, and control returns from the loop or switch statement immediately to the first statement after the loop.
Syntax:
break;
Break statements are generally used when we are unsure about the number of iterations of a loop, and we want to terminate the loop based on some conditions.
Example: Check if an array contains any negative value.
C:
#include <stdio.h>
int main()
{
int arr[] = {5, 6, 0, -3, 3, -2, 1};
int size = 7; // No of elements in array
for (int i = 0; i < size; i++)
{
if (arr[i] < 0)
{
// Array contains a negative value, so break the loop
printf("Array contains negative value.");
break;
}
}
}
#include <iostream>
using namespace std;
int main()
{
int arr[] = {5, 6, 0, -3, 3, -2, 1};
int size = 7; // No of elements in array
for (int i = 0; i < size; i++)
{
if (arr[i] < 0)
{
// Array contains a negative value, so break the loop
cout << "Array contains negative value.";
break;
}
}
}
You can also try this code with Online C++ Compiler
Continue is used for decision-making in C/C++ and is just opposite to the break statement; instead of terminating the loop, it forces it to execute the next iteration of the loop.
When the continue statement is executed, the code following the continue statement is skipped, and controls move to the next iteration.
Syntax:
continue;
Example: Print all non-negative values in an array.
C:
#include <stdio.h>
int main()
{
int arr[] = {5, 6, 0, -3, 3, -2, 1};
int size = 7; // no of elements in array
for (int i = 0; i < size; i++)
{
if (arr[i] < 0)
{
// If arr[i] < 0, then skip the current iteration i.e no statements following
// continue will be executed.
continue;
}
printf("%d ",arr[i]);
}
}
#include <iostream>
using namespace std;
int main()
{
int arr[] = {5, 6, 0, -3, 3, -2, 1};
int size = 7; // no of elements in array
for (int i = 0; i < size; i++)
{
if (arr[i] < 0)
{
// If arr[i] < 0, then skip the current iteration i.e no statements following
// continue will be executed.
continue;
}
cout<<arr[i]<<" ";
}
}
You can also try this code with Online C++ Compiler
The goto statement is used to alter the normal sequence of program execution by transferring control to some other part of the program. The goto statement can be used to jump from anywhere to anywhere within a function.
Input1:
7
Output1:
Odd number
Input2:
8
Output2:
Even number
Note: In modern programming, the goto statement is considered harmful and bad programming practice as it can jump to any part of the program, making the program’s logic complex and tangled. In most cases, the goto statement can be replaced by using break or continue.
d. Return
The return statement terminates a function’s execution and transfers program control back to the calling function. It can also specify a value to be returned by the function. A function may contain one or more return statements.
Syntax:
return [expression];
Example:
C:
#include <stdio.h>
// int return type function to calculate sum
int SUM(int a, int b) {
int s1 = a + b;
return s1;
}
// void returns type function to print
void Print(int s2) {
printf("The sum is %d",s2);
return;
}
int main() {
int n1 = 10;
int n2 = 20;
int summ = SUM(n1, n2);
Print(summ);
return 0;
}
#include <iostream>
using namespace std;
// int return type function to calculate sum
int SUM(int a, int b) {
int s1 = a + b;
return s1;
}
// void returns type function to print
void Print(int s2) {
cout << "The sum is " << s2;
return;
}
int main() {
int n1 = 10;
int n2 = 20;
int summ = SUM(n1, n2);
Print(summ);
return 0;
}
You can also try this code with Online C++ Compiler
What is the need of decision making statements in C?
Decision-making statements are used for controlling the flow of a C/C++ program. Control structures allow you to take decisions based on certain conditions and run the corresponding code blocks.
Which statement is used for decision making operations?
Some commonly used decision-making statements in C/C++ are, if-else, if-else-if ladder, switch, conditional operator, and jump statements such as break, continue, and return. They are used for changing the flow of a program based on certain conditions.
What are the conditions necessary for decision-making?
Control structures such as if-else-if ladders and switch statements are used for making decisions in C/C++. If a certain condition is true, these control structures execute the corresponding blocks of code allowing you to make decisions based on different parameters.
Conclusion
This article describes the various statements for decision-making in C/C++ such as if, if-else, nested if else statements,if-else-if ladder, and switch and jump statements. The article covers the syntax, flowchart, and programs for each of these decision-making statements in C/C++.
If you are preparing for interviews at top product-based companies then Coding Ninjas Studio is your one-stop destination. It is a great platform developed by some aspiring enthusiasts and working professionals who have experience in companies like Google, Amazon, and Microsoft.
At Coding Ninjas Studio you get interview problems, interview experiences, and practice problems that can help you to land your dream job.