Loops

C Language

Overview

Loops are another important aspect of control flow in C language. Loops allow you to repeat several lines of code without needing to type it over and over. In C language, there are three main types of loops: a while loop, a for loop, and a do-while loop.


Introduction to Loops

Loops are used to repeat a block of your program. A basic loop works like this: the computer checks whether or not a condition is TRUE (similar to an if structure), if it is, then it executes the body of the loop, and when it is finished, the computer goes back to the condition and checks it again, and this process is repeated; if it is FALSE, then it skips to what is after the loop. So the computer would execute the body over and over as long as the condition stays TRUE. A real life example of you using loops in your everyday life is that when you are walking to a library, for example, your brain checks if you arrived your destination or not, if you haven't (TRUE), you will take another step; if you have arrived (FALSE), then you would stop. Let's look at while loops first.


While Loops

Here is what a while loop looks like:
while(condition)
{
do this over and over as long as the condition is TRUE
}
You can see that the while loop is structured very similar to the if structure. It begins with the keyword "while", then followed by a condition in parenthesis. The computer checks if the condition is TRUE as it would in an if structure. The body is also enclosed in braces. But different from the if structure, when the body finishes executing, the computer goes back to the while line and do this process again. Here is a diagram of how a while loop works:

while Loop Diagram

Here is an example of how a while loop is used in a program that print out the numbers 1 through 10:

#include <stdio.h>

int main()
{
  int num=1;
  while(num<=10) /*The condition part is just like the condition in an if structure, with the 
same operators*/
   {
     printf("%d\t",num);
     num++; /*This increase num by 1 so next time the the computer would print out the number 
that is one greater than the original num*/
   }
  /*This while structure is just saying "as long as num is less than or equal to 10, print out 
num, and increase it by 1"*/
}

1      2      3      4      5     6      7      8      9      10

In this example program, the condition is num<=10, at the beginning, num is 1. The computer checks if num, 1, is less or equal to then 10. Seeing that it is TRUE, the computer executes the body for the first time by printing out "1\t" and increasing num to 2. The computer goes back and evaluate the condition again. Seeing 2 is still less than or equal to ten, it executes the body for the second time and prints out "2\t" and increase num again... After the program print out "10\t" and increase num to 11 on the 10th time executing the body, the computer goes back again to check if num is less than or equal to 10. This time, num is 11, making the condition FALSE. So the computer continues on with the rest of the program and ends the loop.

Loops can be very useful in your programs. You can use it to do much more complex operations. Let's look at some examples.

Examples

#include <stdio.h>

int main()
{
  int num=1,sum=0; /*Set initial values to num:1; sum:0*/
  printf("Calculating 1+2+3...+99+100\n");
  while(num<=100)
   {
     sum+=num; /*This is equal to sum=sum+num; (see Introduction page)*/
     printf("Status:num=%d;sum=%d\t",num,sum); /*Print out the status*/
     num++; /*Increase num by 1*/
   }
  printf("1+2+3...+99+100=%d\n",sum);
}

Calculating 1+2+3...+99+100
Status:num=1;sum=1	Status:num=2;sum=3	Status:num=3;sum=6	Status:num=4;sum=10	
Status:num=5;sum=15	Status:num=6;sum=21	Status:num=7;sum=28	Status:num=8;sum=36	
Status:num=9;sum=45	Status:num=10;sum=55	Status:num=11;sum=66	Status:num=12;sum=78	
Status:num=13;sum=91	Status:num=14;sum=105	Status:num=15;sum=120	Status:num=16;sum=136	
Status:num=17;sum=153	Status:num=18;sum=171	Status:num=19;sum=190	Status:num=20;sum=210	
Status:num=21;sum=231	Status:num=22;sum=253	Status:num=23;sum=276	Status:num=24;sum=300	
Status:num=25;sum=325	Status:num=26;sum=351	Status:num=27;sum=378	Status:num=28;sum=406	
Status:num=29;sum=435	Status:num=30;sum=465	Status:num=31;sum=496	Status:num=32;sum=528	
Status:num=33;sum=561	Status:num=34;sum=595	Status:num=35;sum=630	Status:num=36;sum=666	
Status:num=37;sum=703	Status:num=38;sum=741	Status:num=39;sum=780	Status:num=40;sum=820	
Status:num=41;sum=861	Status:num=42;sum=903	Status:num=43;sum=946	Status:num=44;sum=990	
Status:num=45;sum=1035	Status:num=46;sum=1081	Status:num=47;sum=1128	Status:num=48;sum=1176	
Status:num=49;sum=1225	Status:num=50;sum=1275	Status:num=51;sum=1326	Status:num=52;sum=1378	
Status:num=53;sum=1431	Status:num=54;sum=1485	Status:num=55;sum=1540	Status:num=56;sum=1596	
Status:num=57;sum=1653	Status:num=58;sum=1711	Status:num=59;sum=1770	Status:num=60;sum=1830	
Status:num=61;sum=1891	Status:num=62;sum=1953	Status:num=63;sum=2016	Status:num=64;sum=2080	
Status:num=65;sum=2145	Status:num=66;sum=2211	Status:num=67;sum=2278	Status:num=68;sum=2346	
Status:num=69;sum=2415	Status:num=70;sum=2485	Status:num=71;sum=2556	Status:num=72;sum=2628	
Status:num=73;sum=2701	Status:num=74;sum=2775	Status:num=75;sum=2850	Status:num=76;sum=2926	
Status:num=77;sum=3003	Status:num=78;sum=3081	Status:num=79;sum=3160	Status:num=80;sum=3240	
Status:num=81;sum=3321	Status:num=82;sum=3403	Status:num=83;sum=3486	Status:num=84;sum=3570	
Status:num=85;sum=3655	Status:num=86;sum=3741	Status:num=87;sum=3828	Status:num=88;sum=3916	
Status:num=89;sum=4005	Status:num=90;sum=4095	Status:num=91;sum=4186	Status:num=92;sum=4278	
Status:num=93;sum=4371	Status:num=94;sum=4465	Status:num=95;sum=4560	Status:num=96;sum=4656	
Status:num=97;sum=4753	Status:num=98;sum=4851	Status:num=99;sum=4950	Status:num=100;sum=5050
1+2+3...+99+100=5050

