Control Flow Statements
Control Flow Statements
In C++, relational and logical operators compare two or more operands and return either true or
false values.
A relational operator is used to check the relationship between two operands. For example,
== Operator
For example,
int x = 10;
int y = 15;
int z = 10;
x == y // false
x == z // true
Note: The relational operator == is not the same as the assignment operator =. The assignment
operator = assigns a value to a variable, constant, array, or vector. It does not compare two
operands.
!= Operator
For example,
int x = 10;
int y = 15;
int z = 10;
x != y // true
x != z // false
> Operator
For example,
int x = 10;
int y = 15;
x > y // false
y > x // true
< Operator
int x = 10;
int y = 15;
x < y // true
y < x // false
>= Operator
• true - if the left operand is either greater than or equal to the right
• false - if the left operand is less than the right
For example,
int x = 10;
int y = 15;
int z = 10;
x >= y // false
y >= x // true
z >= x // true
<= Operator
• true - if the left operand is either less than or equal to the right
• false - if the left operand is greater than right
For example,
int x = 10;
int y = 15;
x > y // false
y > x // true
In order to learn how relational operators can be used with strings, refer to our tutorial here.
We use logical operators to check whether an expression is true or false. If the expression is
true, it returns 1 whereas if the expression is false, it returns 0.
Operator Example Meaning
Logical AND.
&& expression1 && expression 2
true only if all the operands are true.
Logical OR.
|| expression1 || expression 2
true if at least one of the operands is true.
Logical NOT.
! !expression
true only if the operand is false.
Let a and b be two operands. 0 represents false while 1 represents true. Then,
a b a && b
000
010
100
111
As we can see from the truth table above, the && operator returns true only if both a and b are
true.
Note: The Logical AND operator && should not be confused with the Bitwise AND operator &.
#include <iostream>
using namespace std;
int main() {
int a = 5;
int b = 9;
return 0;
}
Run Code
Output
0
0
0
1
In this program, we declare and initialize two int variables a and b with the values 5 and 9
respectively. We then print a logical expression
Here, a == 0 evaluates to false as the value of a is 5. a > b is also false since the value of a
is less than that of b. We then use the AND operator && to combine these two expressions.
From the truth table of && operator, we know that false && false (i.e. 0 && 0) results in an
evaluation of false (0). This is the result we get in the output.
Similarly, we evaluate three other expressions that fully demonstrate the truth table of the &&
operator.
a b a || b
000
011
101
111
As we can see from the truth table above, the || operator returns false only if both a and b are
false.
#include <iostream>
using namespace std;
int main() {
int a = 5;
int b = 9;
return 0;
}
Run Code
Output
0
1
1
1
In this program, we declare and initialize two int variables a and b with the values 5 and 9
respectively. We then print a logical expression
Here, a == 0 evaluates to false as the value of a is 5. a > b is also false since the value of a
is less than that of b. We then use the OR operator || to combine these two expressions.
From the truth table of || operator, we know that false || false (i.e. 0 || 0) results in an
evaluation of false (0). This is the result we get in the output.
Similarly, we evaluate three other expressions that fully demonstrate the truth table of ||
operator.
The logical NOT operator ! is a unary operator i.e. it takes only one operand.
It returns true when the operand is false, and false when the operand is true.
int main() {
int a = 5;
// !false = true
cout << !(a == 0) << endl;
// !true = false
cout << !(a == 5) << endl;
return 0;
}
Run Code
Output
1
0
In this program, we declare and initialize an int variable a with the value 5. We then print a
logical expression
!(a == 0)
Here, a == 0 evaluates to false as the value of a is 5. However, we use the NOT operator ! on
a == 0. Since a == 0 evaluates to false, the ! operator inverts the results of a == 0 and the
final result is true.
C++ if Statement
Syntax
if (condition) {
// body of if statement
}
1. If the condition evaluates to true, the code inside the body of if is executed.
2. If the condition evaluates to false, the code inside the body of if is skipped.
#include <iostream>
using namespace std;
int main() {
int number;
return 0;
}
Run Code
Output 1
Enter an integer: 5
You entered a positive number: 5
This statement is always executed.
When the user enters 5, the condition number > 0 is evaluated to true and the statement inside
the body of if is executed.
Output 2
Enter a number: -5
This statement is always executed.
When the user enters -5, the condition number > 0 is evaluated to false and the statement inside
the body of if is not executed.
C++ if...else
Syntax
if (condition) {
// block of code if condition is true
}
else {
// block of code if condition is false
}
#include <iostream>
using namespace std;
int main() {
int number;
if (number >= 0) {
cout << "You entered a positive integer: " << number << endl;
}
else {
cout << "You entered a negative integer: " << number << endl;
}
return 0;
}
Run Code
Output 1
Enter an integer: 4
You entered a positive integer: 4.
This line is always printed.
In the above program, we have the condition number >= 0. If we enter the number greater or
equal to 0, then the condition evaluates true.
Here, we enter 4. So, the condition is true. Hence, the statement inside the body of if is
executed.
Output 2
Enter an integer: -4
You entered a negative integer: -4.
This line is always printed.
Here, we enter -4. So, the condition is false. Hence, the statement inside the body of else is
executed.
The if...else statement is used to execute a block of code among two alternatives. However, if
we need to make a choice between more than two alternatives, we use the if...else
if...else statement.
Syntax
if (condition1) {
// code block 1
}
else if (condition2){
// code block 2
}
else {
// code block 3
}
Here,
Note: There can be more than one else if statement but only one if and else statements.
Example 3: C++ if...else...else if
// Program to check whether an integer is positive, negative or zero
#include <iostream>
using namespace std;
int main() {
int number;
if (number > 0) {
cout << "You entered a positive integer: " << number << endl;
}
else if (number < 0) {
cout << "You entered a negative integer: " << number << endl;
}
else {
cout << "You entered 0." << endl;
}
return 0;
}
Run Code
Output 1
Enter an integer: 1
You entered a positive integer: 1.
This line is always printed.
Output 2
Enter an integer: -2
You entered a negative integer: -2.
This line is always printed.
Output 3
Enter an integer: 0
You entered 0.
This line is always printed.
In this program, we take a number from the user. We then use the if...else if...else ladder
to check whether the number is positive, negative, or zero.
If the number is greater than 0, the code inside the if block is executed. If the number is less
than 0, the code inside the else if block is executed. Otherwise, the code inside the else block
is executed.
Sometimes, we need to use an if statement inside another if statement. This is known as nested
if statement.
Think of it as multiple layers of if statements. There is a first, outer if statement, and inside it is
another, inner if statement.
Syntax
// outer if statement
if (condition1) {
// statements
// inner if statement
if (condition2) {
// statements
}
}
Notes:
1. We can add else and else if statements to the inner if statement as required.
2. The inner if statement can also be inserted inside the outer else or else if statements (if
they exist).
3. We can nest multiple layers of if statements.
#include <iostream>
using namespace std;
int main() {
int num;
// outer if condition
if (num != 0) {
// inner if condition
if (num > 0) {
cout << "The number is positive." << endl;
}
// inner else condition
else {
cout << "The number is negative." << endl;
}
}
// outer else condition
else {
cout << "The number is 0 and it is neither positive nor negative." <<
endl;
}
return 0;
}
Run Code
Output 1
Enter an integer: 35
The number is positive.
This line is always printed.
Output 2
Output 3
Enter an integer: 0
The number is 0 and it is neither positive nor negative.
This line is always printed.
1. We take an integer as an input from the user and store it in the variable num.
2. We then use an if...else statement to check whether num is not equal to 0.
1. If true, then the inner if...else statement is executed.
2. If false, the code inside the outer else condition is executed, which prints "The
number is 0 and it is neither positive nor negative."
3. The inner if...else statement checks whether the input number is positive i.e. if num is
greater than 0.
1. If true, then we print a statement saying that the number is positive.
2. If false, we print that the number is negative.
Note: As you can see, nested if...else makes your logic complicated. If possible, you should
always try to avoid nested if...else.
If the body of if...else has only one statement, you can omit { } in the program. For example,
you can replace
int number = 5;
if (number > 0) {
cout << "The number is positive." << endl;
}
else {
cout << "The num
ber is negative." << endl;
}
with
int number = 5;
if (number > 0)
cout << "The number is positive." << endl;
else
cout << "The number is negative." << endl;
Note: Although it's not necessary to use { } if the body of if...else has only one statement,
using { } makes your code more readable.
The ternary operator is a concise, inline method used to execute one of two expressions based
on a condition. To learn more, visit C++ Ternary Operator.
If we need to make a choice between more than one alternatives based on a given test condition,
the switch statement can be used. To learn more, visit C++ switch.
Also Read:
For example, let's say we want to show a message 100 times. Then instead of writing the print
statement 100 times, we can use a loop.
That was just a simple example; we can achieve much more efficiency and sophistication in our
programs by making effective use of loops.
• for loop
• while loop
• do...while loop
This tutorial focuses on C++ for loop. We will learn about the other type of loops in the
upcoming tutorials.
Here,
To learn more about conditions, check out our tutorial on C++ Relational and Logical
Operators.
Flowchart of for Loop in C++
int main() {
for (int i = 1; i <= 5; ++i) {
cout << i << " ";
}
return 0;
}
Run Code
Output
1 2 3 4 5
#include <iostream>
int main() {
for (int i = 1; i <= 5; ++i) {
cout << "Hello World! " << endl;
}
return 0;
}
Run Code
Output
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
#include <iostream>
int main() {
int num, sum;
sum = 0;
return 0;
}
Run Code
Output
In the above example, we have two variables num and sum. The sum variable is assigned with 0
and the num variable is assigned with the value provided by the user.
Here,
When i becomes 11, the condition is false and sum will be equal to 0 + 1 + 2 + ... + 10.
In C++11, a new range-based for loop was introduced to work with collections such as arrays
and vectors. Its syntax is:
Here, for every value in the collection, the for loop is executed and the value is assigned to the
variable.
int main() {
return 0;
}
Run Code
Output
1 2 3 4 5 6 7 8 9 10
In the above program, we have declared and initialized an int array named num_array. It has 10
items.
Here, we have used a range-based for loop to access all the items in the array.
C++ Infinite for loop
If the condition in a for loop is always true, it runs forever (until memory is full). For
example,
In the above program, the condition is always true which will then run the code for infinite
times.
Also Read:
For example, let's say we want to show a message 100 times. Then instead of writing the print
statement 100 times, we can use a loop.
That was just a simple example; we can achieve much more efficiency and sophistication in our
programs by making effective use of loops.
1. for loop
2. while loop
3. do...while loop
In the previous tutorial, we learned about the C++ for loop. Here, we are going to learn about
while and do...while loops.
C++ while Loop
while (condition) {
// body of the loop
}
Here,
To learn more about the conditions, visit C++ Relational and Logical Operators.
#include <iostream>
int main() {
int i = 1;
return 0;
}
Run Code
Output
1 2 3 4 5
#include <iostream>
using namespace std;
int main() {
int number;
int sum = 0;
return 0;
}
Run Code
Output
Enter a number: 6
Enter a number: 12
Enter a number: 7
Enter a number: 0
Enter a number: -2
The sum is 25
In this program, the user is prompted to enter a number, which is stored in the variable number.
In order to store the sum of the numbers, we declare a variable sum and initialize it to the value
of 0.
The while loop continues until the user enters a negative number. During each iteration, the
number entered by the user is added to the sum variable.
When the user enters a negative number, the loop terminates. Finally, the total sum is displayed.
The do...while loop is a variant of the while loop with one important difference: the body of
do...while loop is executed once before the condition is checked.
Here,
• The body of the loop is executed at first. Then the condition is evaluated.
• If the condition evaluates to true, the body of the loop inside the do statement is executed
again.
• The condition is evaluated once again.
• If the condition evaluates to true, the body of the loop inside the do statement is executed
again.
• This process continues until the condition evaluates to false. Then the loop stops.
#include <iostream>
using namespace std;
int main() {
int i = 1;
return 0;
}
Run Code
Output
1 2 3 4 5
#include <iostream>
using namespace std;
int main() {
int number = 0;
int sum = 0;
do {
sum += number;
// take input from the user
cout << "Enter a number: ";
cin >> number;
}
while (number >= 0);
return 0;
}
Run Code
Output 1
Enter a number: 6
Enter a number: 12
Enter a number: 7
Enter a number: 0
Enter a number: -2
The sum is 25
Here, the do...while loop continues until the user enters a negative number. When the number
is negative, the loop terminates; the negative number is not added to the sum variable.
Output 2
Enter a number: -6
The sum is 0.
The body of the do...while loop runs only once if the user enters a negative number.
If the condition of a loop is always true, the loop runs for infinite times (until the memory is
full). For example,
int count = 1;
do {
// body of loop
}
while(count == 1);
In the above programs, the condition is always true. Hence, the loop body will run for infinite
times.
A for loop is usually used when the number of iterations is known. For example,
However, while and do...while loops are usually used when the number of iterations is
unknown. For example,
while (condition) {
// body of the loop
}
break;
Before you learn about the break statement, make sure you know about:
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 5; i++) {
// break condition
if (i == 3) {
break;
}
cout << i << endl;
}
return 0;
}
Run Code
Output
1
2
In the above program, the for loop is used to print the value of i in each iteration. Here, notice
the code:
if (i == 3) {
break;
}
This means, when i is equal to 3, the break statement terminates the loop. Hence, the output
doesn't include values greater than or equal to 3.
#include <iostream>
using namespace std;
int main() {
int number;
int sum = 0;
while (true) {
// take input from the user
cout << "Enter a number: ";
cin >> number;
// break condition
if (number < 0) {
break;
}
return 0;
}
Run Code
Output
Enter a number: 1
Enter a number: 2
Enter a number: 3
Enter a number: -5
The sum is 6.
In the above program, the user enters a number. The while loop is used to print the total sum of
numbers entered by the user. Here, notice the code,
if(number < 0) {
break;
}
This means, when the user enters a negative number, the break statement terminates the loop
and codes outside the loop are executed.
The while loop continues until the user enters a negative number.
When break is used with nested loops, break terminates the inner loop. For example,
#include <iostream>
using namespace std;
int main() {
int number;
int sum = 0;
// first loop
for (int i = 1; i <= 3; i++) {
// second loop
for (int j = 1; j <= 3; j++) {
if (i == 2) {
break;
}
cout << "i = " << i << ", j = " << j << endl;
}
}
return 0;
}
Run Code
Output
i = 1, j = 1
i = 1, j = 2
i = 1, j = 3
i = 3, j = 1
i = 3, j = 2
i = 3, j = 3
In the above program, the break statement is executed when i == 2. It terminates the inner
loop, and the control flow of the program moves to the outer loop.
The break statement is also used with the switch statement. To learn more, visit C++ switch
statement.
Also Read:
continue;
Before you learn about the continue statement, make sure you know about,
In a for loop, continue skips the current iteration and the control flow jumps to the update
expression.
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 5; i++) {
// condition to continue
if (i == 3) {
continue;
}
Output
1
2
4
5
In the above program, we have used the the for loop to print the value of i in each iteration.
Here, notice the code,
if (i == 3) {
continue;
}
This means
• When i is equal to 3, the continue statement skips the current iteration and starts the next
iteration
• Then, i becomes 4, and the condition is evaluated again.
• Hence, 4 and 5 are printed in the next two iterations.
Note: The continue statement is almost always used with decision-making statements.
In a while loop, continue skips the current iteration and control flow of the program jumps
back to the while condition.
#include <iostream>
using namespace std;
int main() {
int sum = 0;
int number = 0;
// continue condition
if (number > 50) {
cout << "The number is greater than 50 and won't be calculated."
<< endl;
number = 0; // the value of number is made 0 again
continue;
}
}
return 0;
}
Run Code
Output
Enter a number: 12
Enter a number: 0
Enter a number: 2
Enter a number: 30
Enter a number: 50
Enter a number: 56
The number is greater than 50 and won't be calculated.
Enter a number: 5
Enter a number: -3
The sum is 99
In the above program, the user enters a number. The while loop is used to print the total sum of
positive numbers entered by the user, as long as the numbers entered are not greater than 50.
• When the user enters a number greater than 50, the continue statement skips the current
iteration. Then the control flow of the program goes to the condition of while loop.
• When the user enters a number less than 0, the loop terminates.
Note: The continue statement works in the same way for the do...while loops.
continue with Nested loop
When continue is used with nested loops, it skips the current iteration of the inner loop. For
example,
#include <iostream>
using namespace std;
int main() {
int number;
int sum = 0;
// first loop
for (int i = 1; i <= 3; i++) {
// second loop
for (int j = 1; j <= 3; j++) {
if (j == 2) {
continue;
}
cout << "i = " << i << ", j = " << j << endl;
}
}
return 0;
}
Run Code
Output
i = 1, j = 1
i = 1, j = 3
i = 2, j = 1
i = 2, j = 3
i = 3, j = 1
i = 3, j = 3
In the above program, when the continue statement executes, it skips the current iteration in the
inner loop. And the control of the program moves to the update expression of the inner loop.
Note: The break statement terminates the loop entirely. However, the continue statement only
skips the current iteration.
C++ goto Statement
In C++ programming, the goto statement is used for altering the normal sequence of program
execution by transferring control to some other part of the program.
In the syntax above, label is an identifier. When goto label; is encountered, the control of
program jumps to label: and executes the code below it.
# include <iostream>
using namespace std;
int main()
{
float num, average, sum = 0.0;
int i, n;
jump:
average = sum / (i - 1);
cout << "\nAverage = " << average;
return 0;
}
Output
Average = 3.95
You can write any C++ program without the use of goto statement and is generally considered a
good idea not to use them.
The goto statement gives the power to jump to any part of a program but, makes the logic of the
program complex and tangled.
In modern programming, the goto statement is considered a harmful construct and a bad
programming practice.
The goto statement can be replaced in most of C++ program with the use of break and continue
statements.
You can do the same thing with the if...else statement. However, the syntax of the switch
statement is much easier to read and write.
Syntax
switch (expression) {
case constant1:
// code to be executed if
// expression is equal to constant1;
break;
case constant2:
// code to be executed if
// expression is equal to constant2;
break;
.
.
.
default:
// code to be executed if
// expression doesn't match any constant
}
The expression is evaluated once and compared with the values of each case label.
• If there is a match, the corresponding code after the matching label is executed. For example, if
the value of the variable is equal to constant2, the code after case constant2: is executed
until the break statement is encountered.
• If there is no match, the code after default: is executed.
Note: We can do the same thing with the if...else..if ladder. However, the syntax of the switch
statement is cleaner and much easier to read and write.
Flowchart of switch Statement
Flowchart of C++
switch...case statement
Example: Create a Calculator using the switch Statement
// Program to build a simple calculator using switch Statement
#include <iostream>
using namespace std;
int main() {
char oper;
float num1, num2;
cout << "Enter an operator (+, -, *, /): ";
cin >> oper;
cout << "Enter two numbers: " << endl;
cin >> num1 >> num2;
switch (oper) {
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:
// operator is doesn't match any case constant (+, -, *, /)
cout << "Error! The operator is not correct";
break;
}
return 0;
}
Run Code
Output 1
Output 2
Output 3
Enter an operator (+, -, *, /): *
Enter two numbers:
2.3
4.5
2.3 * 4.5 = 10.35
2.3
4.5
2.3 - 4.5 = -2.2
Output 3
Output 4
Output 5
In the above program, we are using the switch...case statement to perform addition,
subtraction, multiplication, and division.
1. We first prompt the user to enter the desired operator. This input is then stored in the
char variable named oper.
2. We then prompt the user to enter two numbers, which are stored in the float variables
num1 and num2.
3. The switch statement is then used to check the operator entered by the user:
a. If the user enters +, addition is performed on the numbers.
b. If the user enters -, subtraction is performed on the numbers.
c. If the user enters *, multiplication is performed on the numbers.
d. If the user enters /, division is performed on the numbers.
e. If the user enters any other character, the default code is printed.
Notice that the break statement is used inside each case block. This terminates the switch
statement.
If the bre
ak statement is not used, all cases after the correct case are executed.
You can visit the article on C++ Program to Make a Simple Calculator to learn more.
A ternary operator evaluates the test condition and executes an expression out of two based on
the result of the condition.
Syntax
The ternary operator takes 3 operands (condition, expression1 and expression2). Hence,
the name ternary operator.
int main() {
double marks;
cout << "You " << result << " the exam.";
return 0;
}
Run Code
Output 1
Suppose the user enters 80. Then, the condition marks >= 40 evaluates to true. Hence, the first
expression "passed" is assigned to result.
Output 2
Now, suppose the user enters 39.5. Then, the condition marks >= 40 evaluates to false. Hence,
the second expression "failed" is assigned to result.
Note: We should only use the ternary operator if the resulting statement is short.
It is also possible to use one ternary operator inside another ternary operator. It is called the
nested ternary operator in C++.
Here's a program to find whether a number is positive, negative, or zero using the nested ternary
operator.
#include <iostream>
#include <string>
using namespace std;
int main() {
int number = 0;
string result;
return 0;
}
Run Code
Output
Number is Zero
Here,
• (number == 0) is the first test condition that checks if number is 0 or not. If it is, then it
assigns the string value "Zero" to result.
• Else, the secon
Note: It is not recommended to use nested ternary operators. This is because it makes our code
more complex.