SEARCH THIS BLOG

for loop IN C/C++

What is for loop in C/C++?

The for loop in C/C++ is a flow of control construct which allows the programmer to repeat a set of statements any desired number of times. Such programming constructs are really useful as instead of writing the same statement n number of times we can simply write it once and repeat it n times.

Suppose you have to print all numbers from 1 to n, where n is to be entered by the user. This n can be in thousands and even lacs. It would be impossible for a person to write thousand cout statements. In such cases he can simply write one cout statement and ask the compiler to repeat it n number of times. The for loop is one of the tools of telling the compiler to repeat the statement.

Let us learn in details about for loop in C/C++ :


General Syntax :

for(initialization ; condition; update)

{

    // set of statements to be repeated

}

The above code is the general syntax and it can be replaced by anyone of the following syntax :

Type 1.

initialization;

for ( ; condition ; update)

 {

     //statements to be repeated

 }

Type 2

for (initialization ; condition ;)

  {

      //statements to be repeated

        update;

  }

Type 3. 

for (initialization; ;)

  {

     if(condition)

      {

        //statements to be repeated

           update;

       }

      else

            break;  

   }

There can be more syntax depending on how you want to use it. The thing to keep in mind is the general working of the loop. If your syntax works in accordance to the general rule of a loop, it will work just fine. Let us read about the working of for loop.


How does for loop work?

As we have seen in the syntax, there are four segments associated with any loop. They are initialization, condition, update statement and the body of the loop. Let us learn about them :

Initialization : It is the first step in for loop. This step initializes the loop variable with an initial value. A loop variable is the variable on which the condition is checked before executing the body of the loop.

Condition : After initialization, the condition is checked. Condition gives Boolean results, i.e. either true or false. If the condition is true, the control passes into the body of the loop and executes all the statements. If false, the control leaves the loop and comes out of it.

Body of the loop : It is the set of statements that is executed if the condition evaluates to true. It is basically the statement we wish to repeat.

Update : After the body of the loop is executed, the control moves to the update statement. An update statement changes the value of the loop variable.

After update, the control again moves to condition and checks if it is still true. If yes, then the body is again executed. Otherwise, the control moves out of the loop.

The following flowchart helps you understand clearly the flow of control in a for loop :

for loop in C/C++

 

Let us visualize the flowchart with a demo code.

//The loop part to print all

//numbers from 1 to 99

for(int i = 1; i < 100; i++)

cout<< i;


The equivalent flowchart :

for loop in C/C++
 


What is nested for loop?

The body of the for loop can contain any number of statements. These statements may also contain other for statements. When one or more for statements are used in the body of another for statement, it is called nested for loop. Many programs need nested for loops in order to fulfil our task. Some most famous programs that use nested for loop are programs including 2 Dimensional arrays, array sorting or printing some patterns, etc.

The basic working logic of nested loops is not tough. It is very easy to understand and it will be a very helpful exercise if you try to understand the logic yourself. You can look at many programs on this site which use nested loops.

 

A demo program with detailed dry run

//sum of odd numbers from 1 to n

#include<iostream>

using namespace std;

int main()

{

   int n;

   cin>>n;

   int sum=0;

   for(int i=1; i<=n; i+=2)

   {

       sum=sum+i;

   }

   cout<< “Sum is ”<<sum;

   return 0;

}

Input : 10

Output : Sum is 25

Let us see how control flows in this program :

1. The program declares an integer variable n and then takes input from  the user.

2. Another variable named sum is created and initialized with 0 (zero). This variable stores the sum of numbers.

3. As the program is to find sum of odd numbers from 1 to n, we initialize the loop variable (i) with 1.

4. The condition is next checked, and if found true the control enters the body of the loop.

5. Inside the loop, the value of i is added to sum and the result is stored again into sum.

6. Then the control moves to update statement where value of  i is increased by 2 so that value of i becomes the next odd number.

7. Control again checks the condition and if found true, all steps from step 5 are again repeated.

8. If condition is false, the control moves out of the loop and prints the sum.

 


If you want to add any information or find something incorrect in this article, comment down or contact us through the mail : coding.nkcoder@gmail.com

Which topics you want an article on? Comment down on this post.

Do not stop here. Read all articles related to C++ here.

If you want to contribute any article for the website, feel free to share it on coding.nkcoder@gmail.com. We will publish it on the website with your name.

Download the pdf form of this article here.


Post a Comment