Switch Statement in C++ with Example

In C++ programming, the switch statement is used to execute one block of code out of multiple blocks of code.

Switch statement Syntax in C++.

switch (expression)
    {
    case /* constant-expression */:
        /* code */
        break;
    case /* constant-expression */:
        /* code */
        break;
    default:
         /*expression not matching with any constant-expression */
        /* code */
    }

Working of switch statement:
  • The switch expression is evaluated once and then compared with the constant-expression value of each case.
  • If the correct match is found, the associated code of that particular case is executed until the break statement in encountered. 
  • When there is no matching expression then default code block is executed.

Switch Statement Flowchart

switch statement flowchart
Switch Statement Flowchart

Example: This C++ program is printing the weekday based on the number.

//C++ Example switch statement
#include<iostream>
using namespace std;

int main(){

    int day;
    cout<<"Enter a day number: ";
    cin>>day;

    switch (day)
    {
    case 1:
        cout<<"Today is Monday";
        break;
    case 2:
        cout<<"Today is Tuesday";
        break;
    case 3:
        cout<<"Today is Wednesday";
        break;
    case 4:
        cout<<"Today is Thursday";
        break;
    case 5:
        cout<<"Today is Friday";
        break;
    case 6:
        cout<<"Today is Saturday";
        break;
    case 7:
        cout<<"Today is Sunday";
        break;                    
    default:
        cout<<"No match found";
    }
    
    return 0;
}
Output 1:
Enter a day number: 5
Today is Friday

Output 2:
Enter a day number: 9
No match found

Here in output 2, the default code block is executed because there is no matching constant-expression matching with value 9 in the switch case.


Use break keyword in switch.

The break statement is optional in switch and it is used to come out of switch block and ignore the execution of reset of the cases. If you don't mention break statement at the end of each switch case then compiler keep executing next case until it found a break statement. 

Example:
//C++ Example switch statement
#include<iostream>
using namespace std;

int main(){

    int day;
    cout<<"Enter a day number: ";
    cin>>day;

    switch (day)
    {
    case 2:
        cout<<"\nToday is Tuesday";
        break;
    case 3:
        cout<<"\nToday is Wednesday";
        /*break statement is missing here*/
    case 4:
        cout<<"\nToday is Thursday";
        break;
    case 7:
        cout<<"\nToday is Sunday";
        break;                    
    default:
        cout<<"\nNo match found";
    }
    
    return 0;
}
Output:
Enter a day number: 3

Today is Wednesday
Today is Thursday

Here in the output, you can observe that when we have selected a case not having a break statement then code executed the next block also and stop when it found a break statement. 

Note: You can perform the same task using if...else statement in C++ but in few cases switch case is use because it is more easy to read and understand. (alert-passed)


Few examples of switch case problem:

Break and Continue Statement in C++

In C++ programming, break and continue statements are used inside loops and switch statements to manipulate the normal execution of the loop and switch statements.

C++ Break Statement.

A break statement is used to bring the control of the program out of the loop. It is basically used to jump out of a running loop. 

syntax: break;


Flowchart of a break statement.

break statement flowchart
break statement Flowchart

Example:
//C++ Example of break statement
#include<iostream>
using namespace std;

int main(){

    cout<<"Print number using for loop"<<endl;
    for(int i = 0; i <= 10; i++){
        if(i == 5){
            break;
        }
        cout<<i<<" ";
    }

    int i = 1;
    
    cout<<"\nPrint number using while loop"<<endl;
    while(i <= 10){
        if(i == 4){
            break;
        }
        cout<<i<<" ";
        i++;
    }
    return 0;
}
Output:
Print number using for loop
1 2 3 4
Print number using while loop
1 2 3

Here in the above example, you can see that both the loop condition is written for printing value from 1 to 10 but both programs jump out of the loop as soon as the break condition is satisfied. 

C++ Continue statement.

The continue statement is used to skip the current iteration of the loop if the specified condition is true and continue with the next iteration of the loop. 
syntax: continue;

Flowchart of a continue statement.

continue flowchart
continue Flowchart
Example:
//C++ Example of continue statement
#include<iostream>
using namespace std;

