C++ for Loop

C++ for Loop

Loops are important in C++ programming for doing repetitive tasks, and the for-loop is one of the loops that helps to iterate for number of times to execute a block of code. The for loop is the most widely used control structure to iterate through arrays, generate patterns, and count. In this article, we will discuss what is C++ for loop with, its syntax, working, flowchart, examples, advantages and disadvantages, and other special types of for loops in C++.

Table of Contents:

What is a for loop in C++?

A for loop in C++ is a control flow statement that is used to execute a block of code for a particular number of iterations repeatedly. It is used when the number of iterations is already known or can be known before starting the loop. It is generally used over the while and do-while loops.

Example:

Cpp

Output:

What is a for loop in C++ Example

The code shows how the initialization(int i =0) sets the loop variable i to 0, the condition (i<5) continues the loop as long as i is less than 5, and the iteration (i++) increments i by 1 after each iteration, and then the output is printed to the console.

Syntax of for Loop in C++

Syntax of for Loop in C++

The general syntax of a for loop in C++ is:

for (initialization; condition; iteration) {
// Code block to execute
}
  • Initialization: It is executed only once at the beginning of the loop, and it declares and initializes the loop control variable.
  • Condition: It is evaluated before each iteration. If it evaluates to true, the loop body is executed, otherwise, if false, the loop terminates.
  • Iteration: It is executed after each iteration of the loop body and updates the loop variable.

How the for Loop Works in C++

Here is a step-by-step description of the working of the for-loop in C++:

Step 1: Initialization

  • This step is executed once before the loop starts.
  • It sets up a loop control variable.

Step 2: Check the Condition 

  • Before each iteration, check the condition.
  • If the condition is true, then the loop body will be executed.
  • If the condition is false, then the loop will terminate.

Step 3: Loop Body Execution

  • If the condition is true, then the code block inside the loop will run.

Step 4: Iteration

  • After the loop body runs, the iteration will be executed.
  • It typically increments or decrements the loop control variable.

Step 5: Repeat from Step 2

  • Check the condition again, then execute the loop body and continue.

Flowchart of the for Loop

Flowchart of the for Loop

Examples of for Loop in C++

Below are a few examples of a for-loop in C++:

Example 1: Printing Numbers from N to 1

Cpp

Output:

Example 1 Printing Numbers from N to 1

The code shows how the numbers from 10 to 1 are printed using a for loop by decrementing the variable i on each iteration.

Example 2: Looping through an Array

Cpp

Output:

Example 2 Looping through an Array

The code shows how an array of integers is iterated using a for loop, the size of the array is calculated using sizeof(arr)/sizeof(arr[0]), and then each element is printed with its index as a result.

Example 3: Summing Numbers from 1 to 100

Cpp

Output:

Example 3 Summing Numbers from 1 to 100

The code shows how the sum of numbers from 1 to 100 is calculated using a for loop, and then the sum is printed with the accumulated total as the loop iterates.

Example 4: Using a for Loop with break

Cpp

Output:

Example 4 Using a for Loop with break

The code shows how a for loop is used to print numbers from 0 to 4, which stops when i is equal to 5 due to the break statement.

Example 5: Range-based for Loop (C++11)

Cpp

Output:

Example 5 Range-based for Loop

The code shows how a range-based for loop is used to iterate over a vector of fruits, and then each fruit name, “Apple, Banana, Cherry”, is printed to the console as a result.

Example 6: Print a Square Pattern Using Nested Loops

Cpp

Output:

Example 6 Print a Square Pattern Using Nested Loops

The code shows how the nested for loop is used to print a square pattern. The outer for loop is executed for each row, the inner for loop is executed for each column in a row, and then prints the square pattern using *.

Using Multiple Loop Variables in a for Loop in C++

A for loop in C++ also allows multiple loop variables to be declared and updated in a single loop header. It is used when there is a need to track or manipulate more than one value simultaneously during iteration in the loop.

Syntax:

for (initialization1, initialization2; condition; update1, update2) {
// Loop body
}

Example:

Cpp

Output:

Using Multiple Loop Variables in a for Loop in C++

The code shows how a for loop is used with two loop variables, i and j, where i starts at 0 and increments, and j starts at 10 and decrements. Also, the loop runs as long as i <= 5 and j  >= 5, and then the values of i and j are printed on each iteration.

Infinite for Loop in C++

A for loop can also become infinite when the condition given is always evaluated to true or when the condition is left empty intentionally.

Example:

Cpp

Output:

Infinite for Loop in C++

The code shows how an infinite loop using an empty for loop, which runs continuously and then prints “This is an infinite loop!” infinite times.

Get 100% Hike!

Master Most in Demand Skills Now!

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

A range-based for loop is used to make the iteration easier over arrays, vectors, and other containers by accessing each element automatically without using indices.

Syntax:

for (datatype element: container) {
// use element
}

Example:

Cpp

Output:

Range-Based for Loop

The code shows how a range-based for loop is used to iterate over a vector of integers, nums, and print each element by accessing them easily without using indices.

for_each Loop in C++

The for_each loop in C++ is a standard library algorithm that is used to apply a given function to each element in a range. It is a part of the <algorithm> header in C++.

Syntax:

for_each(start_iterator, end_iterator, function);

Example:

Cpp

Output:

for_each Loop in C++

The code shows how a for_each loop is used to iterate from nums.begin() to nums.end() by calling the function printElement for each element, and then the output is printed to the console.

Advantages of for Loop in C++

  • The components of a for loop in one line, which makes the code precise, simple, and easy to read.
  • It gives full control over the loop variables, which makes it ideal for counted loops.
  • A for loop can be used with arrays, vectors, and custom loop conditions.
  • By using a for loop, more than one loop variable in the header can be declared and updated.
  • It is easier to find and logic errors in a for loop.

Disadvantages of for Loop in C++

  • It is not suitable for too complex logic, as the loop logic becomes too complex and harder to read.
  • An incorrect condition or update can lead to an infinite for-loop.
  • This loop is suitable for the iteration whose number is not known in advance.
  • A for loop can contain more words when it iterates over containers compared to the range-based for loops.

Conclusion

The for loop in C++ is one of the most important and commonly used control flow statements. It is used when the number of iterations is already known. Also, there are some special types of for loops that are used in programming. It has some advantages and disadvantages. So, by understanding how a for loop works, its uses, advantages, and disadvantages, you can use the for loop in C++ programming effectively and efficiently.

C++ for Loop – FAQs

Q1. What is a for loop in C++?

A for loop is a control structure that is used to repeat a block of code for a fixed number of times.

Q2. When should I use a for loop?

You should use a for loop when the number of iterations is already known.

Q3. Can I use multiple variables in a for loop?

Yes, you can use multiple variables in a for loop using commas in the initialization and update sections.

Q4. What is a range-based for loop?

A range-based for loop is a simplified loop to directly iterate over arrays or containers.

Q5. Can a for loop run infinitely?

Yes, a for loop can run infinitely if the condition is always true.

About the Author

Technical Research Analyst - Full Stack Development

Kislay is a Technical Research Analyst and Full Stack Developer with expertise in crafting Mobile applications from inception to deployment. Proficient in Android development, IOS development, HTML, CSS, JavaScript, React, Angular, MySQL, and MongoDB, he’s committed to enhancing user experiences through intuitive websites and advanced mobile applications.

Full Stack Developer Course Banner