codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
⚡

C++ Programming

16 / 87 topics
14if, if...else, and Nested if...else15switch..case Statement16Loops17Jump Statements: break, continue, goto
Tutorials/C++ Programming/Loops
⚡C++ Programming

Loops

Updated 2026-05-12
30 min read

Loops

In programming, loops are essential constructs that allow you to execute a block of code repeatedly until a certain condition is met. They are fundamental for tasks like iterating over data structures, performing repetitive calculations, and more. Understanding loops is crucial as they enable efficient and concise code execution.

In this tutorial, we will explore different types of loops in C++: for loop, range-based for loop, while loop, do-while loop, nested loops, and infinite loops. Each type has its own use cases and syntax, which we'll cover with detailed explanations and examples.

Introduction to Loops

Loops are control structures that allow a program to repeatedly execute a block of code until a specified condition is met. They help in automating repetitive tasks, making your code more efficient and easier to maintain.

  • For Loop: Used when the number of iterations is known beforehand.
  • Range-based For Loop: Introduced in C++11, simplifies looping over arrays and other iterable data structures.
  • While Loop: Executes as long as a condition remains true.
  • Do-While Loop: Similar to a while loop but guarantees at least one execution of the loop body.
  • Nested Loops: Loops inside another loop, useful for multi-dimensional data processing.
  • Infinite Loops: Loops that continue indefinitely until an explicit exit condition is met.

For Loop

The for loop is used when you know the number of iterations in advance. It consists of three parts: initialization, condition, and increment/decrement expression.

Syntax

C++
1for (initialization; condition; increment/decrement) {
2 // code to be executed
3}
  • Initialization: Executed once before the loop starts.
  • Condition: Checked before each iteration. If true, the loop body executes; if false, the loop terminates.
  • Increment/Decrement: Executed after each iteration.

Example

Let's print numbers from 1 to 5 using a for loop.

for_loop.cpp
1#include <iostream>
2using namespace std;
3
4int main() {
5 for (int i = 1; i <= 5; i++) {
6 cout << "Number: " << i << endl;
7 }
8 return 0;
9}
Output
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5

Common Mistakes

  • Forgetting to update the loop variable (e.g., i++) can lead to infinite loops.
  • Incorrect initialization or condition can cause the loop to skip iterations or not execute at all.

Range-based For Loop

Introduced in C++11, the range-based for loop simplifies iterating over arrays and other iterable data structures like vectors. It automatically handles the iteration variable and index management.

Syntax

C++
1for (auto element : container) {
2 // code to be executed
3}
  • element: A copy of each element in the container.
  • container: The iterable data structure (e.g., array, vector).

Example

Let's print elements of an integer array using a range-based for loop.

range_based_for.cpp
1#include <iostream>
2using namespace std;
3
4int main() {
5 int numbers[] = {10, 20, 30, 40, 50};
6 for (auto num : numbers) {
7 cout << "Number: " << num << endl;
8 }
9 return 0;
10}
Output
Number: 10
Number: 20
Number: 30
Number: 40
Number: 50

Tips

  • Use auto to automatically deduce the type of elements in the container.
  • Modifying the element inside the loop (e.g., num = 100) will not affect the original array unless you use a reference (auto& num).

While Loop

The while loop executes as long as a specified condition is true. It's useful when the number of iterations isn't known beforehand.

Syntax

C++
1while (condition) {
2 // code to be executed
3}
  • Condition: Checked before each iteration. If true, the loop body executes; if false, the loop terminates.

Example

Let's print numbers from 1 to 5 using a while loop.

while_loop.cpp
1#include <iostream>
2using namespace std;
3
4int main() {
5 int i = 1;
6 while (i <= 5) {
7 cout << "Number: " << i << endl;
8 i++;
9 }
10 return 0;
11}
Output
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5

Common Mistakes

  • Forgetting to update the loop variable can lead to infinite loops.
  • Incorrect initial values or conditions can cause the loop to skip iterations or not execute at all.

Do-While Loop

