Full Version: Understanding Loops in C++
Dream.In.Code > Programming Tutorials > C++ Tutorials
rahulbatra
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.

CODE

#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,

CODE

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 :-

CODE

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 :-

CODE

#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 :-
CODE

for(inti=5;i>=1;i--)



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

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

2. Using C++ by Rob McGregor
Prentice Hall of India
Amadeus
Excellent tutorial...the only comment I have is to point out that the iostream.h header library syntax has been deprecated, and is no longer accetable in ANSI standard code. It is preferred to use namespaces instead...this changes
CODE

#include<iostream.h>

to
CODE

#include<iostream>
using namespace std;

Great work!
Mrafcho001
Very nice tutorial rahulbatra!

I really like how you use a lot of examples and explain them well.

I know many people will disagree on this, but void main() is not a good practive/habit to get into.

instad:

CODE

int main()
{
   return 0;
}
Amadeus
I would tend to agree...structuring the program to return an int upon exit ensures that it can work with other programs should the occasion require.
rahulbatra
Its completely true. I actually am in nasty habit of using 'void main()' since the first book that I read used that, and the Turbo C++ compiler I use doesn't give a warning on this.

However whenever possible use 'int main()'. Infact while talking to a kernel developer, he told me that the void is just an abstraction in this case. In all such cases, a '0' is returned. Though I can't verify the correctness of this as of now, it certainly seems possible.
shikha
hi Mr Rahul...... nice try ....... 1 thing ....... this article would hav been gr8 if with more examples.....
virendra
rolleyes.gif rahul really it is in very easy language. and 100% understandable .could u plz explain the necessity of the each loop i.e. which loop is use when and under which condition
virendra
thanks for such nice tutoria;
VIRENDRA rolleyes.gif
rahulbatra
Actually most programmers prefer one type of loop or another. It becomes a choice of personal preference actually. But most of them prefer to use the 'for loop' because of its power and flexibility, having the condition and the increment in the same construct.

'For loops' also (in my opinion) look a lot cleaner when nested. The 'do-while' becomes too cumbersome when nesting though this may not always be the case.
born2c0de
QUOTE(rahulbatra @ 30 Dec, 2005 - 03:23 AM) *

Its completely true. I actually am in nasty habit of using 'void main()' since the first book that I read used that, and the Turbo C++ compiler I use doesn't give a warning on this.

However whenever possible use 'int main()'. Infact while talking to a kernel developer, he told me that the void is just an abstraction in this case. In all such cases, a '0' is returned. Though I can't verify the correctness of this as of now, it certainly seems possible.

It is true...I think I've even mentioned that on </dic> on some posts.
If you know Assembly Language, use any debugger loaded with any program, and study the value of the AX or EAX (depending on the whether your program uses 16-bit or 32-bit code) after main() is done executing.
browngod2002
good topic. liked the examples. next time maybe cover nested loops.as a beginner that is wher I am having some problems.
Xing
QUOTE(rahulbatra @ 29 Dec, 2005 - 02:01 AM) *
A few reference books that I would suggest are :-

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

Don't know about the second book but please anyone reading this thread should not follow this book. Yes, the language is easy but the author does lot of naive mistakes. Do good to yourself by not reading this book.
Therois
good tut i forgot alot of stuff over the summer this will refresh my mind
nirvanarupali
QUOTE(Amadeus @ 29 Dec, 2005 - 01:37 PM) *

I would tend to agree...structuring the program to return an int upon exit ensures that it can work with other programs should the occasion require.



That's right. It is never used and will never use in C++ the
CODE
void main()
even your compiler compiles it.

For more information visit :

http://www.research.att.com/~bs/bs_faq2.html#void-main
Lt_Kernel
your "for" loop example gives a not so good errors

1. inti undeclared first use this function
2.each undeclared identifiers isreported only once for each functions it appears in
3. i undeclared first use this function
4. build error error 1
5.in fuction int amin ()

and you gave only numbers as an example
there is also a thing called "letters" there is also a "still images, videos and more others,

can u give examples of letters or words using for loop

icon_down.gif

ooops for got to check the date
sorry for the not so late reply
XxXnucronXxX
thank you for that mr.rahulbatra.. very brief explanation on the loops! icon_up.gif
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Invision Power Board © 2001-2008 Invision Power Services, Inc.