int main(){

    for(int i = 1; i <= 10; i++){
        if(i == 5){
            continue;
        }
        cout<<i<<" ";
    }

    return 0;
}
Output:
1 2 3 4 6 7 8 9 10

Here, if you observe the output then you can see that value 5 is not printed by the loop because that condition is evaluated true for the continue statement so it skips the remaining part of the code and moves to the next iteration.

do...while Loop in C++ with Example

In the previous post, we covered for loop and while loop, and in this post, we are going to discuss the do...while loop which is a variant of the while loop. 


C++ do...while Loop.

The do...while is known as the exit control loop because the loop executes the block of code once before evaluating the given condition. After executing the code block for the first time it will work like a normal while loop and run the loop as long as the condition is true.

Syntax of do...while Loop.
do {
  // code block
}
while (condition);

Flowchart of do...while loop.
flowchart of do while loop
do...while loop flowchart
Example:
//C++ Example of do while loop 
#include<iostream>
using namespace std;

int main(){

    int i = 1;
    //do while loop
    do{
        cout<<"Do While Loop Code Block";
    }while(i <= 0);

    return 0;
}
Output:
Do While Loop Code Block

Here you can see that the code block is present inside the body of do...while loop executed one time even if the condition is false because the do-while loop checks the condition later after the first execution.  

Example: Program to print multiplication table
//C++ Example of do while loop to print 5 number
#include<iostream>
using namespace std;

int main(){

    int i = 1, num;
    cout<<"Enter a value: ";
    cin>>num;
    //do while loop
    do{
        cout<<num<<" x "<<i<<" = "<<num * i<<endl;
        i++;
    }while(i <= 10);

    return 0;
}
Output:
Enter a value: 5
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50
Warning: Never write a condition for your loop that will be always evaluated as true else your loop will keep on running for infinite times until your memory gets full. (alert-warning)

While Loop in C++ with Example

In programming, loops are used to repeatedly execute the same block of code multiple times as long as the given condition is true. In C++, we have three types of loops and these are:

Here in this post, we are going to discuss while loop in detail.

C++ While Loop.

While loop is used to execute the same block of code repeatedly as long as the specified condition is true. While loop is an entry control loop which means it checks the condition each time before entering the loop. 
While loops are used when we don't know the exact count of how many times the loop is going to run. (alert-passed)

while loop syntax: 
while (condition){
  //code block
}
Here the while loop evaluates the specified condition and if the condition is true then it will execute the block of code present inside the body of the while loop. While the loop will check the condition each time before executing the code block and this process continues until the condition become false. (alert-success)

while loop flowchart
Flowchart of while loop in C++

C++ Example: Program to print the first five natural numbers.

//C++ Example of while loop to print 5 number
#include<iostream>
using namespace std;

int main(){

    int i = 1;
    //while loop
    while(i <= 5){
        cout<<i<<" ";
        i++;
    }

    return 0;
}
Output:
1 2 3 4 5

Here in this program, we are executing the code block and printing natural numbers as long as the value of variable i is less than or equal to 5
Warning: Never write a condition for your loop that will be always evaluated as true else your loop will keep on running for infinite times until your memory gets full. (alert-warning)

Few example programs:

For Loop in C++ with Examples

In programming, loops are used to repeatedly execute the same block of code multiple times. It is used when we have to perform some repetitive task. In C++, we have three types of loops available and these are:

The while and do...while loops are used when we don't know the exact count of how many times the loop is going to run whereas for loop is used when we know the exact count. Here we are going to discuss for loop in detail with many examples. 

C++ For Loop Syntax:

for (initialization; condition; update) {
    // code block to execute
}

For loop is an entry control loop which means the given condition is evaluated first each time before entering inside the loop. In the above syntax:
  • initialization: Initialize a variable and executed only one time before entering the loop body.
  • condition: This condition is checked every time and if it returns true then only the code block inside the body of the loop is executed.
  • update: It is executed every time and updates the value of the initialized variable.

Flowchart of For Loop in C++
Flowchart of For Loop
Flowchart of for Loop

