C++ Switch Statement and Loops

Introduction:

Welcome to the 5th tutorial of this short tutorial series for beginners in C++. We are going to have some more fun with the control structures in this part. We will introduce you to the “Switch” statement and in the later part will move to the iteration structures such as “for”, “while”, “do while” loops. We will also explain some important statements which can be used inside a loop to control the iterations. These statements include “continue” and “break”.

Note: We will develop a basic console application to in order to explain these concepts, e.g


#include <iostream>

using namespace std;

int main()

{

	//code here

	return 0;

}

 

Let’s have a quick glance at the contents:

Contents:

1- switch

2- loops

a. for

b. while

c. do while

3- break

4- continue

5- Project “Calculator” and “Table”

 

1 – switch:

The “switch” statement is followed by a block of statements. A block of statements is a multiple number of statements which are inside a block. Switch statement has the same functionality as multiple “else if” statements but it is more organized and easier to use. Switch is also called a selective structure. Have a look at following example:


int roll;

cout<<"Enter the digit:";

cin>> roll;

switch(roll)

{

	case 10:

		cout<<"You Entered ten.";

		break;

	case 20:

		cout<<"You Entered twenty.";

		break;

	case 30:

		cout<<"You Entered thirty.";

		break;

	default:

		cout<<"You did not enter 10,20 or 30";

}

Here in this example, “roll” is variable whose value will be passed by the user. Inside the switch statement, this roll will be compared to the first constant which is “case 10:”. If the value of roll is 10, the statement “You Entered ten.”, will be executed and after that the break statement will cause the control to exit the switch block without executing the remaining statements as shown:

Now if user enters something other than 10,20,30 which do not have any corresponding execution statement inside switch block, the default switch statement will be executed as shown below:

In short, we can say that “switch” statement is a selection statement which executes one of many statements inside its block. Selection is based upon the comparison of the value passed inside the switch block with those values which are already present inside the switch block. If no value matches, the default statement inside the switch block is executed.

 

2 – Loops:

Basically we have three types of loops in C++. We will discuss their syntax and functionality in the coming sections.

a – for loop.

The most basic and most widely used loop. Whenever we already know the exact number of repetitions, for loop should be used. Following is a simple program which uses while loop to display first 25 digits. Remember, here we know that we exactly want 25 repetitions, therefore we are using for loop.


for(int i=1; i<26;i++)

{

	cout<<i<<" ";

}

A for loop statement has three parts as can be seen above. First is the initialization part here in this example the loop has been started from 1. Second part is the condition which is checked in each iteration; here the condition is that “I” should be less than 26. After the execution of these two parts, control goes inside the loop, executes the code and then come back to execute the third part which is increment statement, here with every iteration “i” is incremented by 1. Hence after 25 iterations, “i” become 26 which make the condition statement false, therefore loop exits. Following is the output of the program.

b – while loop

“While” loop performs same functionality as for loop, but it should be used when we don’t know the exact number of iterations. It is usually used when we want iterations based on some conditions rather than exact number of iterations. Consider following example


int i =1;

while(i != 26)

{

	cout<<i<<" ";

	i++;

}

In this program, same functionality have been achieved i-e to print first 25 digits. But instead of using a for loop, we have used a while loop with the condition. Here unless i becomes 26, while loop will keep on iterating. We can also use Boolean values to define condition of a while loop. Remember, here increment is being done inside the while loop block rather than while loop header as it was the case with for loop. Output is the same.

 

c – do while loop

The only difference between a “while” loop and a “do while” loop is that do while loop executes at least once, whereas there is no such compulsion for while loop, it may execute many times or not execute at all. This difference is because in case of do while loop, the condition statement is at the end of the execution block which makes it inevitable for a do while loop to execute once. Consider the following example


int i =1;

do

{

	cout<<i<<" ";

	i++;

}

while (i != 26);

Here the condition statement comes at the end, hence the loop has to execute at least once to reach the condition statement. We got the same output using while loop as shown below.

 

3 – break Statement

The “break” statement is used to exit the loop at any time of execution. As soon as break statement is reached, no code inside the loop block is executed after that, and control immediately exits the loop block. Let’s modify our for loop example to explain this concept.


for(int i=1; i<26;i++)

