1. Home
C++ Tutorial

Explore C++ Tutorials: Exploring the World of C++ Programming

Discover comprehensive C++ tutorials designed for beginners and advanced programmers alike. Enhance your coding skills with step-by-step guides and practical examples.

  • 77 Lessons
  • 15 Hours
right-top-arrow
12

A Comprehensive Guide to Loop in C++

Updated on 20/09/2024425 Views

A loop in C++ automates repetition in our code to save us from tedious manual tasks. 

Whether we are iterating over data, repeating actions a set number of times, or waiting for a specific condition to occur, loops are our go-to solution. By understanding for, while, and do-while loops, as well as loop control mechanisms, we can unlock the power to write efficient, adaptable, and concise C++ programs.

Let us dive in and learn about the concept of a loop in C++ and how to use the different loops effectively in C++ programming.

What is a Loop in C++?

Loop in C++ is a control structure designed to execute a block of code multiple times. They provide a streamlined approach to automating repetitive tasks, reducing the need for redundant code, and improving the efficiency and maintainability of programs.

Why Are Loops Essential?

By leveraging loops, we can avoid manually repeating code, thereby minimizing the risk of errors and enhancing the readability and clarity of our programs. Furthermore, loops offer the flexibility to adapt to dynamic conditions, making applications more responsive to user input and environmental changes.

Loops are critical for a variety of programming tasks, including:

  • Iteration: Processing elements in collections (arrays, vectors, etc.).
  • Repetition: Executing a set of instructions a fixed number of times.
  • Conditional execution: Repeating a block of code until a specific condition is met.

Types of Loop in C++

C++ offers three primary loop structures, each tailored to different scenarios:

  • for loop in C++: Ideal for situations where the number of iterations is known in advance or can be easily determined. It combines initialization, condition checking, and update steps into a compact syntax.
  • while loop in C++: Well-suited for scenarios where the loop should continue executing as long as a given condition remains true. The condition is checked before each iteration.
  • do-while loop in C++: Similar to the while loop in C++, but the condition is checked after each iteration, guaranteeing that the loop body executes at least once.

Let us now learn about the more common loops with C++ for loop, C++ while-loop, and C++ do while loop examples.

The for Loop in C++

C++ for loop syntax:

for (initialization; condition; update) {

    // Code to be repeated 

}

How for loop in C++ Works:

  • Initialization: The loop counter is set to its initial value.
  • Condition check: The condition is evaluated. If true, proceed to step 3. If false, the loop terminates.
  • Execute code block: The code within the loop in C++ body is executed.
  • Update: The loop in C++ counter is modified (e.g., incremented).
  • Repeat: Go back to step 2.

for loop in C++ example 1:

// Counting from 0 to 9

for (int i = 0; i < 10; i++) {

    std::cout << i << " ";

}

for loop in C++ example 2:

// Iterating over an array

int arr[5] = {10, 20, 30, 40, 50};

for (int i = 0; i < 5; i++) {

    std::cout << arr[i] << " ";

}

The while Loop in C++

Syntax:

while (condition) {

    // Code to be repeated

}

How cpp while loop works:

  • Condition check: The condition is evaluated. If true, proceed to step 2. If false, the loop terminates.
  • Execute code block: The code within the loop in C++ body is executed.
  • Repeat: Go back to step 1.

While loop in C++ example:

// Reading user input until a valid number is entered

int number;

std::cout << "Enter a positive number: ";

std::cin >> number;

while (number <= 0) {

    std::cout << "Invalid input. Enter a positive number: ";

    std::cin >> number;

}

The do while Loop in C++

Syntax:

do {

    // Code to be repeated

} while (condition);

How it works:

  • Execute code block: The code within the loop in C++ body is executed.
  • Condition check: The condition is evaluated. If true, proceed to step 1. If false, the loop terminates.

Cpp do while example:

int choice;

do {

    std::cout << "Menu:\n";

    std::cout << "1. Option 1\n";

    std::cout << "2. Option 2\n";

    std::cout << "0. Exit\n";

    std::cout << "Enter your choice: ";

    std::cin >> choice;

    // ... process the choice

} while (choice != 0); 

If you wish to learn how to code in C++, you can check out upGrad’s software engineering courses.

Range-based for Loop (C++11 and later)

