Skip to main content
Logo image

Section 13.1 The while Loop

Remember our program, using a for-loop, to compute the factorial of a number? Essentially, it went like this:
N = 5; 
fac = 1; 
for (i=1; i<=N; i++) { 
  fac = fac * i; 
}
C has three different types of loops. Sometimes we want to loop through a section of code, but we do not know how many times we want it to execute. Maybe we want it to repeat the code while a certain condition is true, or maybe while that condition is not met. In these sorts of cases, a while-loop will come in handy!

If you cannot see this codecast, please click here.

Check Your Understanding Check Your Understanding

1.

Quick review on for-loops:
What is the final value of x (i.e. the value of x after the loop has terminated) when the following code is run:
int x;
for(x=0; x<5; x++) {
  printf("x = %d\n", x);
}

2.

How many times does the following loop get executed, assuming that i is an integer type variable initialized with the value 8:
while (i>0) {
  printf("i = %d\n", i); 
  i = i-1;
}
Feel free to use the window below to try out some code. Be sure to work the correct answer out "by hand" first before verifying your answer using the code window.

admin.....open in new window

Please enter your answer (the number only, no words) in the box below.

3.

What is the value of n after the loop terminates, assuming that before starting the loop, n has the value 19:
while (n<10)
  n = n+1;
Code window for your convenience. Remember to work the correct answer out "by hand" first before verifying it using the code window.

admin.....open in new window

Please enter your answer (the number only, no words) in the box below.

4.

You’d like to add up all of the scores you have received so far on your assignments. Please write a C program that uses a while loop to repeatedly ask the user to enter a score, and that adds up all of these scores until the user enters -1 to finish. Obviously, the -1 should not be added to your final tally.
Finally, print the calculated sum.
Note: scores entered could be negative (you may not have experienced this, but the old SATs actually had negative scores for guessing incorrectly...). Just -1 is not an actual score in this particular exercise and forces the loop to terminate.

admin.....open in new window

When your program performs correctly you’ll be given a keyword to enter in Canvas.