{

	if(i>15)

	break;

	cout<<i<<" ";

}

Here we have used a condition inside a loop that whenever “i” becomes greater than 15, loop should immediately break; hence only first 15 digits will be displayed as follows.

 

4 – continue statement

“Continue” statement is used to shift the control back to the beginning of the loop without executing the code after it. Let’s look at the following example to clear the concept.


for(int i=1; i<26;i++)

{

	if(i >10 && i <=15)

		continue;

		cout<<i<<" ";

}

Here we have used a condition that whenever “i” is greater than 10 and less than or equal to 15 continue statement executes which shifts the control to the beginning of the loop without executing the remaining code, hence these numbers are not printed as shown in the output

 

PROJECTS:

For the sake of better understanding and self-evaluation of the reader we have make created two projects. One is “Calculator” which uses switch statement to perform basic mathematical functions of addition, subtraction, multiplication and division. The second project simply uses loops to display the table of a number provided by the user.

1- Calculator

It’s a simple calculator which prompts user to enter two numbers. It then gives user to enter the operation which he wants to perform on those numbers. Using switch statements the operation is evaluated by the program and subsequently the answer is displayed. Use of do while loop in practical scenario has also been explained in this project where at the end of each operation, do while loop executes and asks the user if he wants to continue with the operation or not Following is the code snippet for the program. Following is the program. Cut and paste the program into visual C++ console project and see the output.


#include <iostream>

using namespace std;

int main()

{

	int num1, num2;

	double result;

	char option, cont;

	cout <<"*** Basic Calculator Project ***";

	do

	{

		cout<<"\nEnter the first number:";

		cin>> num1;

		cout<<"Enter the 2nd number: ";

		cin>> num2;

		cout<<"Enter the operation to perform:";

		cin>> option;

		switch(option)

		{

			case '+':

			{

				result = num1 + num2;

				cout<<"\nThe answer of multiplication is:"<<result;

				break;

			}

			case '-':

			{

				result = num1 - num2;

				cout<<"The answer of subtraction is:"<<result;

				break;

			}

			case '*':

			{

				result = num1 * num2;

				cout<<"The answer of multiplication is:"<<result;

				break;

			}

			case '/':

			{

				result = num1 / num2;

				cout<<"The answer of division is:"<<result;

				break;

			}

		}

		cout<<"\nDo you want to perform another operation? (y/n)";

		cin >> cont;

	}

	while (cont == 'y');

}

OUTPUT:

 

2 – Table:

We have seen the use of switch statements and do while loop In the previous project, now we will explain the use of for and while loops. We will get a number from the user and will display its table using both for loop and while loop.

Using for loop

Let’s first make a table of a digit using for loop. Take the following code snippet, copy and paste it into a C++ console application an see the results.


#include <iostream>

using namespace std;

int main()

{

	int num;

	cout <<"Enter the number to print table:";

	cin >>num;

	for(int i=1 ;i<=10; i++)

	{

		cout<<num<<" x "<<i<<" = " <<num*i<<endl;

	}

	getchar();// Just to prevent screen from disappearing

	cin.get();// Just to prevent screen from disappearing

}

Output:

 

Using “while” loop:

The above table can be made using while loop as well. The code snippet for while loop is as follows:


#include <iostream>

using namespace std;

int main()

{

	int num;

	cout <<"Enter the number to print table:";

	cin >>num;

	int i=1;

	while(i<=10){

		cout<<num<<" x "<<i<<" = " <<num*i<<endl;

		i++;

	}

	getchar();// Just to prevent screen from disappearing

	cin.get();// Just to prevent screen from disappearing

}

OUTPUT:

 

You might want to read:

C++ for Beginners Part 8 – Functions

C++ for Beginners Part 7 – Pointers

C++ for beginners Part 6 – Arrays & Strings

C++ for beginners Part 5 – “switch and loops”

C++ for beginners Part 4 – else if Statement in C++

C++ for beginners Part 3 – Conditional “if” Statement

C++ for beginners Part 2 – The Basics of C++

C++ for beginners Part 1 – Installing Visual C++ Express

 

More C / C++ and Dev Programming Tutorials:

 

If you liked this tutorial, please share with your friends:

Leave a Reply

Your email address will not be published. Required fields are marked *