Loop
For
- #include <stdio.h>
-
- int main()
- {
- for(int i = 0; i < 10; i++)
- {//start block
- printf("Hello World!\n");
- }//end block
-
- // the braces can be ignored if there is only one line of code
- for(int i = 0; i < 10; i++)
- printf("Hello World!\n");
-
- return 0;
- }
-
break, provides an early exit from for, while, and do ... while, and switch
- #include <stdio.h>
-
- int main()
- {
- for(int i = 0; i < 10; i++)
- {
- if(i == 6) break;
- printf("%d\n", i);
- }
-
- return 0;
- }
-
continue, skip the rest statements of the current iteration, applies only to loops, not to switch
- #include <stdio.h>
-
- int main()
- {
- for(int i = 0; i < 10; i++)
- {
- if(i == 6) continue;
- printf("%d\n", i);
- }
-
- return 0;
- }
-
Nested For Loop
- #include <stdio.h>
-
- int main()
- {
- for(int i = 1; i < 10; i++)
- {
- for(int j = 1; j < 10; j++)
- printf("%3d * %3d = %4d", i, j, i*j);
-
- printf("\n");
- }
-
- return 0;
- }
-
While
- #include <stdio.h>
-
- int main()
- {
- int i = 10;
-
- while (i > 0)
- {
- printf("%d\n", i);
- i--;
- }
-
- return 0;
- }
-
Do ... While
- #include <stdio.h>
-
- int main()
- {
- int i = 10;
-
- do
- {
- printf("%d\n", i);
- i--;
- }while ( i > 0 );
-
- return 0;
- }
-