C++ Example 1: Print the first five natural numbers.
//C++ For Loop example to print natural number
#include<iostream>
using namespace std;

int main(){
    //print 5 natural number
    for(int i = 1; i <= 5; i++){
        cout<<i<<endl;
    }
    return 0;
}
Output:
1
2
3
4
5

Here, we have initialized the variable i with our first value which is 1, and then we have defined a condition (i <= 5) that we will print the value of i till this condition is true and each time after printing the value of i we are updating the value of i by 1 using increment operator. 

C++ Example 2: Print the sum of 10 natural numbers

//C++ For Loop example to print sum of n natural number
#include<iostream>
using namespace std;

int main(){

    int sum = 0;
    //print the sum of 10 natural numbers
    for(int i = 1; i <= 10; i++){
        sum += i;
    }
    cout<<sum;

    return 0;
}
Output:
55
Here we have initialized the variable i with 1 and given a condition (i <= 10) which is indicating that the loop is going to run 10 times and each time it is taking the value of i and adding the value with the sum variable. After the for loop gets terminated program will print the sum of the first 10 natural numbers.

Nested For Loop in C++

When one for loop is present inside another for loop then it is called a nested for loop. The inner loop will execute completely for each iteration of the outer loop. 

Example of Nested for Loop.
//C++ Example for Nested For Loop
#include<iostream>
using namespace std;

int main(){

    //outer loop
    for(int i = 1; i <= 3; i++){
        cout<<"\nThis is outer loop "<<i;
        //inner loop
        for(int j = 1; j <= 3; j++){
            cout<<"\nThis is inner loop "<<j;
        }
        cout<<"\n";
    }

    return 0;
}
Output:
This is outer loop 1
This is inner loop 1
This is inner loop 2
This is inner loop 3

This is outer loop 2
This is inner loop 1
This is inner loop 2
This is inner loop 3

This is outer loop 3
This is inner loop 1
This is inner loop 2
This is inner loop 3


Foreach Loop in C++

The for-each loops are used to iterate over the elements of an array or any other data sets. This loop reduces the chances of error and increases the overall performance of the code.

Syntax of a for-each loop:
for (type variable name : array_name){
  //code block
}

Example of a for-each loop:
//C++ Example of foreach Loop
#include<iostream>
using namespace std;

int main(){

    int arr[] = {3, 5, 9, 1, 4};
    //printing array element
    for(int i : arr){
        cout<<i<<" ";
    }

    return 0;
}
Output:
3 5 9 1 4

The for-each loop is very easy to use but there are many disadvantages also like you cannot traverse the array in the reverse direction and you cannot skip any element while traversing the array. (alert-warning)


Few example problems: 

if...else statement in C++

In this post, we will learn about C++ if...else conditional statement which is used for decision-making purposes in programming. In a decision-making process, we have to choose one out of many available options and our decision is based upon certain conditions. 


In programming, let's say you have two blocks of code and you want to execute the first block of code only if a certain condition is true else you will execute the second block of code. In these kinds of cases, you require a condition statement like if...else


There are three kinds of if...else statement available in C++.

  • if statement.
  • if...else statement.
  • if...else if...else statement.


if statement in C++.

The if statement evaluates the given boolean condition and if the condition returns true then the code present inside the body ({ }) of if gets executed and if the condition returns false then the code present inside the body of if gets skipped and the program continues to execute the remaining statements. 

Syntax of if statement:
if(condition){
  //statement(s) to execute if condition is true
}
if statement flowchart
Flowchart of if statement

C++ Example of if statement.
//C++ if statement Example 
#include<iostream>
using namespace std;

int main(){
    
    int num;

    cout<<"Enter number:";
    cin>>num;

    if(num % 2 == 0){
        cout<<"The Entered number is an even number.";
    }
    cout<<"\nThe value of num: "<<num;

    return 0;
}
Output 1:
Enter number:24
The entered number is an even number.
The value of num: 24
The user entered 24 which is an even number and it is satisfying our if condition and returns true so the statement inside the if body gets executed. 

Output 2:
Enter number:21
The value of num: 21
The user entered 21 which is an odd number and it is not satisfying our if condition and returns false so the statement inside the if body will get not executed.

