In C++ programming, sometimes there is a need to perform some operation more than once or (say) n number of times. For example, suppose we want to print "Hello World" 5 times. Manually, we have to write cout for the C++ statement 5 times as shown.
C++
#include <iostream>
using namespace std;
int main() {
cout << "Hello World\n";
cout << "Hello World\n";
cout << "Hello World\n";
cout << "Hello World\n";
cout << "Hello World";
return 0;
}
OutputHello World
Hello World
Hello World
Hello World
Hello World
Somewhat manageable, right? Let's say you have to write it 20 times. It would surely take more time to write 20 statements. Now imagine you have to write it 100 times. It would be really hectic to re-write the same statement again and again.
In such cases, loops come into play, allowing users to repeatedly execute a block of statements any number of times.
C++
#include <iostream>
using namespace std;
int main() {
for (int i = 0; i < 5; i++) {
cout << "Hello World\n";
}
return 0;
}
OutputHello World
Hello World
Hello World
Hello World
Hello World
In the above program, we have used one of the loops to write "Hello World" 5 times. You can see how much code is reduced. The same line of code can write "Hello World" 20 or even 100 times.
What are Loops?
In C++ programming, a loop is an instruction that is used to repeatedly execute a code until a certain condition remains true. They are useful for performing repetitive tasks without having to write the same code multiple times.
C++ provides three types of loops that works the same, but are preferred in different use cases:
for Loop
The for loop is a type of loop that allows us to write a loop that is executed a specific number of times. It is an entry-controlled loop, which means that it checks whether the test condition is true before executing the statements inside it.
Syntax
C++
for (initialization; condition; updation) {
// body of for loop
}
The various parts of the for loop are:
- Initialization: Initialize the variable to some initial value.
- Test Condition: This specifies the test condition. If the condition evaluates to true, then body of the loop is executed. If evaluated false, loop is terminated.
- Update Expression: After the execution loop's body, this expression increments/decrements the loop variable by some value.
All these together is used to create a logic and flow of the loop.
Example
C++
#include <iostream>
using namespace std;
int main() {
// For loop that starts with i = 1 and ends
// when i is greater than 5.
for (int i = 1; i <= 5; i++) {
cout << i << " ";
}
return 0;
}
There is a type of for loop that does not need the condition and updating statement. It is called range based for loop and it can only be used for iteratable objects such as vector, set, etc.
while Loop
The while loop is also an entry-controlled loop which is used in situations where we do not know the exact number of iterations of the loop beforehand.
While studying for loop, we have seen that the number of iterations is known beforehand, i.e. the number of times the loop body is needed to be executed is known to us and we create the condition on the basis of it. But while loops execution is solely based on the condition.
Syntax
C++
while (condition) {
// Body of the loop
// update expression
}
Only the condition is the part of while loop syntax, we have to initialize and update loop variable manually.
Example
C++
#include <iostream>
using namespace std;
int main() {
// Initialization
int i = 1;
// while loop that starts with i = 1 and ends
// when i is greater than 5.
while (i <= 5) {
cout << i << " ";
// Updation
i++;
}
return 0;
}
do while Loop
The do-while loop is also a loop whose execution is terminated on the basis of test conditions like while loop but this loop is an exit-controlled loop. It means that in do-while loop, the condition is checked after executing the body of the loop. So, in a do-while loop, the loop body will execute at least once irrespective of the test condition.
Syntax
C++
do {
// Body of the loop
// Update expression
} while (condition);
Like while loop, only the condition is the part of do while loop syntax, we have to do the initialization and updation of loop variable manually.
Example
C++
#include <iostream>
using namespace std;
int main() {
// Initialization
int i = 1;
// while loop that starts with i = 1 and ends
// when i is greater than 5.
do {
cout << i << " ";
// Updation
i++;
}while (i <= 5);
return 0;
}
Remember the last semicolon at the end of the loop.
Infinite Loops
An infinite loop (sometimes called an endless loop) is a piece of coding that lacks a functional exit so that it repeats indefinitely. An infinite loop occurs when a condition is always evaluated to be true. Usually, this is an error. We can manually create an infinite loop using all three loops:
Example
C++
#include <iostream>
using namespace std;
int main() {
// This is an infinite for loop as the condition
// expression is blank
for (;;) {
cout << "This loop will run forever.\n";
}
return 0;
}
Output
This loop will run forever.
This loop will run forever.
...................
Nesting of Loops
Nesting of loops refers to placing one loop inside another. The inner loop is executed completely for each iteration of the outer loop. This is useful when you need to perform multiple iterations within each iteration of a larger loop, such as iterating over a two-dimensional array or performing operations that require more than one level of iteration.
Example:
C++
#include <iostream>
using namespace std;
int main() {
for (int i = 0; i < 3; i++) {
// Outer loop runs 3 times
for (int j = 0; j < 2; j++) {
// Inner loop runs 2 times for each
// outer loop iteration
cout << "i = " << i << ", j = " << j << endl;
}
}
return 0;
}
Outputi = 0, j = 0
i = 0, j = 1
i = 1, j = 0
i = 1, j = 1
i = 2, j = 0
i = 2, j = 1
Loop Control Statements
Generally, the normal flow of any loop is that it will repeat till its test condition is true. In each repetition, it will execute the given set of statements. But C++ provides ways to modify this normal flow. This can be done by using loop control statements shown below:
Break out of the Loop
The break statement when encountered, terminates the loop regardless of its test condition. This is useful when the execution of loop is dependent on multiple conditions.
Example:
C++
#include <iostream>
using namespace std;
int main() {
for (int i = 0; i < 5; i++) {
// Terminating before reaching i = 4
if (i == 2) break;
cout << "Hi" << endl;
}
return 0;
}
Skip a Particular Iteration
The continue statement, when encountered, skips the remaining code inside the current iteration of the loop and proceeds to the next iteration. This is useful when you want to skip specific iterations based on certain conditions but still want to continue the loop execution.
Example:
C++
#include <iostream>
using namespace std;
int main() {
for (int i = 0; i < 5; i++) {
// Skipping when i equals 2
if (i == 2) continue;
cout << "Hi" << endl;
}
return 0;
}
Similar Reads
C++ Tutorial | Learn C++ Programming C++ is a popular programming language that was developed as an extension of the C programming language to include OOPs programming paradigm. Since then, it has become foundation of many modern technologies like game engines, web browsers, operating systems, financial systems, etc.Features of C++Why
5 min read
Introduction to c++
Difference between C and C++C++ is often viewed as a superset of C. C++ is also known as a "C with class" This was very nearly true when C++ was originally created, but the two languages have evolved over time with C picking up a number of features that either weren't found in the contemporary version of C++ or still haven't m
3 min read
Setting up C++ Development EnvironmentC++ is a general-purpose programming language and is widely used nowadays for competitive programming. It has imperative, object-oriented, and generic programming features. C++ runs on lots of platforms like Windows, Linux, Unix, Mac, etc. Before we start programming with C++. We will need an enviro
8 min read
Header Files in C++C++ offers its users a variety of functions, one of which is included in header files. In C++, all the header files may or may not end with the ".h" extension unlike in C, Where all the header files must necessarily end with the ".h" extension. Header files in C++ are basically used to declare an in
6 min read
Namespace in C++Name conflicts in C++ happen when different parts of a program use the same name for variables, functions, or classes, causing confusion for the compiler. To avoid this, C++ introduce namespace.Namespace is a feature that provides a way to group related identifiers such as variables, functions, and
6 min read
Writing First C++ Program - Hello World ExampleThe "Hello World" program is the first step towards learning any programming language and is also one of the most straightforward programs you will learn. It is the basic program that demonstrates the working of the coding process. All you have to do is display the message "Hello World" on the outpu
4 min read
Basics
C++ Data TypesData types specify the type of data that a variable can store. Whenever a variable is defined in C++, the compiler allocates some memory for that variable based on the data type with which it is declared as every data type requires a different amount of memory.C++ supports a wide variety of data typ
7 min read
C++ VariablesIn C++, variable is a name given to a memory location. It is the basic unit of storage in a program. The value stored in a variable can be accessed or changed during program execution.Creating a VariableCreating a variable and giving it a name is called variable definition (sometimes called variable
4 min read
Operators in C++C++ operators are the symbols that operate on values to perform specific mathematical or logical computations on given values. They are the foundation of any programming language.Example:C++#include <iostream> using namespace std; int main() { int a = 10 + 20; cout << a; return 0; }Outpu
9 min read
Basic Input / Output in C++In C++, input and output are performed in the form of a sequence of bytes or more commonly known as streams.Input Stream: If the direction of flow of bytes is from the device (for example, Keyboard) to the main memory then this process is called input.Output Stream: If the direction of flow of bytes
5 min read
Control flow statements in ProgrammingControl flow refers to the order in which statements within a program execute. While programs typically follow a sequential flow from top to bottom, there are scenarios where we need more flexibility. This article provides a clear understanding about everything you need to know about Control Flow St
15+ min read
C++ LoopsIn C++ programming, sometimes there is a need to perform some operation more than once or (say) n number of times. For example, suppose we want to print "Hello World" 5 times. Manually, we have to write cout for the C++ statement 5 times as shown.C++#include <iostream> using namespace std; int
7 min read
Functions in C++A function is a building block of C++ programs that contains a set of statements which are executed when the functions is called. It can take some input data, performs the given task, and return some result. A function can be called from anywhere in the program and any number of times increasing the
9 min read
C++ ArraysIn C++, an array is a derived data type that is used to store multiple values of similar data types in a contiguous memory location.Arrays in C++Create an ArrayIn C++, we can create/declare an array by simply specifying the data type first and then the name of the array with its size inside [] squar
10 min read
Strings in C++In C++, strings are sequences of characters that are used to store words and text. They are also used to store data, such as numbers and other types of information in the form of text. Strings are provided by <string> header file in the form of std::string class.Creating a StringBefore using s
5 min read
Core Concepts
Pointers and References in C++In C++ pointers and references both are mechanisms used to deal with memory, memory address, and data in a program. Pointers are used to store the memory address of another variable whereas references are used to create an alias for an already existing variable. Pointers in C++ Pointers in C++ are a
5 min read
new and delete Operators in C++ For Dynamic MemoryIn C++, when a variable is declared, the compiler automatically reserves memory for it based on its data type. This memory is allocated in the program's stack memory at compilation of the program. Once allocated, it cannot be deleted or changed in size. However, C++ offers manual low-level memory ma
6 min read
Templates in C++C++ template is a powerful tool that allows you to write a generic code that can work with any data type. The idea is to simply pass the data type as a parameter so that we don't need to write the same code for different data types.For example, same sorting algorithm can work for different type, so
9 min read
Structures, Unions and Enumerations in C++Structures, unions and enumerations (enums) are 3 user defined data types in C++. User defined data types allow us to create a data type specifically tailored for a particular purpose. It is generally created from the built-in or derived data types. Let's take a look at each of them one by one.Struc
3 min read
Exception Handling in C++In C++, exceptions are unexpected problems or errors that occur while a program is running. For example, in a program that divides two numbers, dividing a number by 0 is an exception as it may lead to undefined errors.The process of dealing with exceptions is known as exception handling. It allows p
11 min read
File Handling through C++ ClassesIn C++, programs run in the computerâs RAM (Random Access Memory), in which the data used by a program only exists while the program is running. Once the program terminates, all the data is automatically deleted. File handling allows us to manipulate files in the secondary memory of the computer (li
8 min read
Multithreading in C++Multithreading is a technique where a program is divided into smaller units of execution called threads. Each thread runs independently but shares resources like memory, allowing tasks to be performed simultaneously. This helps improve performance by utilizing multiple CPU cores efficiently. Multith
5 min read
C++ OOPS
Standard Template Library (STL)
Practice Problem