The figure below shows how recursion works by calling itself over and over again.
How recursion works in C++ programming
The recursion continues until some condition is met.
To prevent infinite recursion, if…else statement (or similar approach) can be used where one branch makes the recursive call and the other doesn’t.
Example 1: Factorial of a Number Using Recursion
// Factorial of n = 1*2*3*...*n
#include <iostream>
using namespace std;
int factorial(int);
int main() {
int n, result;
cout << "Enter a non-negative number: ";
cin >> n;
result = factorial(n);
cout << "Factorial of " << n << " = " << result;
return 0;
}
int factorial(int n) {
if (n > 1) {
return n * factorial(n - 1);
} else {
return 1;
}
}
Output
Enter a non-negative number: 4
Factorial of 4 = 24
Working of Factorial Program
How this C++ recursion program works
As we can see, the factorial() function is calling itself. However, during each call, we have decreased the value of n by 1. When n is less than 1, the factorial() function ultimately returns the output.
Advantages and Disadvantages of Recursion
Below are the pros and cons of using recursion in C++.
Advantages of C++ Recursion
It makes our code shorter and cleaner.
Recursion is required in problems concerning data structures and advanced algorithms, such as Graph and Tree Traversal.
Disadvantages of C++ Recursion
It takes a lot of stack space compared to an iterative program.
It uses more processor time.
It can be more difficult to debug compared to an equivalent iterative program.
In this article, you’ll learn about different storage classes in C++. Namely: local, global, static local, register and thread local.
Every variable in C++ has two features: type and storage class.
Type specifies the type of data that can be stored in a variable. For example: int, float, char etc.
And, storage class controls two different properties of a variable: lifetime (determines how long a variable can exist) and scope (determines which part of the program can access it).
Depending upon the storage class of a variable, it can be divided into 4 major types:
Local variable
Global variable
Static local variable
Register Variable
Thread Local Storage
Local Variable
A variable defined inside a function (defined inside function body between braces) is called a local variable or automatic variable.
Its scope is only limited to the function where it is defined. In simple terms, local variable exists and can be accessed only inside a function.
The life of a local variable ends (It is destroyed) when the function exits.
Example 1: Local variable
#include <iostream>
using namespace std;
void test();
int main()
{
// local variable to main()
int var = 5;
test();
// illegal: var1 not declared inside main()
var1 = 9;
}
void test()
{
// local variable to test()
int var1;
var1 = 6;
// illegal: var not declared inside test()
cout << var;
}
The variable var cannot be used inside test() and var1 cannot be used inside main() function.
Keyword auto was also used for defining local variables before as: auto int var;
But, after C++11 auto has a different meaning and should not be used for defining local variables.
Global Variable
If a variable is defined outside all functions, then it is called a global variable.
The scope of a global variable is the whole program. This means, It can be used and changed at any part of the program after its declaration.
Likewise, its life ends only when the program ends.
Example 2: Global variable
#include <iostream>
using namespace std;
// Global variable declaration
int c = 12;
void test();
int main()
{
++c;
// Outputs 13
cout << c <<endl;
test();
return 0;
}
void test()
{
++c;
// Outputs 14
cout << c;
}
Output
13
14
In the above program, c is a global variable.
This variable is visible to both functions main() and test() in the above program.
Static Local variable
Keyword static is used for specifying a static variable. For example:
A static local variable exists only inside a function where it is declared (similar to a local variable) but its lifetime starts when the function is called and ends only when the program ends.
The main difference between local variable and static variable is that, the value of static variable persists the end of the program.
Example 3: Static local variable
#include <iostream>
using namespace std;
void test()
{
// var is a static variable
static int var = 0;
++var;
cout << var << endl;
}
int main()
{
test();
test();
return 0;
}
Output
1
2
In the above program, test() function is invoked 2 times.
During the first call, variable var is declared as static variable and initialized to 0. Then 1 is added to var which is displayed in the screen.
When the function test() returns, variable var still exists because it is a static variable.
During second function call, no new variable var is created. The same var is increased by 1 and then displayed to the screen.
Output of above program if var was not specified as static variable
1
1
Register Variable (Deprecated in C++11)
Keyword register is used for specifying register variables.
Register variables are similar to automatic variables and exists inside a particular function only. It is supposed to be faster than the local variables.
If a program encounters a register variable, it stores the variable in processor’s register rather than memory if available. This makes it faster than the local variables.
However, this keyword was deprecated in C++11 and should not be used.
Thread Local Storage
Thread-local storage is a mechanism by which variables are allocated such that there is one instance of the variable per extant thread.
In this tutorial, we will learn C++ default arguments and their working with the help of examples.
In C++ programming, we can provide default values for function parameters.
If a function with default arguments is called without passing arguments, then the default parameters are used.
However, if arguments are passed while calling the function, the default arguments are ignored.
Working of default arguments
How default arguments work in C++
We can understand the working of default arguments from the image above:
When temp() is called, both the default parameters are used by the function.
When temp(6) is called, the first argument becomes 10 while the default value is used for the second parameter.
When temp(6, -2.3) is called, both the default parameters are overridden, resulting in i = 6 and f = -2.3.
When temp(3.4) is passed, the function behaves in an undesired way because the second argument cannot be passed without passing the first argument.
Therefore, 3.4 is passed as the first argument. Since the first argument has been defined as int, the value that is actually passed is 3.
Example: Default Argument
#include <iostream>
using namespace std;
// defining the default arguments
void display(char = '*', int = 3);
int main() {
int count = 5;
cout << "No argument passed: ";
// *, 3 will be parameters
display();
cout << "First argument passed: ";
// #, 3 will be parameters
display('#');
cout << "Both arguments passed: ";
// $, 5 will be parameters
display('$', count);
return 0;
}
void display(char c, int count) {
for(int i = 1; i <= count; ++i)
{
cout << c;
}
cout << endl;
}
Output
No argument passed: ***
First argument passed: ###
Both arguments passed: $$$$$
Here is how this program works:
display() is called without passing any arguments. In this case, display() uses both the default parameters c = '*' and n = 1.
display('#') is called with only one argument. In this case, the first becomes '#'. The second default parameter n = 1 is retained.
display('#', count) is called with both arguments. In this case, default arguments are not used.
We can also define the default parameters in the function definition itself. The program below is equivalent to the one above.
#include <iostream>
using namespace std;
// defining the default arguments
void display(char c = '*', int count = 3) {
for(int i = 1; i <= count; ++i) {
cout << c;
}
cout << endl;
}
int main() {
int count = 5;
cout << "No argument passed: ";
// *, 3 will be parameters
display();
cout << "First argument passed: ";
// #, 3 will be parameters
display('#');
cout << "Both argument passed: ";
// $, 5 will be parameters
display('$', count);
return 0;
}
Run Code
Things to Remember
Once we provide a default value for a parameter, all subsequent parameters must also have default values. For example,// Invalid void add(int a, int b = 3, int c, int d); // Invalid void add(int a, int b = 3, int c, int d = 4); // Valid void add(int a, int c, int b = 3, int d = 4);
If we are defining the default arguments in the function definition instead of the function prototype, then the function must be defined before the function call. // Invalid code int main() { // function call display(); } void display(char c = '*', int count = 5) { // code }
In this tutorial, we will learn about the function overloading in C++ with examples.
In C++, two functions can have the same name if the number and/or type of arguments passed is different.
These functions having the same name but different arguments are known as overloaded functions. For example:
// same number different arguments
int test() { }
int test(int a) { }
float test(double a) { }
int test(int a, double b) { }
Here, all 4 functions are overloaded functions.
Notice that the return types of all these 4 functions are not the same. Overloaded functions may or may not have different return types but they must have different arguments. For example,
// Error code
int test(int a) { }
double test(int b){ }
Here, both functions have the same name, the same type, and the same number of arguments. Hence, the compiler will throw an error.
Function Overloading using Different Types of Parameter
// Program to compute absolute value
// Works for both int and float
#include <iostream>
using namespace std;
// function with float type parameter
float absolute(float var){
if (var < 0.0)
var = -var;
return var;
}
// function with int type parameter
int absolute(int var) {
if (var < 0)
var = -var;
return var;
}
int main() {
// call function with int type parameter
cout << "Absolute value of -5 = " << absolute(-5) << endl;
// call function with float type parameter
cout << "Absolute value of 5.5 = " << absolute(5.5f) << endl;
return 0;
}
Run Code
Output
Absolute value of -5 = 5
Absolute value of 5.5 = 5.5
Working of overloading for the absolute() function
In this program, we overload the absolute() function. Based on the type of parameter passed during the function call, the corresponding function is called.
Function Overloading using Different Number of Parameters
#include <iostream>
using namespace std;
// function with 2 parameters
void display(int var1, double var2) {
cout << "Integer number: " << var1;
cout << " and double number: " << var2 << endl;
}
// function with double type single parameter
void display(double var) {
cout << "Double number: " << var << endl;
}
// function with int type single parameter
void display(int var) {
cout << "Integer number: " << var << endl;
}
int main() {
int a = 5;
double b = 5.5;
// call function with int type parameter
display(a);
// call function with double type parameter
display(b);
// call function with 2 parameters
display(a, b);
return 0;
}
Here, the display() function is called three times with different arguments. Depending on the number and type of arguments passed, the corresponding display() function is called.
Working of overloading for the display() function
The return type of all these functions is the same but that need not be the case for function overloading.
Note: In C++, many standard library functions are overloaded. For example, the sqrt() function can take double, float, int, etc. as parameters. This is possible because the sqrt() function is overloaded in C++.
In this tutorial, you will learn about different approaches you can take to solve a single problem using functions.
For better understanding of arguments and return in functions, user-defined functions can be categorised as:
Function with no argument and no return value
Function with no argument but return value
Function with argument but no return value
Function with argument and return value
Consider a situation in which you have to check prime number. This problem is solved below by making user-defined function in 4 different ways as mentioned above.
Example 1: No arguments passed and no return value
# include <iostream>
using namespace std;
void prime();
int main()
{
// No argument is passed to prime()
prime();
return 0;
}
// Return type of function is void because value is not returned.
void prime()
{
int num, i, flag = 0;
cout << "Enter a positive integer enter to check: ";
cin >> num;
for(i = 2; i <= num/2; ++i)
{
if(num % i == 0)
{
flag = 1;
break;
}
}
if (flag == 1)
{
cout << num << " is not a prime number.";
}
else
{
cout << num << " is a prime number.";
}
}
In the above program, prime() is called from the main() with no arguments.
prime() takes the positive number from the user and checks whether the number is a prime number or not.
Since, return type of prime() is void, no value is returned from the function.
Example 2: No arguments passed but a return value
#include <iostream>
using namespace std;
int prime();
int main()
{
int num, i, flag = 0;
// No argument is passed to prime()
num = prime();
for (i = 2; i <= num/2; ++i)
{
if (num%i == 0)
{
flag = 1;
break;
}
}
if (flag == 1)
{
cout<<num<<" is not a prime number.";
}
else
{
cout<<num<<" is a prime number.";
}
return 0;
}
// Return type of function is int
int prime()
{
int n;
printf("Enter a positive integer to check: ");
cin >> n;
return n;
}
In the above program, prime() function is called from the main() with no arguments.
prime() takes a positive integer from the user. Since, return type of the function is an int, it returns the inputted number from the user back to the calling main() function.
Then, whether the number is prime or not is checked in the main() itself and printed onto the screen.
Example 3: Arguments passed but no return value
#include <iostream>
using namespace std;
void prime(int n);
int main()
{
int num;
cout << "Enter a positive integer to check: ";
cin >> num;
// Argument num is passed to the function prime()
prime(num);
return 0;
}
// There is no return value to calling function. Hence, return type of function is void. */
void prime(int n)
{
int i, flag = 0;
for (i = 2; i <= n/2; ++i)
{
if (n%i == 0)
{
flag = 1;
break;
}
}
if (flag == 1)
{
cout << n << " is not a prime number.";
}
else {
cout << n << " is a prime number.";
}
}
In the above program, positive number is first asked from the user which is stored in the variable num.
Then, num is passed to the prime() function where, whether the number is prime or not is checked and printed.
Since, the return type of prime() is a void, no value is returned from the function.
Example 4: Arguments passed and a return value.
#include <iostream>
using namespace std;
int prime(int n);
int main()
{
int num, flag = 0;
cout << "Enter positive integer to check: ";
cin >> num;
// Argument num is passed to check() function
flag = prime(num);
if(flag == 1)
cout << num << " is not a prime number.";
else
cout<< num << " is a prime number.";
return 0;
}
/* This function returns integer value. */
int prime(int n)
{
int i;
for(i = 2; i <= n/2; ++i)
{
if(n % i == 0)
return 1;
}
return 0;
}
In the above program, a positive integer is asked from the user and stored in the variable num.
Then, num is passed to the function prime() where, whether the number is prime or not is checked.
Since, the return type of prime() is an int, 1 or 0 is returned to the main() calling function. If the number is a prime number, 1 is returned. If not, 0 is returned.
Back in the main() function, the returned 1 or 0 is stored in the variable flag, and the corresponding text is printed onto the screen.
Which method is better?
All four programs above gives the same output and all are technically correct program.
There is no hard and fast rule on which method should be chosen.
The particular method is chosen depending upon the situation and how you want to solve a problem.
the empty parentheses mean it doesn’t have any parameters
the function body is written inside {}
Note: We will learn about returnType and parameters later in this tutorial.
Calling a Function
In the above program, we have declared a function named greet(). To use the greet() function, we need to call it.
Here’s how we can call the above greet() function.
int main() {
// calling a function
greet();
}
How Function works in C++
Example 1: Display a Text
#include <iostream>
using namespace std;
// declaring a function
void greet() {
cout << "Hello there!";
}
int main() {
// calling the function
greet();
return 0;
}
Run Code
Output
Hello there!
Function Parameters
As mentioned above, a function can be declared with parameters (arguments). A parameter is a value that is passed when declaring a function.
For example, let us consider the function below:
void printNum(int num) {
cout << num;
}
Here, the int variable num is the function parameter.
We pass a value to the function parameter while calling the function.
int main() {
int n = 7;
// calling the function
// n is passed to the function as argument
printNum(n);
return 0;
}
Example 2: Function with Parameters
// program to print a text
#include <iostream>
using namespace std;
// display a number
void displayNum(int n1, float n2) {
cout << "The int number is " << n1;
cout << "The double number is " << n2;
}
int main() {
int num1 = 5;
double num2 = 5.5;
// calling the function
displayNum(num1, num2);
return 0;
}
Run Code
Output
The int number is 5
The double number is 5.5
In the above program, we have used a function that has one int parameter and one double parameter.
We then pass num1 and num2 as arguments. These values are stored by the function parameters n1 and n2 respectively.
C++ function with parameters
Note: The type of the arguments passed while calling the function must match with the corresponding parameters defined in the function declaration.
Return Statement
In the above programs, we have used void in the function declaration. For example,
void displayNumber() {
// code
}
This means the function is not returning any value.
It’s also possible to return a value from a function. For this, we need to specify the returnType of the function during function declaration.
Then, the return statement can be used to return a value from a function.
For example,
int add (int a, int b) {
return (a + b);
}
Here, we have the data type int instead of void. This means that the function returns an int value.
The code return (a + b); returns the sum of the two parameters as the function value.
The return statement denotes that the function has ended. Any code after return inside the function is not executed.
Example 3: Add Two Numbers
// program to add two numbers using a function
#include <iostream>
using namespace std;
// declaring a function
int add(int a, int b) {
return (a + b);
}
int main() {
int sum;
// calling the function and storing
// the returned value in sum
sum = add(100, 78);
cout << "100 + 78 = " << sum << endl;
return 0;
}
Run Code
Output
100 + 78 = 178
In the above program, the add() function is used to find the sum of two numbers.
We pass two int literals 100 and 78 while calling the function.
We store the returned value of the function in the variable sum, and then we print it.
Working of C++ Function with return statement
Notice that sum is a variable of int type. This is because the return value of add() is of int type.
Function Prototype
In C++, the code of function declaration should be before the function call. However, if we want to define a function after the function call, we need to use the function prototype. For example,
// function prototype
void add(int, int);
int main() {
// calling the function before declaration.
add(5, 3);
return 0;
}
// function definition
add(int a, int b) {
cout < (a + n);
}
In the above code, the function prototype is:
void add(int, int);
This provides the compiler with information about the function name and its parameters. That’s why we can use the code to call a function before the function has been defined.
// using function definition after main() function
// function prototype is declared before main()
#include <iostream>
using namespace std;
// function prototype
int add(int, int);
int main() {
int sum;
// calling the function and storing
// the returned value in sum
sum = add(100, 78);
cout << "100 + 78 = " << sum << endl;
return 0;
}
// function definition
int add(int a, int b) {
return (a + b);
}
Run Code
Output
100 + 78 = 178
The above program is nearly identical to Example 3. The only difference is that here, the function is defined after the function call.
That’s why we have used a function prototype in this example.
Benefits of Using User-Defined Functions
Functions make the code reusable. We can declare them once and use them multiple times.
Functions make the program easier as each small task is divided into a function.
Functions increase readability.
C++ Library Functions
Library functions are the built-in functions in C++ programming.
Programmers can use library functions by invoking the functions directly; they don’t need to write the functions themselves.
Some common library functions in C++ are sqrt(), abs(), isdigit(), etc.
In order to use library functions, we usually need to include the header file in which these library functions are defined.
For instance, in order to use mathematical functions such as sqrt() and abs(), we need to include the header file cmath.
Example 5: C++ Program to Find the Square Root of a Number
#include <iostream>
#include <cmath>
using namespace std;
int main() {
double number, squareRoot;
number = 25.0;
// sqrt() is a library function to calculate the square root
squareRoot = sqrt(number);
cout << "Square root of " << number << " = " << squareRoot;
return 0;
}
Run Code
Output
Square root of 25 = 5
In this program, the sqrt() library function is used to calculate the square root of a number.
The function declaration of sqrt() is defined in the cmath header file. That’s why we need to use the code #include <cmath> to use the sqrt() function.
To learn more, visit C++ Standard Library functions.
In this article, you’ll learn about goto statment, how it works and why should it be avoided.
In C++ programming, 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.
Example: goto Statement
// This program calculates the average of numbers entered by user.
// If user enters negative number, it ignores the number and
// calculates the average of 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 power to jump to any part of program but, makes the logic of the program complex and tangled.
In modern programming, 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.
In this tutorial, we will learn about switch statement and its working in C++ programming with the help of some examples.
The switch statement allows us to execute a block of code among many alternatives.
The syntax of the switch statement in C++ is:
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
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
Notice that the break statement is used inside each case block. This terminates the switch statement.
If the break statement is not used, all cases after the correct case are executed.
We first prompt the user to enter the desired operator. This input is then stored in the char variable named oper.
We then prompt the user to enter two numbers, which are stored in the float variables num1 and num2.
The switch statement is then used to check the operator entered by the user:
If the user enters +, addition is performed on the numbers.
If the user enters -, subtraction is performed on the numbers.
If the user enters *, multiplication is performed on the numbers.
If the user enters /, division is performed on the numbers.
If the user enters any other character, the default code is printed.
// 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.
// 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.
// 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,