Copyright © tutorialspoint.com

# while loop examples

Try following example to understand while loop. You can put the following code into a test.c file and then compile it and then run it.

    #include <stdio.h>

    main()
    {
        int i = 10;

        while ( i > 0 )
        {
           printf("Hello %d\n", i );
           i = i -1;
        }
    }

This will produce following output:

    Hello 10
    Hello 9
    Hello 8
    Hello 7
    Hello 6
    Hello 5
    Hello 4
    Hello 3
    Hello 2
    Hello 1

You can make use of break to come out of while loop at any time.

    #include <stdio.h>

    main()
    {
        int i = 10;

        while ( i > 0 )
        {
           printf("Hello %d\n", i );
           i = i -1;
           if( i == 6 )
           {
              break;
           }
        }
    }

This will produce following output:

    Hello 10
    Hello 9
    Hello 8
    Hello 7

Copyright © tutorialspoint.com