0% found this document useful (0 votes)
3 views46 pages

Control Flow Statements

The document provides an overview of C++ relational and logical operators, explaining their functions and providing examples for each operator. It covers relational operators such as ==, !=, >, <, >=, and <=, as well as logical operators including &&, ||, and !, detailing how they evaluate expressions to return true or false. Additionally, the document discusses the use of if, if...else, and nested if statements for decision-making in programming.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views46 pages

Control Flow Statements

The document provides an overview of C++ relational and logical operators, explaining their functions and providing examples for each operator. It covers relational operators such as ==, !=, >, <, >=, and <=, as well as logical operators including &&, ||, and !, detailing how they evaluate expressions to return true or false. Additionally, the document discusses the use of if, if...else, and nested if statements for decision-making in programming.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

C++ Relational and Logical Operators

In C++, relational and logical operators compare two or more operands and return either true or
false values.

We use these operators in decision making

C++ Relational Operators

A relational operator is used to check the relationship between two operands. For example,

// checks if a is greater than b


a > b;

Here, > is a relational operator. It checks if a is greater than b or not.

If the relation is true, it returns 1 whereas if the relation is false, it returns 0.

The following table summarizes the relational operators used in C++.

Operator Meaning Example

== Is Equal To 3 == 5 gives us false

!= Not Equal To 3 != 5 gives us true

> Greater Than 3 > 5 gives us false

< Less Than 3 < 5 gives us true

>= Greater Than or Equal To 3 >= 5 give us false

<= Less Than or Equal To 3 <= 5 gives us true

== Operator

The equal to == operator returns

• true - if both the operands are equal or the same


• false - if the operands are unequal

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

The not equal to != operator returns

• true - if both operands are unequal


• false - if both operands are equal.

For example,

int x = 10;
int y = 15;
int z = 10;

x != y // true
x != z // false

> Operator

The greater than > operator returns

• true - if the left operand is greater than the right


• false - if the left operand is less than the right

For example,

int x = 10;
int y = 15;

x > y // false
y > x // true

< Operator

The less than operator < returns

• true - if the left operand is less than the right


• false - if the left operand is greater than right
For example,

int x = 10;
int y = 15;

x < y // true
y < x // false

>= Operator

The greater than or equal to >= operator returns

• 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

The less than or equal to operator <= returns

• 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.

C++ Logical Operators

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.

C++ Logical AND Operator

The logical AND operator && returns

• true - if and only if all the operands are true.


• false - if one or more operands are false.

Truth Table of && Operator

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 &.

Example 1: C++ OR Operator


// C++ program demonstrating && operator truth table

#include <iostream>
using namespace std;