Introduced in C++11, the range-based for loop streamlines the way you iterate over elements in containers like arrays, vectors, lists, and more. It offers a cleaner and more expressive syntax compared to traditional for loops, making our code easier to read and write.

Syntax:

for (element_declaration : range) {

    // Code to be repeated for each element

}

  • element_declaration: This declares a variable that will hold each element from the range during each iteration. The type of this variable can often be automatically deduced (auto).
  • range: This represents the collection of elements you want to iterate over (e.g., an array, a vector, or any other iterable object).

How it works:

  • The loop starts at the beginning of the range.
  • In each iteration, the element_declaration variable is assigned to the next element in the range.
  • The code block within the loop is executed, working with the current element.
  • The loop continues until all elements in the range have been processed.

Example 1:

// Iterating over an array

int numbers[] = {10, 20, 30, 40};

for (int num : numbers) {

    std::cout << num << " "; 

}

// Output: 10 20 30 40

Example 2:

// Iterating over a vector

std::vector<std::string> names = {"Alice", "Bob", "Charlie"};

for (const std::string& name : names) { // Use const reference for efficiency

    std::cout << name << " ";

}

// Output: Alice Bob Charlie

Key Advantages

Here are the key advantages of range-based for loops:

  • Conciseness: Eliminates the need for explicit index management or iterators.
  • Readability: Makes the intent of iterating over a collection much clearer.
  • Less error-prone: Reduces the risk of off-by-one errors that can occur with traditional loops.
  • Versatility: Works with a wide range of iterable objects, not just arrays and vectors.

Range-Based C++ for Loop Program Example

Here's a for each loop in C++ example program that combines both the traditional for loop and the range-based for-each loop:

Loop in C++ example

Code:

#include <iostream>

#include <vector>

int main() {

    // Traditional for loop with an array

    int numbers[] = {5, 10, 15, 20};

    int arraySize = sizeof(numbers) / sizeof(numbers[0]); // Calculate the number of elements in the array 

std::cout << "Using for loop (array): ";

    for (int i = 0; i < arraySize; ++i) {

        std::cout << numbers[i] << " ";

    }

    std::cout << std::endl;

    // Range-based for-each loop with a vector

    std::vector<std::string> fruits = {"apple", "banana", "orange"};

    std::cout << "Using for-each loop (vector): ";

    for (const std::string& fruit : fruits) { 

        std::cout << fruit << " ";

    }

    std::cout << std::endl;

    return 0;

}

Loop Control Statements

Loop control statements are essential tools that allow you to fine-tune how our loops behave. They let you alter the usual flow of execution, giving you more flexibility when handling specific conditions within our loops.

break Statement

The break statement acts like an emergency exit for our loop in C++. When encountered within a loop, it immediately terminates the loop, regardless of the loop condition.

Typical use cases:

  • Exiting early when a specific condition is met (e.g., finding a search target).
  • Breaking out of infinite loops in error situations.

Example:

for (int i = 0; i < 10; i++) {

    if (i == 5) {

        break; // Terminate the loop when i reaches 5

    }

    std::cout << i << " "; 

// Output: 0 1 2 3 4

continue Statement

The continue statement is like a "skip" button within our loop in C++. When encountered, it immediately jumps to the next iteration of the loop, bypassing any remaining code in the current iteration.

Typical use cases:

  • Skipping specific iterations based on a condition (e.g., skipping even numbers).
  • Avoiding unnecessary processing in certain situations.

Example:

for (int i = 0; i < 10; i++) {

    if (i % 2 == 0) { // Check if i is even

        continue; // Skip even numbers

    }

    std::cout << i << " "; 

}

// Output: 1 3 5 7 9 

Practical Use of Loops Individually and Together

Let us explore the practical use of loops and how to combine loops.

1. for Loop (Counting)

Example:

int number = 0;

while (number <= 0) {

    std::cout << "Enter a positive number: ";

    std::cin >> number;

}

std::cout << "You entered: " << number << std::endl;

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

    std::cout << i << " "; 

}

// Output: 1 2 3 4 5

Explanation: The for loop in C++ initializes a counter i to 1, continues as long as i is less than or equal to 5, and increments i after each iteration. This prints numbers 1 through 5.

2. while Loop (User Input)

Example:

int number = 0;

while (number <= 0) {

    std::cout << "Enter a positive number: ";

    std::cin >> number;

}

