C Tutorial – for loop, while loop, break and continue

In every programming language, thus also in the C programming language, 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 printf function, but it is easier to use a loop. The only thing you have to do is to setup a loop that execute the same printf function 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; continue or end condition; increase value)
     		statement;

Look at the example below:


	#include<stdio.h>

	int main()
	{
     		int i;
     		for (i = 0; i < 10; i++)
     		{
          		printf ("Hello\n");
         		printf ("World\n");
     		}
     	return 0;
	}

Note: A single instruction can be placed behind the “for loop” without the curly brackets.
Note: For those who don’t know printf or need to know more about printf format specifiers, then first a look at our printf C language tutorial.

Let’s 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 (prefix incrementing) the one is added before the “for loop” tests if i < 10. With i++ (postfix incrementing) the one is added after the test i < 10. In case of a for loop this make no difference, but in while loop test it makes a difference. But before we look at a postfix and prefix increment while loop example, we first look at the while loop.

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<stdio.h>

	int main()

	{
    		int counter, howmuch;

    		scanf("%d", &howmuch);
    		counter = 0;
    		while ( counter < howmuch)
    		{
          		counter++;
          		printf("%d\n", counter);
    		}
    		return 0;
	}

Let’s 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.

As said before (after the for loop example) it makes a difference if prefix incrementing (++i) or postfix incrementing (i++) is used with while loop. Take a look at the following postfix and prefix increment while loop example:


	#include<stdio.h>

	int main(void) {
		int i;
	
		i = 0;
		while(i++ < 5) {
			printf("%d\n", i);
		}
		printf("\n");
		i = 0;
		while(++i < 5) {
			printf("%d\n", i);
		}
		return 0;
	}

The output of the postfix and prefix increment example will look like this:


	1
	2
	3
	4
	5

	1
	2
	3
	4

