Understanding Loops in C++

Home

Loops are basically means to do a task multiple times, without actually coding all statements over and over again.

For example, loops can be used for displaying a string many times, for counting numbers and of course for displaying menus.

Loops in C++ are mainly of three types :-

1. 'while' loop
2. 'do while' loop
3. 'for' loop

For those who have studied C or JAVA, this isn't very new, as the syntax for the loops are exactly same. So if you know the above languages,  don't waste your time understanding loop syntax in C++.

 

The 'while' loop :-
Let me show you a small example of a program which writes ABC three(3) times.

#include<iostream.h>

void main()
{
  int i=0;
  while(i<3)
  {
    i++;
    cout<<"ABC"<<endl;
  }
}

The output of the above code will be :-
ABC
ABC
ABC

A point to notice here is that, for making it more easy to understand, we could also write,

int i=1;
while(i<=3)

This would make our code more easy for a newbie, but in actuality it doesn't make a difference either way.


The 'do while' loop :-
It is very similar to the 'while' loop shown above. The only difference being, in a 'while' loop, the condition is checked beforehand, but in a 'do while' loop, the condition is checked after one execution of the loop.

Example code for the same problem using a 'do while' loop would be :-

void main()
{
  int i=0;
  do
  {
    i++;
    cout<<"ABC"<<endl;
  }while(i<3);
}

The output would once again be same as in the above example.

 

The 'for' loop :-
This is probably the most useful and the most used loop in C/C++. The syntax is slightly more complicated than that of 'while' or the 'do while' loop.

The general syntax can be defined as :-
for(<initial value>;<condition>;<increment>)

To further explain the above code, we will take an example. Suppose we had to print the numbers 1 to 5, using a 'for' loop. The code for this
would be :-

#include<iostream.h>

void main()
{
  for(inti=1;i<=5;i++)
  cout<<i<<endl;
}

The output for this code would be :-
1
2
3
4
5

Here variable 'i' is given an initial value of 1. The condition applied is till 'i' is less than or equal to 5. And for each iteration, the value of 'i' is also incremented by 1.

Notice here that if we wanted to print,
5
4
3
2
1

we would change our 'for' loop to :-
for(inti=5;i>=1;i--)

 


This is a very brief introduction to loops in C++. Hope it helped you. A few reference books that I would suggest are :-

1. Computer Science C++ by Sumita Arora
   Volume I and II
   Dhanpat Rai Publications

2. Object Oriented Programming using C++
   By E Balagurusamy
   Tata McGraw Hill

3. Using C++ by Rob McGregor
   Prentice Hall of India

Written by Rahul Batra

Special Thanks to Ashish Kushwaha and Tanuj Kush

 

Hosted by www.Geocities.ws

1