std::cout << "You entered: " << number << std::endl;

Explanation: The while loop in C++ keeps asking the user for input until they enter a positive number. The loop condition checks the input before each iteration.

Note: The C++ for while loop can work together to form a combined loop.

3. do-while Loop (Menu)

Example:

int choice;

do {

    std::cout << "\nMenu:\n";

    std::cout << "1. Option 1\n";

    std::cout << "2. Option 2\n";

    std::cout << "0. Exit\n";

    std::cout << "Enter your choice: ";

    std::cin >> choice;

    // ... handle choice ...

} while (choice != 0);

Explanation: This do-while loop in C++ presents a menu and repeatedly asks for the user's choice until they enter 0 to exit. The code block executes at least once before the condition is checked.

Combined Loop Example (Nested Loop C++)

Example:

// Printing a multiplication table

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

    std::cout << "Multiplication table for " << i << ":\n";

    for (int j = 1; j <= 10; ++j) {

        std::cout << i << " x " << j << " = " << (i * j) << std::endl;

    }

    std::cout << std::endl; // Add space after each table

}

Explanation: The outer for loop iterates through the numbers 1 to 10 (rows of the table).

The inner for loop, nested within the outer loop, also iterates from 1 to 10 (columns of the table). Finally, the multiplication and output are performed inside the inner loop.

Best Practices and Considerations for Loop in C++

Choosing the Right Loop

Selecting the appropriate loop type depends on our specific requirements:

  • for loop: Preferable when we know the exact number of iterations in advance, or when you need to tightly control the initialization, condition, and update steps of the loop.
  • while loop: Suitable when the number of iterations is unknown and depends on a condition that must be checked before each iteration.
  • do-while loop: Consider this when we need the loop body to execute at least once, even if the condition is initially false.

Avoiding Infinite Loops

Infinite loops can cause our program to hang or crash. To prevent them:

  • Careful condition design: Ensure your loop condition will eventually become false. This might involve incrementing or decrementing a counter, modifying a variable based on input, or reaching a specific state in your program.
  • Break conditions: Use the break statement strategically to exit the loop prematurely if a certain condition arises that shouldn't lead to continued iteration.

Optimizing Loop Performance

Loops can be computationally intensive, especially when dealing with large datasets or complex operations. Here are some tips for improving loop in C++ performance:

  • Minimize loop overhead: If possible, move calculations or variable assignments outside of the loop if they don't need to be repeated in each iteration.
  • Efficient container access: If we are iterating over a container like a vector or an array, avoid repeatedly calling size() within the loop condition. We can store the size in a variable beforehand.
  • Use algorithms: C++'s Standard Template Library (STL) provides powerful algorithms like std::find, std::transform, and std::sort that can often replace manual loops with more optimized implementations.
  • Consider performance profiling: If our loop is a performance bottleneck, we can use profiling tools to identify areas for improvement.

Final Tips

Mastering loops is essential for any C++ programmer. With the right loop for the job and a keen eye for optimization, you'll be able to write code that's not only functional but also elegant and efficient.

If you wish to learn programming languages such as C++, you can check out upGrad’s computer science programs such as the Master’s in Computer Science Program.

Frequently Asked Questions

  1. What are loops in C++?

Loops in C++ are programming constructs that allow you to repeatedly execute a block of code until a specific condition is met.

  1. What are the types of loops in C++?

The main types of loops in C++ are for, while, and do-while.

  1. What is the syntax for a for loop in C++?

The syntax is: for (initialization; condition; update) { // code block to be executed }

  1. What is loop structure?

loop in C++ structure refers to the way a loop is organized, including its initialization, condition, update (for for loops), and the body of code to be repeated.

  1. How do you exit a loop in C++?

You can exit a loop in C++ prematurely using the break statement or by making the loop condition false.

  1. How to write a for loop in C?

The syntax for a for loop in C is the same as in C++: for (initialization; condition; update) { /* code block to be executed */ }

Kechit Goyal

Kechit Goyal

Team Player and a Leader with a demonstrated history of working in startups. Strong engineering professional with a Bachelor of Technology (BTech…Read More

Need Guidance? We're Here to Help!
form image
+91
*
By clicking, I accept theT&Cand
Privacy Policy
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
right-top-arrowleft-top-arrow

upGrad Learner Support

Talk to our experts. We’re available 24/7.

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...