if...else statement in C++.

In if...else statement the given boolean condition is evaluated and if it return true then the code present inside the body of if get executed and if the condition return false then the code present inside the body of else get executed.

Syntax of if...else statement: 
if(condition){
  //statement(s) to execute if condition is true
}
else{
  //statement(s) to execute if condition is false
}
if else statement flowchart
Flowchart of if...else statement

C++ Example of if...else statement.
//C++ if..else statement Example 
#include<iostream>
using namespace std;

int main(){
    
    int num;

    cout<<"Enter number:";
    cin>>num;

    if(num % 2 == 0){
        cout<<"The Entered number is even number.";
    }
    else{
        cout<<"The Entered number is an odd number.";
    }
    cout<<"\nThe value of num: "<<num;

    return 0;
}
Output 1:
Enter number:33
The entered number is an odd number.
The value of num: 33
The user have entered 33 which is an odd number so condition return false and code inside else block get executed.

Output 2:
Enter number:36
The entered number is even number.
The value of num: 36
The user has entered 36 which is an even number so condition return true and code inside if block get executed and skipped the else part.

if...else if...else statement in C++.

The if...else if...else statement is used when we have more than two block of code to choose from. In this case, we have multiple conditions to evaluate and whichever condition return true that block of code get executed and if non of the condition is true then the last else block get executed. 

Syntax of if...else if...else statement: 
if(condition 1){
  //statement(s) to execute if condition 1 is true
}
else if(condition 2){
  //statement(s) to execute if condition 2 is true
}
else if(condition 3){
  //statement(s) to execute if condition 3 is true
}
else{
  //statement(s) to execute if all conditions false
}
if else if else flowchart
Flowchart of if...else if...else statement

C++ Example of if...else if...else statement.
//C++ if..else if else statement Example 
#include<iostream>
using namespace std;

int main(){
    
    int mark;

    cout<<"Enter the mark of the student: ";
    cin>>mark;

    if(mark >= 90){
        cout<<"Student got Grade A";
    }
    else if(mark >= 70 && mark < 90){
        cout<<"Student got Grade B";
    }
    else if(mark > 50 && mark < 70){
        cout<<"Student got Grade C";
    }
    else{
        cout<<"Student got Grade D";
    }

    cout<<"\nTotal mark of the student: "<<mark;

    return 0;
}
Output 1:
Enter the mark of the student: 70
Student got Grade B
Total mark of the student: 70
When the user enter a value 70 then our second condition got satisfied so compiler execute second block of code and print "Student got Grade B".

Output 2:
Enter the mark of the student: 40
Student got Grade D
Total mark of the student: 40
When the user enter a value 40 then none of the condition got satisfied so compiler execute else block of code and print "Student got Grade D".
Note: There can be more than one else if statement in our code but only one if and else statement is allowed. (alert-success)


Nested if...else statement.

Nested if...else is a condition in which we use if..else statement inside another if...else statement. 

Syntax of Nested if...else statement: 
if(condition 1){
  //statement(s) to execute if condition 1 is true
  if(condition 1A){
    //statement(s) to execute if condition 1A is true
  }
  else{
    //statement(s) to execute if condition 1A is false
  }
}
else if(condition 2){
  //statement(s) to execute if condition 2 is true
}  
else{
  //statement(s) to execute if all conditions false
}

C++ Example of if...else if...else statement.
//C++ Nested if..else if else statement Example 
#include<iostream>
using namespace std;

int main(){

    int num;

    cout<<"Enter a number: ";
    cin>>num;

    if(num % 2 == 0){
        if(num % 5 == 0){
            cout<<"Number is Even and Divisible by 5";
        }
        else{
            cout<<"Number is Even and not Divisible by 5";
        }
    }
    else{
        if(num % 5 == 0){
            cout<<"Number is Odd and Divisible by 5";
        }
        else{
            cout<<"Number is Odd and not Divisible by 5";
        }
    }

    return 0;
}
Output:
Enter a number: 25
Number is Odd and Divisible by 5

DON'T MISS

Nature, Health, Fitness
© all rights reserved
made with by templateszoo