In this program, the variable sum records the total of the numbers, while each time the body of the loop is executed, the sum (which is originally 0), will be added by num, which increases everytime from 1 to 100. As you can see, on the first time the loop's body is executed, the num is equal to 1, and the sum is 0. The computer adds num to sum, getting the new sum, which equals to one; and increase num by 1. Now the second time the loop is executed, the num is 2, and the sum is 1. The computer adds the num to the variable sum, getting the new value of 3. It increase num again... The computer will repeat this process until num=100, and finally getting the sum of 5050.

#include <stdio.h>

int main()
{
  int base,exponent,result=1; /*Example, 5^3=125,5:base;3:exponent;125:result*/
  int current=1; /*Current power calculated in the loop*/
  printf("Enter an exponent expression (a^b):");
  scanf("%d^%d",&base,&exponent);
  while(current<=exponent)
   {
     result*=base; /*Same as result=result*base;*/
     printf("Current status: %d^%d=%d\n",base,current,result);
     current++;
   }
  printf("%d^%d=%d\n",base,exponent,result);
}

Enter an exponent expression (a^b):5^3
Current status: 5^1=5
Current status: 5^2=25
Current status: 5^3=125
5^3=125

In this example, the result, originally set as 1, will multiply the base for exponent amount of times. In this case, 1 is multiplied by 5 three times. At the beginning (result: 1; base: 5; exponent: 3; current 1), current, 1, is less than or equal to exponent, 3, so the result (1), is multiplied by base, 5, so the new result is 5. Current is then increased by 1 to 2, and the condition is evaluated again. Being TRUE, the result, now being 5, is multiplied by 5 again, making 25. Then the third time, 25 is multiplied by 5 again, resulting 125. This time, after the increment, the current will be equal to 4, making the condition FALSE, and ends the loop, finding the result of 5^3. As you can see, the status is printed each time the computer loops around with the printf statement, and shows the current values of the variable current and result.

For the condition of your loop, you can also put a constant expression (same for if structure). Anything other than 0 would evaluate to TRUE, and 0 would evaluate to FALSE. But be careful, a non-zero constant expression would create an infinite loop (except if you use a break; or continue; statement, which will be discussed later)!

for Loops

The second type of loop is a for loop, which is a little more complex than the while loop, but it is the most used since it is most convenient. Here is the basic structure of a for loop:
for(expr 1;condition;expr 2)
{
body
}
This would be equivalent to this in a while loop:
expr 1;
while(condition)
{
body
expr 2;
}
As you can see, there are three parts of the for structure separated by semicolons. The condition, is the second part of the three. It acts the same way as it would in a while loop. The first part, shown by expr 1 above, is executed first no matter what the condition evaluates to (this is usually variable initialization, shown in the next example). Then, the computer evaluates the condition, if it is TRUE, the body is executed, and when that is finished, the third part, or expr 2, is executed (normally a variable update). Here is a diagram:

for Loop Diagram

Here is the previous program of finding the sum of 1 through 100 written in a for loop:

#include <stdio.h>

int main()
{
  int num,sum;
  printf("Calculating 1+2+3...+99+100\n");
  for(num=1;num<=100;num++)
   {
     sum+=num;
   }
  printf("1+2+3...+99+100=%d\n",sum);
}
	

Calculating 1+2+3...+99+100
1+2+3...+99+100=5050

As you can see, the for loop is much compacted than the while loop, and would be especially useful when doing operations in arrays. First the computer sets num to 1. Then, the condition is evaluated to TRUE, executing sum+=num. When that is finished, expr 2, in this case, num++, is executed, and the computer loops back and evaluates the condition again. The for loop is just a compacted version of the while loop, but can save you a lot of time in many situations.You can also leave parts of the for loop blank, for example: for(;num<=100;num++) is a for loop without expr 1.

