In a Loop
Hello! Welcome back to Getting Started with C Programming! Just a quick reminder: you are already halfway through the course. Yay you!
When writing programs, sometimes we need to repeatedly perform the same operation. For example, you want your program to display the numbers from 1 to 100. One way to do that would be to use hundred printf statements. But you are coder, and you are going to use a loop statement.
printf(“%i \n”, number);
number = number + 1;
This is one of the simplest loop structures. The computer checks if the number is less than or equal to 10. If it satisfies this condition, the number is displayed, and then incremented by 1. This process continues until the number 10 is displayed. Since the statement for incrementing the number by 1 is present immediately after the display statement, the number becomes 11 and the while loop is again executed. This time, the condition is not satisfied, so we come out of the while loop and go to the next line. As we don’t have any other statement after this, the program ends when it reaches the final closing curly bracket.
Another commonly used loop structure is the for loop.
int counter, number=10;
for(counter=1 ; counter<=10 ; counter=counter+1)
printf(“%i \n”, counter);
This program does everything that the previous program did but is more compact. See the for statement. At first, the value 1 is assigned to the variable counter, followed by a semicolon to signal the end of value assignment. Then, the maximum value that counter is allowed to reach is specified. And finally, the last part increments counter by 1 for each iteration of the loop.
The assignment of value to counter happens exactly once. Then the condition specified by the for statement is checked, and if the condition is satisfied, the computer performs the statements contained within the for loop—that is, in our case, display the value of counter. Next, the third and final part of the for statement is performed; that is, counter is increased by 1, and the computer goes back to checking the condition specified by the second part of the for loop. This goes on until the condition is not satisfied, at which point we come out of the for loop and move to the next line in the program code.
The for loop may seem slightly confusing at first, but once you get the hang of it, you will find yourself using it more than the while loop.
See you tomorrow with more on loops. Till then, happy coding!
Share with friends