C++ for loops, while loops

In this C++ programming tutorial we will look at loops.

There are circumstances were you want to do the same thing many times. For instance you want to
print the same words ten times. You could type ten cout statements, but it is easier to use a loop, such as a “for loop” or a “while loop.” The only thing you have to do is to setup a loop that execute the same cout statement ten times.

There are three basic types of loops which are:

  • “for loop”
  • “while loop”
  • “do while loop”

The for loop

The “for loop” loops from one number to another number and increases by a specified value each time.
The “for loop” uses the following structure:


      for (Start value; end condition; increase value)
     		statement(s);

Look at the example below:


	#include<iostream>
	using namespace std;

	int main()
	{
		int i;

		for (i = 0; i < 10; i++)
		{
			cout << "Hello" << "\n";
			cout << "There" << "\n";
		}
		return 0;
	}

Note: A
single instruction can be placed behind the “for loop” without the curly brackets.

Lets look at the “for loop” from the example: We first start by setting the variable i to 0. This is  where we start to count. Then we say that the for loop must run if the counter i is smaller then ten. Last we say that every cycle i must be increased by one (i++).

In the example we used i++ which is the same as using i = i + 1. This is called incrementing. The instruction i++ adds 1 to i. If you want to subtract 1 from i you can use i–. It is also possible to use ++i or -i. The difference is is that with ++i the one is added before the “for loop” tests if i < 10. With i++ the one is added after the test i < 10.

The while loop

The while loop can be used if you don’t know how many times a loop must run.
Here is an example:


	#include<iostream>
	using namespace std;

	int main()
	{
		int counter, howmuch;

		cin >> howmuch;

		counter = 0;
		while ( counter < howmuch)
		{
			counter++;
			cout << counter << '\n';
		}
		return 0;
	}

Lets take a look at the example: First you must always initialize the counter before the while loop starts ( counter = 1). Then the while loop will run if the variable counter is smaller then the variable “howmuch”. If the input is ten, then 1 through 10 will be printed on the screen. A last thing you have to remember is to increment the counter inside the loop (counter++). If you forget this the loop becomes infinitive.

The do while loop

The “do while loop” is almost the same as the while loop. The “do while loop” has the following form:


	do
	{
    		do something;
	}
	while (expression);

Do something first and then test if we have to continue. The result is that the loop always runs once. (Because the expression test comes afterward). Take a look at an example:


	#include <iostream>
	using namespace std;

	int main()
	{
		int counter, howmuch;

		cin >> howmuch;
		counter = 0;
		do
		{
			counter++;
			cout << counter << '\n';
		}
		while ( counter < howmuch);
		return 0;
	}

Note: There is a semi-colon behind the while line.

Break and continue

To exit a loop you can use the break statement at any time. This can be very useful if you want to stop running a loop because a condition has been met other than the loop end condition. Take a look at the following example:


	#include <iostream>
	using namespace std;

	int main()
	{
		int i;

		i = 0;
		while ( i < 20 )
		{
			i++;
			cout << "Hello\n";
			if ( i == 10)
				break;
		}
		return 0;
	}

In the example above, the while loop will run, as long i is smaller then twenty. In the while loop there is an if statement that states that if i equals ten the while loop must stop (break). The result is that only ten Hello will be printed.

With “continue;” it is possible to skip the rest of the commands in the current loop and start from the top again. (the loop variable must still be incremented). Take a look at the example below:


	#include <iostream>
	using namespace std;

	int main()
	{
		int i;

		i = 0;
		while ( i < 20 )
		{
			i++;
			continue;
			cout << "Hello\n";
			if ( i == 10)
				break;
		}
		return 0;
	}

In the example above, the cout function is never called because of the “continue;”.

The exit function

The exit function is defined in the cstdlib library.

The purpose of exit is to terminate the current program with a specific exit code. Its prototype is:


     void exit (int exitcode);

The exitcode is used by some operating systems (UNIX / Linux) and may be used by calling programs. An exit code of 0 means that the program finished normally and any other value means that some error occurred.