int main() {
int a = 5;
int b = 9;

// false && false = false


cout << ((a == 0) && (a > b)) << endl;

// false && true = false


cout << ((a == 0) && (a < b)) << endl;

// true && false = false


cout << ((a == 5) && (a > b)) << endl;

// true && true = true


cout << ((a == 5) && (a < b)) << endl;

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

((a == 0) && (a > b))

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.

C++ Logical OR Operator

The logical OR operator || returns

• true - if one or more of the operands are true.


• false - if and only if all the operands are false.

Truth Table of || Operator


Let a and b be two operands. Then,

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.

Example 2: C++ OR Operator


// C++ program demonstrating || operator truth table

#include <iostream>
using namespace std;

int main() {
int a = 5;
int b = 9;

// false && false = false


cout << ((a == 0) || (a > b)) << endl;

// false && true = true


cout << ((a == 0) || (a < b)) << endl;

// true && false = true


cout << ((a == 5) || (a > b)) << endl;

// true && true = true


cout << ((a == 5) || (a < b)) << endl;

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

((a == 0) || (a > b))

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.

C++ Logical NOT 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.

Truth Table of the ! Operator

Let a be an operand. Then,

Example 3: C++ ! Operator


// C++ program demonstrating ! operator truth table
#include <iostream>
using namespace std;

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.

Similarly, the expression !(a == 5) ultimately returns false because a == 5 is true.

C++ if, if...else and Nested if...else


In computer programming, we use the if...else statement to run one block of code under
certain conditions and another block of code under different conditions.

For example, assigning grades (A, B, C) based on marks obtained by a student.

1. if the percentage is above 90, assign grade A


2. if the percentage is above 75, assign grade B
3. if the percentage is above 65, assign grade C

C++ if Statement

Syntax

if (condition) {
// body of if statement
}

The if statement evaluates the condition inside the parentheses ( ).

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.

Note: The code inside { } is the body of the if statement.


How if Statement Works

Example 1: C++ if Statement


// Program to print positive number entered by the user
// If the user enters a negative number, it is skipped

#include <iostream>
using namespace std;

int main() {

int number;

cout << "Enter an integer: ";


cin >> number;

// checks if the number is positive


if (number > 0) {
cout << "You entered a positive integer: " << number << endl;
}

cout << "This statement is always executed.";

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

The if statement can have an optional else clause.

Syntax

if (condition) {
// block of code if condition is true
}
else {
// block of code if condition is false
}

The if..else statement evaluates the condition inside the parenthesis.

How if...else Statement Works

If the condition evaluates true,

1. the code inside the body of if is executed


2. the code inside the body of else is skipped from execution
If the condition evaluates false,

1. the code inside the body of else is executed


2. the code inside the body of if is skipped from execution

Example 2: C++ if...else Statement


// Program to check whether an integer is positive or negative
// This program considers 0 as a positive number

#include <iostream>
using namespace std;

int main() {

int number;

cout << "Enter an integer: ";


cin >> number;

if (number >= 0) {
cout << "You entered a positive integer: " << number << endl;
}
else {
cout << "You entered a negative integer: " << number << endl;
}

cout << "This line is always printed.";

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.

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

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,

1. If condition1 evaluates to true, the code block 1 is executed.


2. If condition1 evaluates to false, then condition2 is evaluated.
3. If condition2 is true, the code block 2 is executed.
4. If condition2 is false, the code block 3 is executed.

How if...else if...else Statement Works

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;

cout << "Enter an integer: ";


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

cout << "This line is always printed.";

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.

C++ Nested if...else

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.

Example 4: C++ Nested if


// C++ program to find if an integer is positive, negative or zero
// using nested if statements

#include <iostream>
using namespace std;

int main() {

int num;

cout << "Enter an integer: ";


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

cout << "This line is always printed." << endl;

return 0;
}
Run Code

Output 1

Enter an integer: 35
The number is positive.
This line is always printed.

Output 2

Enter an integer: -35


The number is negative.
This line is always printed.

Output 3

Enter an integer: 0
The number is 0 and it is neither positive nor negative.
This line is always printed.

In the above example,

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.

Body of if...else With Only One Statement

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;

The output of both programs will be the same.

Note: Although it's not necessary to use { } if the body of if...else has only one statement,
using { } makes your code more readable.

More on Decision Making

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:

1. C++ Program to Check Whether Number is Even or Odd


2. C++ Program to Check Whether a Character is Vowel or Consonant.
3. C++ Program to Find Largest Number Among Three Numbers

C++ for Loop


In computer programming, loops are used to repeat a block of code.

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.

There are 3 types of loops in C++.

• 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.

C++ for loop

The syntax of for-loop is:

for (initialization; condition; update) {


// body of-loop
}

Here,

• initialization - initializes variables and is executed only once


• condition - if true, the body of for loop is executed
if false, the for loop is terminated
• update - updates the value of initialized variables and again checks the condition

To learn more about conditions, check out our tutorial on C++ Relational and Logical
Operators.
Flowchart of for Loop in C++

Flowchart of for loop in C++

Example 1: Printing Numbers From 1 to 5


#include <iostream>

using namespace std;

int main() {
for (int i = 1; i <= 5; ++i) {
cout << i << " ";
}
return 0;
}
Run Code
Output

1 2 3 4 5

Here is how this program works

Iteration Variable i Action

1st i = 1 true 1 is printed. i is increased to 2.

2nd i = 2 true 2 is printed. i is increased to 3.

3rd i = 3 true 3 is printed. i is increased to 4.

4th i = 4 true 4 is printed. i is increased to 5.

5th i = 5 true 5 is printed. i is increased to 6.

6th i = 6 false The loop is terminated

Example 2: Display a text 5 times


// C++ Program to display a text 5 times

#include <iostream>

using namespace std;

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!

Here is how this program works

Iteration Variable i Action

1st i = 1 true Hello World! is printed and i is increased to 2.


2nd i = 2 true Hello World! is printed and i is increased to 3.

3rd i = 3 true Hello World! is printed and i is increased to 4.

4th i = 4 true Hello World! is printed and i is increased to 5.

5th i = 5 true Hello World! is printed and i is increased to 6.

6th i = 6 false The loop is terminated

Example 3: Find the sum of first n Natural Numbers


// C++ program to find the sum of first n natural numbers
// positive integers such as 1,2,3,...n are known as natural numbers

#include <iostream>

using namespace std;

int main() {
int num, sum;
sum = 0;

cout << "Enter a positive integer: ";


cin >> num;

for (int i = 1; i <= num; ++i) {


sum += i;
}

cout << "Sum = " << sum << endl;

return 0;
}
Run Code

Output

Enter a positive integer: 10


Sum = 55

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.

Note that we have used a for loop.

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

Here,

• int i = 1: initializes the i variable


• i <= num: runs the loop as long as i is less than or equal to num
• ++i: increases the i variable by 1 in each iteration

When i becomes 11, the condition is false and sum will be equal to 0 + 1 + 2 + ... + 10.

Ranged Based for Loop

In C++11, a new range-based for loop was introduced to work with collections such as arrays
and vectors. Its syntax is:

for (variable : collection) {


// body of loop
}

Here, for every value in the collection, the for loop is executed and the value is assigned to the
variable.

Example 4: Range Based for Loop


#include <iostream>

using namespace std;

int main() {

int num_array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

for (int n : num_array) {


cout << n << " ";
}

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,

// infinite for loop


for(int i = 1; i > 0; i++) {
// block of code
}

In the above program, the condition is always true which will then run the code for infinite
times.

Also Read:

• while and do...while loop


• C++ Program to Calculate Sum of Natural Numbers
• C++ Program to Find Factorial

C++ while and do...while Loop


In computer programming, loops are used to repeat a block of code.

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.

There are 3 types of loops in C++.

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

The syntax of the while loop is:

while (condition) {
// body of the loop
}

Here,

• A while loop evaluates the condition


• If the condition evaluates to true, the code inside the while loop is executed.
• The condition is evaluated again.
• This process continues until the condition is false.
• When the condition evaluates to false, the loop terminates.

To learn more about the conditions, visit C++ Relational and Logical Operators.

Flowchart of while Loop

Flowchart of C++ while loop


Example 1: Display Numbers from 1 to 5
// C++ Program to print numbers from 1 to 5

#include <iostream>

using namespace std;

int main() {
int i = 1;

// while loop from 1 to 5


while (i <= 5) {
cout << i << " ";
++i;
}

return 0;
}
Run Code

Output

1 2 3 4 5

Here is how the program works.

Iteration Variable i <= 5 Action

1st i = 1 true 1 is printed and i is increased to 2.

2nd i = 2 true 2 is printed and i is increased to 3.

3rd i = 3 true 3 is printed and i is increased to 4

4th i = 4 true 4 is printed and i is increased to 5.

5th i = 5 true 5 is printed and i is increased to 6.

6th i = 6 false The loop is terminated

Example 2: Sum of Positive Numbers Only


// program to find the sum of positive numbers
// if the user enters a negative number, the loop ends
// the negative number entered is not added to the sum

#include <iostream>
using namespace std;

int main() {
int number;
int sum = 0;

// take input from the user


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

while (number >= 0) {


// add all positive numbers
sum += number;

// take input again if the number is positive


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

// display the sum


cout << "\nThe sum is " << sum << endl;

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.

C++ do...while Loop

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.

Its syntax is:


do {
// body of loop;
}
while (condition);

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.

Flowchart of do...while Loop

Flowchart of C++ do...while loop

Example 3: Display Numbers from 1 to 5


// C++ Program to print numbers from 1 to 5

#include <iostream>
using namespace std;

int main() {
int i = 1;

// do...while loop from 1 to 5


do {
cout << i << " ";
++i;
}
while (i <= 5);

return 0;
}
Run Code

Output

1 2 3 4 5

Here is how the program works.

Iteration Variable i <= 5 Action

i = 1 not checked 1 is printed and i is increased to 2

1st i = 2 true 2 is printed and i is increased to 3

2nd i = 3 true 3 is printed and i is increased to 4

3rd i = 4 true 4 is printed and i is increased to 5

4th i = 5 true 5 is printed and i is increased to 6

5th i = 6 false The loop is terminated

Example 4: Sum of Positive Numbers Only


// program to find the sum of positive numbers
// If the user enters a negative number, the loop ends
// the negative number entered is not added to the sum

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

// display the sum


cout << "\nThe sum is " << sum << endl;

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.

Infinite while loop

If the condition of a loop is always true, the loop runs for infinite times (until the memory is
full). For example,

// infinite while loop


while(true) {
// body of the loop
}

Here is an example of an infinite do...while loop.

// infinite do...while loop

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.

for vs while loops

A for loop is usually used when the number of iterations is known. For example,

// This loop is iterated 5 times


for (int i = 1; i <=5; ++i) {
// body of the loop
}

Here, we know that the for-loop will be executed 5 times.

However, while and do...while loops are usually used when the number of iterations is
unknown. For example,

while (condition) {
// body of the loop
}

C++ break Statement


In C++, the break statement terminates the loop when it is encountered.

The syntax of the break statement is:

break;

Before you learn about the break statement, make sure you know about:

• C++ for loop


• C++ if...else
• C++ while loop
Working of C++ break Statement

Working of break statement in C++

Example 1: break with for loop


// program to print the value of i

#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.

Note: The break statement is usually used with decision-making statements.

Example 2: break with while loop


// program to find the sum of positive numbers
// if the user enters a negative numbers, break ends the loop
// the negative number entered is not added to sum

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

// add all positive numbers


sum += number;
}

// display the sum


cout << "The sum is " << sum << endl;

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.

break with Nested loop

When break is used with nested loops, break terminates the inner loop. For example,

// using break statement inside


// nested for loop

#include <iostream>
using namespace std;

int main() {
int number;
int sum = 0;

// nested for loops

// 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.

Hence, the value of i = 2 is never displayed in the output.

The break statement is also used with the switch statement. To learn more, visit C++ switch
statement.

Also Read:

• C++ continue Statement

C++ continue Statement


In computer programming, the continue statement is used to skip the current iteration of the
loop and the control of the program goes to the next iteration.

The syntax of the continue statement is:

continue;

Before you learn about the continue statement, make sure you know about,

• C++ for loop


• C++ if...else
• C++ while loop
Working of C++ continue Statement

Working of continue statement in


C++

Example 1: continue with for loop

In a for loop, continue skips the current iteration and the control flow jumps to the update
expression.

// program to print the value of i

#include <iostream>
using namespace std;

int main() {
for (int i = 1; i <= 5; i++) {
// condition to continue
if (i == 3) {
continue;
}

cout << i << endl;


}
return 0;
}
Run Code

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.

Example 2: continue with while loop

In a while loop, continue skips the current iteration and control flow of the program jumps
back to the while condition.

// program to calculate positive numbers till 50 only


// if the user enters a negative number,
// that number is skipped from the calculation

// negative number -> loop terminate


// numbers above 50 -> skip iteration

#include <iostream>
using namespace std;

int main() {
int sum = 0;
int number = 0;

while (number >= 0) {


// add all positive numbers
sum += number;

// take input from the user


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

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

// display the sum


cout << "The sum is " << sum << endl;

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.

Notice the use of the continue statement.

if (number > 50){


continue;
}

• 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,

// using continue statement inside


// nested for loop

#include <iostream>
using namespace std;

int main() {
int number;
int sum = 0;

// nested for loops

// 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.

Hence, the value of j = 2 is never displayed in the output.

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.

Syntax of goto Statement


goto label;
... .. ...
... .. ...
... .. ...
label:
statement;
... .. ...

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.

Working of goto in C++

Example: goto Statement


// This program calculates the average of numbers entered by the user.
// If the user enters a negative number, it ignores the number and
// calculates the average number entered before it.

# include <iostream>
using namespace std;

int main()
{
float num, average, sum = 0.0;
int i, n;

cout << "Maximum number of inputs: ";


cin >> n;

for(i = 1; i <= n; ++i)


{
cout << "Enter n" << i << ": ";
cin >> num;
if(num < 0.0)
{
// Control of the program move to jump:
goto jump;
}
sum += num;
}

jump:
average = sum / (i - 1);
cout << "\nAverage = " << average;
return 0;
}

Output

Maximum number of inputs: 10


Enter n1: 2.3
Enter n2: 5.6
Enter n3: -5.6

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.

Reason to Avoid goto Statement

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.

C++ switch..case Statement


The switch statement allows us to execute a block of code among many alternatives.

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
}

How does the switch statement work?

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

Enter an operator (+, -, *, /): +


Enter two numbers:
2.3
4.5
2.3 + 4.5 = 6.8

Output 2

Enter an operator (+, -, *, /): -


Enter two numbers:
2.3
4.5
2.3 - 4.5 = -2.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

Enter an operator (+, -, *, /): *


Enter two numbers:
2.3
4.5
2.3 * 4.5 = 10.35

Output 4

Enter an operator (+, -, *, /): /


Enter two numbers:
2.3
4.5
2.3 / 4.5 = 0.511111

Output 5

Enter an operator (+, -, *, /): ?


Enter two numbers:
2.3
4.5
Error! The operator is not correct.

In the above program, we are using the switch...case statement to perform addition,
subtraction, multiplication, and division.

How This Program Works

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.

C++ Ternary Operator


In C++, the ternary operator is a concise, inline method used to execute one of two expressions
based on a condition. It is also called the conditional operator.

Ternary Operator in C++

A ternary operator evaluates the test condition and executes an expression out of two based on
the result of the condition.

Syntax

condition ? expression1 : expression2;

Here, condition is evaluated and

• if condition is true, expression1 is executed.


• if condition is false, expression2 is executed.

The ternary operator takes 3 operands (condition, expression1 and expression2). Hence,
the name ternary operator.

Example: C++ Ternary Operator


#include <iostream>
#include <string>
using namespace std;

int main() {
double marks;

// take input from users


cout << "Enter your marks: ";
cin >> marks;

// ternary operator checks if


// marks is greater than 40
string result = (marks >= 40) ? "passed" : "failed";

cout << "You " << result << " the exam.";

return 0;
}
Run Code

Output 1

Enter your marks: 80


You passed the exam.

Suppose the user enters 80. Then, the condition marks >= 40 evaluates to true. Hence, the first
expression "passed" is assigned to result.

Output 2

Enter your marks: 39.5


You failed the exam.

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.

Nested Ternary Operators

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;

// nested ternary operator to find whether


// number is positive, negative, or zero
result = (number == 0) ? "Zero" : ((number > 0) ? "Positive" : "Negative");

cout << "Number is " << result;

return 0;
}
Run Code

Output

Number is Zero

In the above example, notice the use of ternary operators,

(number == 0) ? "Zero" : ((number > 0) ? "Positive" : "Negative");

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

• d test condition (number > 0) is evaluated if the first condition is false.

Note: It is not recommended to use nested ternary operators. This is because it makes our code
more complex.

You might also like