i++ will increment the value of i, but is using the pre-incremented value to test against < 5. That’s why we get 5 numbers.
++i will increment the value of i, but is using the incremented value to test against < 5. That’s why we get 4 numbers.

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<stdio.h>

	int main()
	{
     		int counter, howmuch;
     		scanf("%d", &howmuch);
     		counter = 0;
     		do
     		{
          		counter++;
          		printf("%d\n", counter);
     		}
     		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<stdio.h>

	int main()
	{
     		int i;

		i = 0;
		while ( i < 20 )
     		{
          		i++;
          		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).

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<stdio.h>

	int main()
	{
		int i;

		i = 0;
     		while ( i < 20 )
     		{
          		i++;
          		continue;
          		printf("Nothing to see\n");
     		}
     		return 0;
	}

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

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

Update: You can also take a look at one of the following example(s) that also use for loops and while loops:

This entry was posted in C Tutorials. You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed. Tweet This! Tweet This! or use to share this post with others.

There are currently 94 responses to “C Tutorial – for loop, while loop, break and continue”

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

  1. admin on November 10th, 2012:

    @jack goh: I’m not exactly sure what you are asking, but I assume something like this piece of code –

    #include<stdio.h>

    #define TRUE 1
    #define FALSE 0

    int main() {
    int year;

    printf(“Please enter a year (example: 1999) : “);
    scanf(“%d”, &year);

    if(year% 4 == FALSE && year%100 != FALSE || year%400 == FALSE) {
    printf(“%d is a Leapyear. \n”, year);
    } else {
    printf(“%d is NOT a Leapyear. \n”, year);
    }
    return 0;
    }

    Also see the tutorial: How to make a calendar in C language for additional information.

    I hope that this helps!

  2. FMMK on November 16th, 2012:

    (#include )

    int main ()
    {

    float Kilogram;

    scanf(“%f”, &Kilogram);

    stdin;

    float Pounds = Kilogram * 2.20046;

    printf(“%f Kilograms = %f Pounds.\n”, Kilogram, Pounds);

    float POUNDS;

    scanf(“%f”, &POUNDS);

    stdin;

    float KILOGRAMS = POUNDS / 2.20046;

    printf(“%f POUNDS = %f KILOGRAMS”, POUNDS, KILOGRAMS);

    return 0;

    }

  3. ranjan on November 20th, 2012:

    Write a program to calculate the sum of all the numbers less than a given number n.
    ex: output
    Enter number : 3
    6
    Enter number : 5
    15

  4. varshu on November 22nd, 2012:

    really its so amazing for learn….

  5. anirban on December 20th, 2012:

    it was really helpfull :)

  6. sivi on December 26th, 2012:

    nice

  7. rohan on December 31st, 2012:

    hey ..could any body write a function to solve simultaneous equations ..
    in have great difficulties with this

  8. Carlo on January 27th, 2013:

    Hello sir

    Can you please help me to output the sum of numbers from 1 to 15 (inclusive) and sum of odd numbers from 15-45 (inclusive) ?

  9. vinshade21 on January 30th, 2013:

    @Rakshith kumar:

    #include
    int main()
    {
    int i=1,j=10;
    while(j>1)
    {

    if(i<11)
    {
    printf("%d ",i);
    ++i;
    }
    else
    {
    –j;
    printf("%d ",j);
    }
    }
    }

  10. mujeeb on January 30th, 2013:

    good job sir

  11. Mohamed F. on February 24th, 2013:

    While testing on continue; i discovered it could be used to skip a certain number too, like when using this:
    i = 0;
    while ( i++ < 20 )
    {
    if ( i == 16 ) continue;
    printf("number %d\n", i );
    }
    it will skip the number 16 but will print every number in the range 1 to 20

  12. prince pandey on March 7th, 2013:

    sir this is very nice tutorial by you

  13. kundan on March 16th, 2013:

    thankyou

  14. M.Salman on March 17th, 2013:

    void main(void)
    {
    for(a=2;a<=400;a+2)
    {
    printf("%d",a);
    }

    i m not getting the series of even num help me???? output showing only 400 nd its blinking !! :S

  15. werke ayalew on March 22nd, 2013:

    #include
    void main(void)
    {
    int a;
    for(a=2;a<=400;a+2)
    {
    printf("%d",a);
    }
    }

  16. werke ayalew on March 22nd, 2013:

    your simple error is only on the declaration of ‘a’ that must be an integer.otherwise the compiler doesn’t know what variable ‘a’ is.

  17. ush on March 31st, 2013:

    it was good n easy..
    plzz tell the purpose of getch and also explain nested loops if possible..
    thankyou

  18. hemanth on April 12th, 2013:

    nice gather

  19. manoj on April 24th, 2013:

    #include
    using namespace std;
    int main()
    {
    int n,factorial=1;
    cout<>n;
    for(int i=n;i>0;i–){
    factorial=i*factorial;
    }
    cout<<factorial<<endl;
    return (0);
    }

  20. obazee ruth on June 12th, 2013:

    can all for loops be rewritten using a while loop?

  21. Eustacia on July 1st, 2013:

    Thanks so much for your tutorials! I’m doing a basic course in C Code, but it’s taught in Japanese so these are really saving my grade!

    I have a question: I’m supposed to build a program where I enter an integer below a hundred, and all numbers smaller than said integer and containing the number “3” appear on the screen (etc, if I enter 14, the numbers “3, 13” should appear).

    However, there’s something wrong with my code, please help! Thank you!

    The code:

    #include

    int main(int argc, const char * argv [])
    {
    int wholenumber;
    printf(“百以内の整数を入力してください\n”);
    scanf_s(“%d”, &wholenumber);

    while(0 <wholenumber)
    {
    wholenumber–;

    while(0 < wholenumber){
    wholenumber = 3 %10;
    wholenumber = 3 /10;

    if (wholenumber == 3);
    {printf("%3d",wholenumber);}
    }
    }
    return 0;
    }

  22. bhawana on July 14th, 2013:

    piz clear these concept also…
    while(n!=0)
    {
    n/=10
    ++count
    }

  23. akj on July 20th, 2013:

    #include
    int main()
    {
    int i;
    for (i=400;i>=1;i–)
    {
    printf(“%d\n”,i);
    }
    return 0;
    }

    y can’t i see 400, the output is starting from 298 and continues till printing 1

  24. Carl on August 7th, 2013:

    Thx for this! I understand loops clearly

  25. Mahesh on September 5th, 2013:

    Program for 12345678910987654321

    #include
    main()
    {
    int i,j;
    for(i=1,j=9;i=1;i++){
    if(i<=10)
    printf("%d",i);
    else{
    printf("%d",j);
    j–;
    }
    }
    getch();
    }

  26. mike swabe on September 17th, 2013:

    how to make 5 * diomond?

  27. Stephen on September 23rd, 2013:

    Excuse me!
    How shall I program two integers then display the factors of the integers and then get their greatest common factors(GCF)…
    May I ask anyone to help me?

  28. Bhagyashree on September 23rd, 2013:

    Thank you so much! I had been looking so long for a proper C tutorial for beginners. Your explanations and examples make it so much easier to understand.

  29. avanish singh on October 13th, 2013:

    hi, sir i want a loop statement then are perform a working
    that are i know you loop dry run

  30. kuldeep on October 16th, 2013:

    can we possibly write this way.

    for(scanf(“%d”, &i)); i<10; i++)
    printf("%d",i);

  31. kuldeep on October 16th, 2013:

    and also this way
    for(i = 1; i<10; printf("%d",i++))

  32. kuldeep on October 16th, 2013:

    or if i’ll use

    for(i=0;i++<10;)
    printf("%d\n",i);

    what will first done in for statement (i++<10) incrementation or comparison

  33. THULASI THAMBI on October 16th, 2013:

    IT WAS HELPFULL & EASIER TO UNDERSTAND….

  34. jakir on November 28th, 2013:

    #include
    int main()
    {
    int num=3,i,a;

    a=0;

    for(i=1;i<=num;i++) {
    a=a+2;
    printf("%d ",a);
    }
    printf("\n");

    for(i=1;i<=num;i++) {
    a=a+4;
    printf("%d ",a);
    }
    printf("\n");

    for(i=1;i<=num;i++) {
    a=a+6;
    printf("%d ",a);
    }
    return 0;
    }

  35. jakir on November 28th, 2013:

    /*the ans of M.Salman question*/
    /*the series of even no.*/

    #include
    int main()

    {
    int num;
    int n;
    //printf(“enter ur number: “);
    //scanf(“%d”,&num);
    for(n=0;n<=100;n++){
    if(n%2==0){
    printf("%d ",n);
    }
    printf("\n");
    }
    return 0;
    }

  36. jhonmark on December 15th, 2013:

    thanks for the codes i will study this codes

  37. J.Aravind Amuthuraj on December 15th, 2013:

    Any one tell me i cant understand the difference between ++i and i++.Please explain in the way of easy understanding.

  38. abhijeet on December 30th, 2013:

    @ Mr. J.Aravind Amuthuraj

    i++ and ++i both are similar…
    but it depends upon the situation… when you are using them,

    lets take an example,

    #include

    int main()
    {

    int x = 10,y;
    int v = 10,z;

    y = ++x + x++;
    z = ++v + ++v;

    printf(“x = %d y = %d”,x,y);
    printf(“\n\nv = %d z = %d”,v,z);

    return 0;
    }

    OUTPUT – x = 12 y = 22

    v = 12 z = 23

    // here as you can see, the values of y and z are changed

    because of the difference of position of ‘++’ increment operator…

    if ++ operator is after the variable then it is executed later… and if ++ operator is before the operator then it is executed first..
    so the value of x is first incremented to 11 and as x = 11 therefore the x++ will result as 11…
    and addition of 2 eleven is 22 so y = 22,

    but in z the value of v is ++v = 11 and then as v = 11 so again ++v = 12
    therefore addition of ++v + ++v will be 23
    hence z will result in 23.

    i hope you understand the difference between ++x and x++. :)

  39. Nik on February 1st, 2014:

    A B C D E D C B A
    A B C D D C B A
    A B C C B A
    A B B A
    A A
    code for this one
    #include
    int main( )
    {
    int i,j,k=65,l;
    for(i=5;i>0;i–)
    {
    for(l=5;l>i;l–)
    {
    printf(” “);
    }
    for(j=0;j<i;j++)
    {
    printf("%c",k+j);
    }
    for(j=0;j<i;j++)
    {
    printf("%c",k-j+i-1);
    }
    printf("\n");
    }
    getchar();
    return 0;

    }

  40. jasveer on February 15th, 2014:

    dear Rakshith kumar:
    i have the answer to your problem:

    #include
    #include
    void main()
    {
    for(int i=1;i<=10;i++)
    {
    cout<=1;i–)
    {
    cout<<i;
    }
    getch();
    }

  41. vaio on March 8th, 2014:

    are,
    for(i=1;i<=5;i++)
    and for(i=1;i++,<= operators because i tend to make mistakes when = are inserted in loops.
    also,for(int i=0;i<10;i++) prints from 0 whereas for(i=1;i++<=5;) prints from 2 to 6.
    i mean if i is initialized from 1 it should start from 1.

  42. chala on April 7th, 2014:

    Really helpful sir

  43. siddharth on April 27th, 2014:

    can we use the while loop for true or false function?

  44. Lydia on May 25th, 2014:

    I just found this site, and well organized and useful, thank you!!!