If you want to change the execution from the normal sequence or if you want the program to exit loops, for these purposes you need to use loop control statements.
Loop control statements are also known as Jump statements. It allows you to jump from the loops or if you wish to repeat the loops after some condition is satisfied, jump statements helps you to achieve that.
C++ supports the following control statements.
break statement
continue statement
goto
break statement in C++
break statement terminates the loop and transfers the execution process immediately to a statement following the loop.
break statement is mostly used in a switch statement to terminate the cases present in a switch statement.
The use of break statements in nested loops terminates the inner loop and the control is transferred to the outer loop.
The continue statement works like a break statement, instead of terminating the loop the continue statement skips the code in between and passes the execution to the next iteration in the loop.
In case of for loop, the continue statement causes the program to jump and pass the execution to the condition and update expression by skipping further statement. Whereas in the case of while and do…while loops, the continue statement passes the control to the conditional checking expression.
continue statement Flowchart:
continue statement
Syntax of continue statement in C++:
continue;
Click here for example of continuestatement in C++.
goto statement in C++
The goto statement is a jump statement that allows the user in the program to jump the execution control to the other part of the program. It jumps to the position where the labeled statement present in the program. The label (tag) is used to spot the jump statement.
NOTE: Remember the use of goto is avoided in programming language because it makes it difficult to trace the control flow of a program, making the program hard to understand and hard to modify.
The goto statement is a jump statement that allows the user in the program to jump the execution control to the other part of the program. It jumps to the position where the labeled statement present in the program. The label (tag) is used to spot the jump statement.
NOTE: Remember the use of goto is avoided in programming language because it makes it difficult to trace the control flow of a program, making the program hard to understand and hard to modify.
The simple example of goto statement in C++ programming.
#include <iostream>
using namespace std;
int main()
{
//this is the label
ineligible_label:
int age;
cout << "Enter your age: ";
cin >> age;
if (age < 18)
{
cout << "You are below 18 and not eligible to vote.\n";
goto ineligible_label;
}
else
{
cout << "You are above 18 and eligible to vote.";
}
}
Output:
Enter your age: 16
You are below 18 and not eligible to vote.
Enter your age: 21
You are above 18 and eligible to vote.
Avoid the use of goto: However, the use of goto is considered a harmful construct and a bad programming practice in a C++ programming. It makes the program complex and tangled, instead you can achieve the task of goto by using thebreak and continue statement.
The continue statement works like a break statement, instead of terminating the loop the continue statement skips the code in between and passes the execution to the next iteration in the loop.
In case of for loop, the continue statement causes the program to jump and pass the execution to the condition and update expression by skipping further statement. Whereas in the case of while and do…while loops, the continue statement passes the control to the conditional checking expression.
continue statement Flowchart:
continue statement
Syntax of continue statement in C++:
continue;
Example of C++ continue statement
Example: Use of continue in for loop in C++ programming.
//C++ program for continue statement
#include <iostream>
using namespace std;
int main()
{
for (int i = 1; i <= 10; i++)
{
//continue condition
if (i == 6)
{
//Number 6 is skipped
continue;
}
cout << "Value of i: " << i << endl;
}
return 0;
}
Output:
Value of i: 1
Value of i: 2
Value of i: 3
Value of i: 4
Value of i: 5
Value of i: 7
Value of i: 8
Value of i: 9
Value of i: 10
As you can see in the above output the 6th iteration is skipped. When the value of i becomes 6, if statement is executed and hence the continue statement. Then the control is passed to the update expression of the for loop and i becomes 7.
Example: Use of continue in do-while loop loop in C++ programming
#include <iostream>
using namespace std;
int main()
{
int a = 1;
// do-while loop
do {
if (a == 5)
{
//a incremented and iteration skipped.
a += 1;
continue;
}
cout << "value of a: " << a << endl;
a += 1;
}
while (a <= 10); //condition check
return 0;
}
Output:
value of a: 1
value of a: 2
value of a: 3
value of a: 4
value of a: 6
value of a: 7
value of a: 8
value of a: 9
value of a: 10
break statement terminates the loop and transfers the execution process immediately to a statement following the loop.
break statement is mostly used in a switch statement to terminate the cases present in a switch statement.
The use of break statements in nested loops terminates the inner loop and the control is transferred to the outer loop.
break statement Flowchart:
break statement
Syntax of break statement in C++:
break;
Example on C++ break Statement
Example: C++ program to demonstrate the use of break statement in single loop.
#include <iostream>
using namespace std;
int main()
{
for (int i = 1; i <= 10; i++)
{
if (i == 7)
{
//when i becomes 7 then it will come out of for loop
break;
}
cout << "i is: " << i << endl;
}
}
Output:
i is: 1
i is: 2
i is: 3
i is: 4
i is: 5
i is: 6
Example: C++ program for break statement used in nested loop.
//using break statement inside nested loop
#include <iostream>
using namespace std;
int main()
{
// outer loop
for (int i = 1; i <= 5; i++)
{
//inner loop
for (int j = 1; j <= 2; j++)
{
if (i == 4)
{
//if i becomes 4, it will come out of inner loop
break;
}
cout << "i = " << i << ", j = " << j << endl;
}
}
return 0;
}
Output:
i = 1, j = 1
i = 1, j = 2
i = 2, j = 1
i = 2, j = 2
i = 3, j = 1
i = 3, j = 2
i = 5, j = 1
i = 5, j = 2
In the above program, for the value i = 4 is skipped because when we reached i value as four, break statement is applied the execution came out of the inner loop, skipping the inner loop for 4.
A situation may arise during coding where you need to repeat the block of code for some number of times then the loops present in C++ will come in play.
Loops allow us to execute a block of code or statement or group of statements as many times according to the user’s need. The condition is checked every time the loop is repeated. It is done by evaluating a given condition for true and false.
If true, the loop statement are repeated, if false then the loop is skipped.
Loops in Programming
Two Types of Loops in C Programming.
1. Entry controlled loop:
In entry control loops, the conditional is checked first and then the block of code is executed. It is also called a pre-checking loop.
A while loop is a straightforward loop and is also an entry-control loop. It evaluates the condition before executing the block of the loop. If the condition is found to be true, only then the body of the loop is executed. The loop continues until the condition stated found to be false.
While loops are used when we do not know the exact number of times the iteration required beforehand. By default the while loop condition is true.
The syntax for while loop in C++:
while(condition)
{
//block of code to be executed
}
You should use a while loop, where the exact number of iterations is not known but the loop termination condition, is known.
For example and flowchart of while loop, click here
do…while loop in C++
Sometimes it is necessary that the block or statement must be executed at least once but if the condition is initially at a false state then the block will not be executed. So for the situation where a block of code must be executed at least once a do-while loop comes into play.
It is the same as the while loop where the loop is terminated on the basis of the test condition. The main difference is that the do-while loop checks the condition at the end of the loop which allows the do-while to execute the loop at least once.
The syntax for do-while loop in C++:
do
{
//statements..
}while (condition);
You should use do while loop if the code needs to be executed at least once.
For example and flowchart of do-while loop, click here
for Loop in C++
The for loop has a more efficient loop structure and is an entry-control loop. The loop allows the programmer to write the execution steps together in a single line and also the specific number of times the execution is to be iterated.
It has three computing steps as shown in the syntax below.
initialization: The first step is the initialization of the variable and is executed only once. And need to end with a semicolon(;).
condition: Second is condition check, it checks for a boolean expression. If true then enter the block and if false exit the loop. And need to end with a semicolon(;).
Increment or Decrement: The third one is the increment or decrement of the variable for the next iteration. Here, we do not need to use the semicolon at the end.
The syntax for for loop in C++:
for(initialization; condition; Increment or Decrement)
{
// Statements
}
You should use for a loop when the number of iterations is known beforehand, i.e. when the number of times the loop body is needed to be executed is known.
C# break Statement: break statement in programming is used to come out of the loop or switch statements. It is a jump statement that breaks the control flow of the program and transfers the execution control after the loop. Click here to learn in detail
C# continue Statement: It is a loop control statement. It is used to continue the loop in the program. The use of continue inside a loop skips the remaining code and transfer the current flow of the execution to the beginning o the loop. Click here to learn in detail
C# goto Statement: The goto statement is a jump statement that allows the user in the program to jump the execution control to the other part of the program. Click here to learn in detail.
The Infinite Loop
As the name suggests, the infinite loop is a forever executing loop. The infinite loop repeats indefinitely and the condition never becomes false. It is also known as an indefinite loop or an endless loop.
We can use one of the Loops in C++ to turn it into infinite loop.
infinite ‘for’ loop
for(; ;)
{
//body of the loop
}
infinite while loop
while(1)
{
//body of the loop
}
infinite do-while loop
do
{
//body of the loop
}while(1);
Example: of infinite for loop in C++
#include <iostream>
using namespace std;
int main ()
{
int i;
//infinite for loop
for ( ; ; )
{
cout << "This loop will run forever.\n";
}
/*//infinite while loop
while (true)
{
cout << "This loop will run forever.\n";
}
*/
return 0;
}
The compiler assume the condition to be true if the condition is absent in the loop.
Sometimes it is necessary that the block or statement must be executed at least once but if the condition is initially at a false state then the block will not be executed. So for the situation where a block of code must be executed at least once a do-while loop comes into play.
It is the same as the while loop where the loop is terminated on the basis of the test condition. The main difference is that the do-while loop checks the condition at the end of the loop which allows the do-while to execute the loop at least once.
do-while Flowchart:
do-while loop
The syntax for do-while loop in C++:
do
{
//statements..
}while (condition);
You should use do while loop if the code needs to be executed at least once.
Example of C++ do-while loop
#include <iostream>
using namespace std;
int main ()
{
int i = 1;
// do loop
do {
cout << "value of i: " << i << endl;
i += 1;
} while( i <= 10 ); //condition check
return 0;
}
Output:
value of i: 1
value of i: 2
value of i: 3
value of i: 4
value of i: 5
value of i: 6
value of i: 7
value of i: 8
value of i: 9
value of i: 10
A while loop is a straightforward loop and is also an entry-control loop. It evaluates the condition before executing the block of the loop. If the condition is found to be true, only then the body of the loop is executed. The loop continues until the condition stated found to be false.
While loops are used when we do not know the exact number of times the iteration required beforehand. By default the while loop condition is true.
while loop Flowchart:
While Loop
The syntax for while loop in C++:
while(condition)
{
//block of code to be executed
}
You should use a while loop, where the exact number of iterations is not known but the loop termination condition, is known.
Example of C++ while loop
#include <iostream>
using namespace std;
int main()
{
int i = 1;
// while loop
while (i <= 10)
{
cout << "value of i: " << i << endl;
i++;
}
return 0;
}
Output:
value of i: 1
value of i: 2
value of i: 3
value of i: 4
value of i: 5
value of i: 6
value of i: 7
value of i: 8
value of i: 9
value of i: 10
The for loop has a more efficient loop structure and is an entry-control loop. The loop allows the programmer to write the execution steps together in a single line and also the specific number of times the execution is to be iterated.
for loop Flowchart:
for loop
It has three computing steps as shown in the syntax below.
initialization: The first step is the initialization of the variable and is executed only once. And need to end with a semicolon(;).
condition: Second is condition check, it checks for a boolean expression. If true then enter the block and if false exit the loop. And need to end with a semicolon(;).
Increment or Decrement: The third one is the increment or decrement of the variable for the next iteration. Here, we do not need to use the semicolon at the end.
The syntax for for loop in C++:
for(initialization; condition; Increment or Decrement)
{
// Statements
}
You should use for a loop when the number of iterations is known beforehand, i.e. when the number of times the loop body is needed to be executed is known.
Example of C++ for loop
#include <iostream>
using namespace std;
int main ()
{
// for loop execution
for( int i = 1; i <= 10; i++ )
cout << "value of i: " << i << endl;
return 0;
}
Output:
value of i: 1
value of i: 2
value of i: 3
value of i: 4
value of i: 5
value of i: 6
value of i: 7
value of i: 8
value of i: 9
value of i: 10
During coding, you tackle most of the situations where your next move depends on your decisions. Now to make such a decision in programming, we use the decision-making statement provided by the programming language.
Decision-Making statements are used when a user wants a certain block to be executed under certain conditions. The condition to be checked is determined by true or false value.
C++ programming language provides the following types of decision-making statements:
if statement
if-else statement
nested-if statement
if-else-if ladder statement
switch-case statement
The above decision making statements determines the direction of flow of the program execution.
C++ if statement
An if statement consists of a Boolean expression followed by one or more statements. If the Boolean expression is true, the block of code inside the if statement will be executed else not. This is most simple of all the decision making statements.
The syntax of the if statement in C++:
if (condition)
{
//block of statement
}
If the condition is evaluated true, block of statement is executed.
If the condition is evaluated false, block of statement is skipped.
For example and flowchart of C++ if statement, click here
C++ if…elsestatement
If the Boolean expression is true then the code inside the if statement block is executed or if it is false then the code inside else statement will be executed. Hence if..else statement.
The syntax of the if..else statement in C++:
if (condition)
{
//code executed if condition true
}
else
{
//code executed if condition false
}
For example and flowchart C++ if…elsestatement, click here
C++ nested if statement
This statement allows the user to use if block inside the other if block. And the inner if statement is executed only if the outer if statement’s condition is true.
The syntax of the nested if statement in C++:
if(condition1)
{
//block of code to be executed
if(condition2)
{
//block of code to be executed
}
}
You can also nest the if..else statement in same manner as shown below.
//Nested if....else statement
if(condition1)
{
if(condition2)
{
//block of statement;
}
else
{
//block of statement;
}
}
else
{
//block of statement;
}
For example and flowchart C++ nested ifstatement, click here
C++ if-else-if ladderstatement
This statement allows the user to have multiple options to check for different conditions. Here, if one of the if or else-if condition is true then that part of the code will be executed and the rest will be skipped. if none of the conditions are true then the final else statement present at the end will be executed.
The syntax of the if-else-if ladder statement in C++:
if(condition1)
{
//code to be executed if condition1 is true
}
else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3){
//code to be executed if condition3 is true
}
...
else{
//final else if all the above condition are false
}
For example and flowchart C++ if-else-if ladderstatement, click here
C++ switchstatement
A switch statement allows a variable to be tested for equality against multiple values and each of those values is called a case. It can be used instead of nestedif...else..if ladder.
Switch expression and case value must be of the same type. There must be at least one case or multiple cases with unique case values. In the end, it can have a default case which is optional that is executed if no cases are matched.
The syntax of the switchstatement statement in C++:
switch (expression)
{
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
.
.
.
.
case valueN:
//code to be executed;
break; //optional
default:
code to be executed if all cases are not matched;
}
The expression is evaluated once and compared with the values of each case label.
If the expression and case value are matched then the corresponding code present within that particular case will be executed and a break statement is used to come out of the switch statement by skipping all of the other cases.
If the values of expression and case do not match, the code within default: is executed.
For example and flowchart C++ switchstatementstatement, click here
The ? : Operator
? : This operator is called a conditional operator or ternary operator. The execution of this operator depends on the result of the binary condition.
Ternary Operator can also be used instead of if...else statement as it does follow the same algorithm and the only difference is ternary operator takes less space and it’s the short version of if...else statement.
? : Operator is also called Ternary Operator because it takes three operands to operate, as shown in the syntax below.
Syntax of Ternary Operator:
variable = Condition ? Expression1 : Expression1
Here, the condition that is the binary condition is to be evaluated. And if the binary condition is true then Expression1 is executed and if it is false then Expression2 is executed. And both of them return the results.
Click here to learn about ternary operator with an example.
A switch statement allows a variable to be tested for equality against multiple values and each of those values is called a case. It can be used instead of nestedif...else..if ladder.
Switch expression and case value must be of the same type. There must be at least one case or multiple cases with unique case values. In the end, it can have a default case which is optional that is executed if no cases are matched.
The syntax of the switchstatement statement in C++:
switch (expression)
{
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
.
.
.
.
case valueN:
//code to be executed;
break; //optional
default:
code to be executed if all cases are not matched;
}
The expression is evaluated once and compared with the values of each case label.
If the expression and case value are matched then the corresponding code present within that particular case will be executed and a break statement is used to come out of the switch statement by skipping all of the other cases.
If the values of expression and case do not match, the code within default: is executed.
Switch statement Flowchart:
Example of C++ switch statement
// C++ Program tocreate calculator
#include <iostream>
using namespace std;
int main()
{
char choice;
float num1, num2;
cout << "Enter two numbers: " << endl;
cin >> num1 >> num2;
cout << "Enter one of the operator(+, -, *, /): ";
cin >> choice;
switch (choice)
{
case '+':
cout << num1 << " + " << num2 << " = " << num1 + num2;
break;
case '-':
cout << num1 << " - " << num2 << " = " << num1 - num2;
break;
case '*':
cout << num1 << " *" << num2 << " = " << num1 * num2;
break;
case '/':
cout << num1 << " / " << num2 << " = " << num1 / num2;
break;
default:
//when entered operator does not match with any cases
cout << "Entered operator is not correct";
break;
}
return 0;
}
Output:
Enter two numbers:
2 3
Enter one of the operator(+, -, *, /): +
2 + 3 = 5
C++ nested switch Statement
The use of switch statement inside another switch statement is called nested switch statement.
Syntax ofnested switch statement in C++:
switch(ch1)
{
case 'A':
printf("This A is part of outer switch" );
//use of another switch statement
switch(ch2) {
case 'A':
printf("This A is part of inner switch" );
break;
case 'B': /* case code */
}
break;
case 'B': /* case code */
}
Example of C++ nested switch statement
#include <iostream>
using namespace std;
int main()
{
int a = 50;
int b = 100;
switch (a)
{
case 50:
cout << "This is a outer switch" << endl;
//another switch
switch (b)
{
case 100:
cout << "This is a inner switch" << endl;
}
}
return 0;
}