What Is Decision Making In C/C++?

What Is Decision Making In C/C++?
What Is Decision Making In C/C++?

Introduction

Decision making is an integral part of our life, everyday we make some decisions consciously or unconsciously, and all these decisions are based on some 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.

What is a Decision Making Statement? 

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.

Decision making in C/C++ can be done by following statements.

  • If statement
  • If..else statement
  • if..else-if statement
  • Nested if statement
  • Switch statement

This blog will discuss all these statements for decision-making in C/C++ with syntax flowcharts and code for each statement.

If statement

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");
}

C++:

#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;;
}

Output:

Inside if block
N is greater than 10
if block ended

As the condition present in the if statement evaluates to true the statements inside the if are executed.

If else in C/C++

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"); 
    }   
}

C++:

#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";
    }
}

Output:

Enter a number:11
Given number is odd 

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.

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;
}

#include <iostream>
using namespace std;

int main() {
    int number;
    cin >> number;
    if (number > 0) {
        cout << "You entered a positive integer\n";
    } 
    else if (number < 0) {
        cout << "You entered a negative integer\n";
    } 
    else {
        cout << "You entered 0.\n";
    }
    return 0;
}

input:-11
Output: You entered a negative integer

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.

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");
        }
    }   
}

C++

#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;
        }
    }   
}

Nested If else in C/C++

Nested if else can also be used for decision making in C/C++.When a series of decisions are required, we can use nested if else in C/C++.

Syntax:

if(condition1)
{   //execute if condition1 is true
    if(condition2)
    { 
      //execute if condition2 is true
       statements
    }
    else
    {
       //execute if condition2 is false
       statements
    }
}
else
{
    //execute if condition1 is false
    statements
}

For example: in this program, we will check if a number is divisible by 10 or not if it is divisible by 10 it is equal to 10 or not.

C:

#include<stdio.h>
int main()
{
    int num=10;
    if(num%10==0)
    {
        if(num==10)
        {
            printf("The number is:%d\n",num);
        }
        else
        {
            printf("The number is divisible by 10 but not 10");
        }
    }
    else
    {
        printf("The number is not divisible by 10");
    }
    return 0;
}

C++:

#include<iostream>
using namespace std;
int main()
{
    int num=10;
    if(num%10==0)
    {
        if(num==10)
        {
            cout<<"The number is:"<<num;
        }
        else
        {
            cout<<"The number is divisible by 10 but not 10";
        }
    }
    else
    {
        cout<<"The number is not divisible by 10";
    }
    return 0;
}

Output:

The number is:10

Switch Case Statement

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;
}

Jump Statements in C/C++

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.

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;
        }
    }
}

C++:

#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;
        }
    }
}

Output:

Array contains negative value.

Continue in C/C++

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]);
    }
}

C++:

#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]<<" ";
    }
}

Output:

5 6 0 3 1 

Goto Statement in C/C++

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.

Syntax:

goto label;
.        	
.       	
.        	
label:

OR

label:  
.        	
.      	
.  	
goto label;

Example: Check if a number is even or not and print accordingly using the goto statement.

C:

#include <stdio.h>

int main()
{
    int number;
    scanf("%d",&number);
    if (number % 2 == 0)
        goto printeven;
    else
        goto printodd;

printeven:
    printf("Even number");
    return 0;

printodd:
    printf("Odd number");
    return 0;
}

C++:

#include <iostream>
using namespace std;

int main()
{
    int number;
    cin >> number;
    if (number % 2 == 0)
        goto printeven;
    else
        goto printodd;

printeven:
    cout << "Even number";
    return 0;

printodd:
    cout << "Odd number";
    return 0;
}

Output:

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.

Return statement in C/C++

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;
}

C++:

#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;
}

Output:

The sum is 30

Frequently Asked Questions

What is decision making statements?

Decision-making statements in a programming language decide the direction and the flow of the program. Decision-making statements 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

What are the different decision-making statements in C/C++?

Decision making in C/C++ can be done by following statements.
If statement
If..else statement
Nested if statement
if..else-if statement
Switch statement
Jump statements

What is the difference between the if and if else statement?

The if statement is a decision-making structure that consists of an expression followed by one or more statements. The if else is a decision-making structure in which the if statement can be followed by an optional else statement that executes when the expression is false.

What is nested if in 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.

Key Takeaways

This article describes the various statements for decision making in C/C++ such as if, if-else, nested if else statement,if-else-if ladder, switch and jump statements. The article covers the syntax, flowchart, and programs for each of these decision making statements in C/C++.

If you want to test out your understanding of decision making in C/C++ you should try to implement The FizzBuzz program.

If you are preparing for interviews at top product based companies then CodeStudio 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, Microsoft.

At CodeStudio you get interview problems, interview experiences, and practice problems that can help you to land your dream job.  

By Pranchal Agrahari