In Every Programming Language
In Every Programming Language
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
#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. 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 can be used if you dont 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; }
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.
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 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:
In the example above, the printf function is never called because of the continue;. That was all for now. Dont forget to make some example programs of your own, just for practice!