The do-while loop is similar to a while loop but guarantees that the loop body executes at least once. The condition is checked after each iteration.

Syntax

C++
1do {
2 // code to be executed
3} while (condition);
  • Condition: Checked after each iteration. If true, the loop continues; if false, the loop terminates.

Example

Let's print numbers from 1 to 5 using a do-while loop.

do_while_loop.cpp
1#include <iostream>
2using namespace std;
3
4int main() {
5 int i = 1;
6 do {
7 cout << "Number: " << i << endl;
8 i++;
9 } while (i <= 5);
10 return 0;
11}
Output
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5

Tips

  • Use a do-while loop when you need to ensure the loop body executes at least once, regardless of the condition.

Nested Loops

Nested loops are loops inside another loop. They are useful for processing multi-dimensional data structures like matrices or nested arrays.

Syntax

C++
1for (initialization; condition; increment/decrement) {
2 // outer loop code
3 for (initialization; condition; increment/decrement) {
4 // inner loop code
5 }
6}

Example

Let's print a 3x3 matrix using nested loops.

nested_loops.cpp
1#include <iostream>
2using namespace std;
3
4int main() {
5 for (int i = 1; i <= 3; i++) {
6 for (int j = 1; j <= 3; j++) {
7 cout << "Row: " << i << ", Column: " << j << endl;
8 }
9 }
10 return 0;
11}
Output
Row: 1, Column: 1
Row: 1, Column: 2
Row: 1, Column: 3
Row: 2, Column: 1
Row: 2, Column: 2
Row: 2, Column: 3
Row: 3, Column: 1
Row: 3, Column: 2
Row: 3, Column: 3

Tips

  • Be cautious with nested loops as they can significantly increase execution time for large data sets.
  • Use meaningful variable names to improve code readability.

Infinite Loops

An infinite loop is a loop that continues indefinitely until an explicit exit condition is met. They are useful in scenarios where the program needs to run continuously, such as server applications.

Syntax

C++
1while (true) {
2 // code to be executed
3}

or

C++
1for (;;) {
2 // code to be executed
3}

Example

Let's create a simple infinite loop that prints "Hello" every second.

infinite_loop.cpp
1#include <iostream>
2#include <thread> // for std::this_thread::sleep_for
3using namespace std;
4
5int main() {
6 while (true) {
7 cout << "Hello" << endl;
8 this_thread::sleep_for(chrono::seconds(1)); // pause for 1 second
9 }
10 return 0;
11}

Tips

  • Use break or return statements to exit infinite loops when a specific condition is met.
  • Be cautious with infinite loops as they can cause the program to hang if not properly managed.

Practical Example

Let's create a simple program that calculates and displays the factorial of numbers from 1 to 5 using nested loops.

factorial.cpp
1#include <iostream>
2using namespace std;
3
4int main() {
5 for (int num = 1; num <= 5; num++) {
6 int factorial = 1;
7 for (int i = 1; i <= num; i++) {
8 factorial *= i;
9 }
10 cout << "Factorial of " << num << " is " << factorial << endl;
11 }
12 return 0;
13}
Output
Factorial of 1 is 1
Factorial of 2 is 2
Factorial of 3 is 6
Factorial of 4 is 24
Factorial of 5 is 120

Summary

Loop TypeDescription
For LoopRepeats a block of code for a fixed number of times.
Range-based ForSimplifies iteration over iterable data structures like arrays and vectors.
While LoopExecutes as long as a condition is true.
Do-While LoopEnsures the loop body executes at least once before checking the condition.
Nested LoopsAllows iterating over multi-dimensional data structures.
Infinite LoopsContinues indefinitely until an explicit exit condition is met.

What's Next?

In the next tutorial, we will explore Jump Statements: break, continue, and goto. These statements provide more control over loop execution, allowing you to skip iterations or terminate loops prematurely.

Stay tuned for more advanced topics in C++ programming!


Previousswitch..case StatementNext Jump Statements: break, continue, goto

Recommended Gear

switch..case StatementJump Statements: break, continue, goto