C While Loop with Example
The simplest of three loops in C Language is the C while loop. In common language while has fairly obvious meaning: the while-loop has a condition:
while (condition) { statements; }
If the statements are executed while the condition has the value “true” (1). The first important thing about this while loop is that has a conditional expression (something like (a > b) etc…) which is evaluated every time the loop is executed by the computer. If the value of the expression is true, then it will carry on with the instructions.
If the expression evaluates to false (or 0) then the instructions are ignored and the entire while loop ends. The computer then moves onto the next statement in the program.
The second thing to notice about this loop is that the conditional expression comes at the start of the loop: this means that the condition is tested at the start of every ‘pass’, not at the end. The reason that this is important is this: if the condition has the value false before the loop has been executed even once, the statements inside will not get executed at all – not even once.
C while loop
The best way to explain loop is to give an example of its use. One example in order to write the skipgarb() function which complemented scanf().
skipgarb () { while (getchar() != ’\n’) { } }
This is slightly odd use of the while loop which is pure C, through and through. It is one instance in which the programmer has to start thinking C and not any other language. Something which is immediately obvious from listing is that the while loop in skipgarb() is empty: it contains no statements.
C While Loop with Example
// Program summing integers #include <stdio.h> int main(void) { unsigned long sum = 0UL; // The sum of the integers unsigned int i = 1; // Indexes through the integers unsigned int count = 0; // The count of integers to be summed // Get the count of the number of integers to sum printf("\nEnter the number of integers you want to sum: "); scanf(" %u", &count); // Sum the integers from 1 to count while(i <= count) sum += i++; printf("Total of the first %u numbers is %lu\n", count, sum); return 0; }
The assignment inside the conditional expression makes this loop special. What happens is the following. When the loop is encountered, the computer attempts to evaluate the expression inside the parentheses.
There, inside the parentheses, it finds a function call to getchar(), so it calls getchar() which fetches the next character from the input. getchar() then takes on the value of the character which it fetched from the input file.