Example

#include <stdio.h>

int main()
{
  /*Print out the table of perfect squares from 1-100*/
  int num;
  printf("Perfect squares within 100:\n");
  for(num=1;num<=10;num++)
   {
     printf("%d^2=%d\n",num,num*num); /*%d is printf statements can also be used to print out a constant 
expression, not just a variable. In this example, num*num is printed as the second %d*/
   }
  printf("1+2+3...+99+100=%d\n",sum);
}
	

Perfect squares within 100:
1^2=1
2^2=4
3^2=9
4^2=16
5^2=25
6^2=36
7^2=49
8^2=64
9^2=81
10^2=100

do-while Loop

A do-while loop is used least frequently, but may come useful in some situations. In a do-while loop, the body is executed at least one time, no matter the condition is TRUE or FALSE. The computer, actually, first execute the body for one time, then when it is finished, it then checks the condition. If this evaluates to TRUE, then the body is repeated. If it is FALSE, then the computer continues. Here is a diagram:

do-while Diagram

Here is the basic structure of the do-while loop:
do
{
body
}while(condition); /*note the semicolon*/

With the do-while loop, you can write a calculator program that can allow the user to repeatedly do operations in a single execution:

#include <stdio.h>

int main()
{
  int a,b,result;
  char operation;
  int mode; /*This stores whether the user wants to calculate again*/
  do
   {
     printf(":");
     scanf("%d%c%d",&a,&operation,&b);
     if(operation=='+')
      {
        result=a+b;
      }
     else if(operation=='-')
      {
        result=a-b;
      }
     else if(operation=='*')
      {
        result=a*b;
      }
     else if(operation=='/')
      {
        result=a/b;
      }
     else
      {
        printf("Operation not developed! Try again!\n");
        mode=1;
        continue;/*See explanation below*/
      }
     printf("%d%c%d=%d\n",a,operation,b,result);
     printf("Do you want to calculate again? (1=yes;0=no)");
     scanf("%d",&mode);
   }while(mode==1);
}
	

:5+3
5+3=8
Do you want to calculate again? (1=yes;0=no)1
:4-6
4-6=-2
Do you want to calculate again? (1=yes;0=no)1
:6^7
Operation not developed! Try again!
:6*7
6*7=42
Do you want to calculate again? (1=yes;0=no)0

do-while structures are not that useful, but in cases like this, it would be better than a while loop because with a while loop, you would need to set the mode to 1 before you write the loop (that could be more difficult if the initialization is an input from the user or a more complex operation than just mode=1;). This program will just allow the user to put in calculations over and over until mode is not equal to 1 anymore.

break; and continue;

There are two useful statements that are sometimes used in loops. The break; statement, which we used before in switch case to exit the structure, and the continue; statement.

break;

The break; statement, exits the current loop or switch case structure that it is in, and ignores what's left in the loop that is unfinished. The break; statement terminates the loop instantly, without executing the rest of the loop. This is often used to handle some special situations that you want the loop to end. Also, notice that break; and continue; statements, as shown in the example above, are not affected by other control flow structures they are in. So although the continue; statement above is inside the if structure, that doesn't affect it and it still has its affect on the loop that it is in. Again, the break; statement just terminates the entire loop and continue on the program.

continue;

The continue; statement is used in the previous example. It is a little bit different from the break; statement, but does basically the same thing. The difference is that the continue; statement doesn't terminate the whole loop, but just that time the body is executed. Which means, the computer will skip over what's left in the loop, but instead of going on to the rest of the program, it goes back to the condition and resumes the loop.

Here is the diagram for break; and continue;

break; and continue; Diagram

Practice

Debug the following program:

#include <stdio.h>

int main()
{
  /*Print out the Fibonacci Sequence up until an inputted number*/
  int limit;
  int num_1,num_2;
  printf("Enter a limit (the program will print the Fibonacci Sequence until exceeds that number:");
  scanf("%d",&limit);
  for(num_1=1,num_2=1;num_1<=limit;num_2+=num_1,num_1=num_2,printf("%d\t",num_1));
  /*Putting two statements inside one part of the for loop is legal, as well as leaving the body empty
by using a semicolon. The mistakes here is logic. (This is a bad example! Do not use for statements like 
this! As you can see here, compacting all of the loop into one line is very unclear to the reader! Try 
to write out this loop in a clearer way so its easier to find the mistakes)*/
  printf("\n");
}

Write a program that calculates the factorial of an inputted number. (Factorial: a!=a*(a-1)*(a-2)*(a-3)...*2*1)

Write a program to calculate the GCF and LCM of two inputted numbers. (see the link for additional practices below for help and more information on this problem)

Additional practices on loops:

Activity 6.2.1

Activity 6.2.2

Activity 6.2.3 (help on GCF and LCM program)

<< Previous TOC Next >>