Introduction
Most programs run and keep on processing until the user exits the applications. Within those applications, running calculations and key input will run many computational tasks; in some cases thousands, if not millions of times a second. This is all attributed and made possible by using Loops.
Handling Loops is an essential task for any programmer, whether it is collecting data entries from a system, or running and updating a video game. In this article, we will go through different types of loops; as there are three main loops which we will deal with in C. Those are For loop, While loop, and Do-While loop. They use similar logic to the previous tutorial on conditional statements.
For Loop
For Loop is designed to perform a predetermined number of times for a section of code to run within a loop. Below shows the basic set up.
for(initialisation;condition;iteration_count)
To initialise a for loop you would of course use a for keyword. Then within the parenthesis that follows, you set the conditions in which the loop runs to. There are three segments within the parenthesis, which are separated by the semi-colon (;). The first segment is the initialisation of the loop counter. You can set it up by using a variable identifier which can be given any value to initialise with; you can leave it blank as long as you have initialised a value beforehand (more explained later in the article). The second segment is where the condition is set; continuing the loop while the condition remains true. The third segment is the iterator count, which increases or decreases after each loop has been executed. Depending on how you do the iterator using Relational Operator. The example below shows both the basic algorithm and the accompanying code.
Counting Loop to Ten
Count Initialised as 0
i Initialised as 0
for Loop repeat 10 times
Count = Count +1
End Loop
|
int count =0;
int i = 0;
for(i=0; i<10; i++)
{
// FOR LOOP CONDITION IS TRUE
printf("Counting : %d", count);
count++;
}
|
In this small example, you can see how the count is the variable, which we have declared before the loop as an identifier with it being assigned with a zero value. This is the value we want before the loop begins. As we enter the for loop, the initialiser is given is given an identifier name as in this case i. The condition is set so the loop iterates while the i value is less than or equal to the conditional value set which is 10. Then the iterator count has been set as i++, which means that the increment value of i will go up by one at the end of each loop.
Once inside the loop scope within the curly bracket, the code will print the count value. Then straight after, it will performs an increment with the count variable count++.The loop will iterate ten times and the loop will end with the i value being ten.
While Loop
while(condition)
{ ... }
The while loop can run either once, many times, or never. It runs the loop as long as the condition specified in the parenthesis is true, similar to the condition of a if statement. It is important that the variable value which is used within the condition changes; or managed within, otherwise the loop will go on infinitely. You can get out of the loop by force with the break keyword within the scope (shown in the previous tutorial with case statements). It will not affect any values assigned, it is an alternative way, you can escape a loop.
Count Value is Initialised as 0
While Loop (Until Count reaches 10)
Incremental Count +1
End loop
|
count = 0;
while(count < 10)
{
// WHILE CONDITION IS TRUE
printf("Loop Count : %d", count);
count++;
}
|
While the count variable value doesn't match the conditional value in the algorithm example above, it will continue to run until the values match, the code will then exit the loop and move on within the program.
Do-While Loop
do { .... } while (condition)
The do-while loop is the opposite of the whole loop as it will always run at least once as the condition is placed at the end of the loop, which means it exits once it reaches the end of a loop; unlike a while loop, which can exit at the beginning of a loop.
Do-While Loop - Begin
Print Message for user to Input
User Enter A Number Score
While (Score < 500) // If Condition Score under 500
// Continue Loop, If Over then Exit
|
int score = 0;
// DO LOOP TRUE WHILE ENTERED DATA IS UNDER 500
do{
printf("Enter Score : ");
scanf("%d",&score);
}while(score < 500)
|
Like the while loop, you can exit with the break keyword inside your statement.
In our code example, we are going to be executing the three different types of loops in C.
Example Code In Detail
First we will define a global variable, it could have been placed inside the main function; but left it there deliberately to separate it from the variables which will be used by the loop conditions.
#include <stdio.h>
// DECLARE GLOBAL VARIABLE IDENTIFIERS
int tencount;
Then once we enter the main loop, we will declare the integers which the loop will use. In earlier versions of C (for example C90), you can only do this at the beginning of a function or a curly bracketed scope; some compilers will report errors if you place any variables elsewhere. Only in the latest compilers allow you to declare wherever you want within a function, or scope. As log as we can assign a value to begin the loop with, the program is ready to operate. The snippet below is self explanatory.
int main()
{
// ASSIGN VALUES TO VARIABLES WHICH WILL BE USED FOR
// THE LOOP ITERATIONS
int i;
int j = 10;
int s = 0;
tencount = 1;
We have initialised the values we need to work with all the loops, so we will go straight into the For Loop. As you might have noticed the for loop uses the i integer, which was declared before without it being assigned a value; unlike the others. The reason we have done this is to show how to initialise within the for loop condition; you can declare it earlier, and leave the initialisation segment in the for loop parenthesis empty (for example for(;i<10;i++) ..). We have assigned the value of 1 to i as we will start the count from there and the count will continue while the condition is less than and equal to 10; the condition is then true. Once it goes over that the loop will naturally end, as the condition is false.
printf("First we will count up to ten with the For Loop...\n");
// INCREMENT AND COUNT UP TO 10 WITH THE FOR LOOP
for(i = 1; i <= 10; i++)
{
printf("Increment Count : %d \n",i);
}
The While Loop, will begin with the j variable being initialised with a value of 10. As the condition is over 0, then it is true and the statement within the scope will continue to loop. The code will decrement the j value within the loop. Once the value reaches 0, the While Loop will become false and therefore exit.
printf("\nNow the While Loop count backwards... \n");
// DECREMENT AND COUNT DOWN FROM 10 TO 1
while(j > 0)
{
printf("Decrement Count : %d\n",j);
j--;
}
Now we will deal with the Do While loop, which as we mentioned earlier in the article will at least run once. The variable that will be used is the s integer, and it is initialised with a value of 0. The s integer will increment by 10. You can do anything with any data you will use for a loop condition, as long as you allow the value to leave the loop. This is only an example of how to implement a Do While loop. Any type of conditions can be set, which we will explore in later tutorials.
printf("\nNow we will increment by 10 with the Do-While Loop... \n");
// INCREMENT THE VALUE BY 10, AND DO IT UNTIL REACHES 100
do
{
s+=10;
tencount = s;
printf("Count : %d\n", tencount);
}while(s < 100);
printf("\nPress ENTER key to exit");
fflush(stdin);
getchar();
return 0;
}
Summary
As we have gone over the basics of Loops in C, it will be important in later tutorials to know how looping and controlling the flow of your program. The key of using loops effectively is to make sure you know which one suits the task in hand. In time, you will find out for yourself how to do little tweaks with a loop, which can not only help you define your program work flow the way you want; but you can also do optimisations with the general performance of a program. Once you have dealt with loops unaided, you have nearly mastered one of the most important aspects of C programming.