That was all for now. Don’t forget to make some example programs of your own, just for practice.

This entry was posted in C++ Tutorials. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site. Tweet This! Tweet This! or use to share this post with others.

There are currently 29 responses to “C++ for loops, while loops”

Why not let us know what you think by adding your own comment!

  1. ankit arpan on December 14th, 2011:

    it has helped me a lot in understanding do,while,for and do-while loop….

  2. anneka on January 10th, 2012:

    i love it !!!!! so good !!!!!
    i like it!!!!

  3. kamagara on March 13th, 2012:

    too perfect

  4. twitter log in on March 27th, 2012:

    I have to say that for the last few of hours i have been hooked by the impressive articles on this website. Keep up the wonderful work.

  5. aziz ali on June 28th, 2012:

    very nice site

  6. Togonon on August 27th, 2012:

    Thanks!!! :D

  7. mafi@bd on September 13th, 2012:

    just i want to say that its really swowsome.

  8. mafi@bd on September 13th, 2012:

    just i want to say that its really wowsome.

  9. pravina on November 9th, 2012:

    #include
    #include
    void main()
    {int i;
    for(i=1;i<5;i++)
    {
    if(i==3) continue;
    cout<<i;
    }
    getch();
    }
    how many times is this loop executed?

  10. Rahe khan on November 11th, 2012:

    i just wana say this is very easy nd awsome thanks

  11. Satvir Singh on December 13th, 2012:

    I really appreciate the effort done by coding unit prog. tutorials… This site has compiled the information about c++ in a very nice ordered way..
    Thank You

  12. Ranajeet on February 3rd, 2013:

    Good for beginners. Thanks a lot

  13. Lauren on February 12th, 2013:

    This is waaaay more helpful than my textbook. I would love it if there were some examples that included showing the output–I find that I kinda sorta understand the general structure of the loops, but when given the variables and told to put what the output will be, I get it wrong A LOT, especially for for loops. Which is very frustrating.

  14. maxwell ocholla on March 20th, 2013:

    very well stipulated!!i love it!

  15. go man on March 28th, 2013:

    GOOD!!!! keep it up… :D

  16. Rhonah Rhitt on April 3rd, 2013:

    ya! l enjoyed the coding of this prog, as l know the diffrences of these loops. thx

  17. silpamohan on April 14th, 2013:

    thanks for giving..foor loop codes..i think this is good way to help programming beginners..

  18. Jentala on May 3rd, 2013:

    The article states incorrectly: “The difference is is that with ++i the one is added before the “for loop” tests if i < 10. With i++ the one is added after the test i < 10."

    This is misleading and incorrect. There is no difference in loop evaluation or execution with ++i and i++ in the for statement because i is incremented in a separate statement from the loop evaluation. (Notice that it's separated by a semicolon.) Modern compilers will even compile the two loops identically so it's merely a style choice.

    There are a few situations where it matters whether a pre-increment or post-increment is used but a for loop is NOT one of them.

  19. JacobChristian on June 9th, 2013:

    its really clear to understand,unlike other websites……

  20. JB on September 4th, 2013:

    haha.. thanks for this !! i have an assignment :)

  21. Dinesh on September 14th, 2013:

    can i use while loop inside for loop

  22. annie milana pm on September 29th, 2013:

    thanxxxxxxxx…………………

  23. Ram on October 8th, 2013:

    thanksssssss…it’s really fab…

  24. varun on October 25th, 2013:

    thanks dude

  25. gladson on November 28th, 2013:

    thanks

  26. Zamn Muhammad on January 12th, 2014:

    “Thanks…!

  27. Ahmed Khaled on February 2nd, 2014:

    Very simple and well organized …. Thank you very much

  28. Afshin Raboonik on March 5th, 2014:

    Thanx a lot .
    writers of this website are truly real teachers.
    simple and well organized.

  29. Mubashar on April 12th, 2014:

    how i convert ‘a’ into ‘A’ using for loop reply me

Leave a Reply: