Lab 4 -- Introduction to Loops

CPE101

Winter 2008

 

Updates and Corrections

 

 

Due Date:

 

By the end of your last lab of week 4 (Feb 1).

 

Objectives

 

 

Overview

 

In your last lab you used if and else if statements to modify the flow of exectution of your program.  Another way to modify the flow of execution in your program is with the use of loops.  With a loop, your program can run a piece of code multiple times.  As with the if control statement, the loops must have properly coded condition tests.  You use the condition test to decide whether or not to continue running the code inside the loop.

There are three basic types of loops in C: while, do-while, and for.  Each has its own purpose.  In general, we use 'while' loops and 'do-while' loops when we don't know in advance how many times we will be looping.  The loop will run until some condition is met.  For example, you will keep prompting for numbers until the user enters a zero.  You don't know in advance how many times that will take.  We can use a do-while loop when we know the loop should be run at least once.  A 'for' loop is generally used when we know in advance how many times we need to run the loop.  For example, you need to print "Giants win theWorld Series" to the screen 5 times.  For loops are also commonly used to access each member of an array.

'While' Loops

Here is the format of a while loop:

while (condition) {

   statement(s);

}


The condition is tested as soon as the loop is reached.  If the condition is false the loop will never be entered.  If the condition is true, the statements inside will be run.  After the statements are run, the condition is tested again.  The loop will continue to run until the condition is false.

Here is a while loop that prompts for a number to add to a running total while the total is less that 100:

   int total = 0;

 

   int number;

   while (total < 100) {

      printf("Current total is %d.\n", total);

      printf("Please input a positive number: ");

      scanf("%d", &number);

      total = total + number;

   }


'Do-While' Loops

Here is the format of a do-while loop:

do {

   statements;

} while (condition);


A do-while loop is similar to a while loop except that the condition is at the bottom of the loop.  The code inside the loop is run first, without checking the condition.  The condition is checked for the first time after the statements inside have been run once.  The loop will continue to run until the condition is false.

Note: A do while loop is very helpful for error checking user input.  For example, you can ask a user to enter a number between 1-10.  You know you want to do this at least once.  Then check the condition at the end and ask them again if their input is invalid.

'For' Loops

Here is the format of a for loop:

for (init; condition; update) {

   statements;

}


The init part of the for loop is run once the first time the loop is encountered.  Then the condition is checked.  As with a while loop, the loop is never entered is the condition is false initially.  If the condition is true, the loop is entered and the statements inside are run.  After the statements are complete, the update portion of the loop is run.  Then the condition is checked again.  The loop will continue to run in that cycle (condition-statements-update-condition) until the condition is false.

Here is a 'for' loop that prints 0 - 9 to the screen:

int i;

for (i = 0; i < 10; i++)

{
   printf("%d\n", i);
}

Note that 'i' is initialized to zero only once when the loop is first encountered.  Then the condition is checked, zero is printed to the screen, 'i' is incremented, and the condition is checked again, etc, until 'i' is 10.  Then the condition is false and the loop is exited.  The number 10 is never printed to the screen.

Note also that 'i' is an accepted and common variable name to use as an index in a for loop.

Infinite Loops

It is almost inevitable when working with loops that you will create an infinite loop.  An infinite loop is a loop whose condition never becomes false.  Thus, the loop never exits.  If your loop contains no output, it will appear that the computer is just sitting there doing nothing.  On vogon, to break out of an infinite loop and exit your program, type ctrl-c.

 

Code Reading

 

Determine what the following loops will print to the screen. Write C programs to check your answers.

int x = 0;

while (x < 5)
{
   printf("%d ", x);
   x++;
}
 
Output:




int x = 0;

while (x < 5)
{
   x++;
   printf("%d ", x);
}

Output:





int x = 0;

do
{
   printf("%d ", x);
   x++;
} while (x < 5);
 
Output:






int x = 0;

do
{
   x++;
   printf("%d ", x);
} while (x < 5);

Output:






int i;

for (i=0; i<10; i=i+2)
{
   printf("%d ", i);
}

Output:






 

Lab Requirements (Or the answer to "So what am I supposed to hand in?")

 

  1. In a file called part1.c write a while loop that asks for a number.  Add the number to a running total.  Quit the loop when the user enters a negative number.  Print the total to the screen. 

 

  1. In a file called part2.c write the same loop as part1.c, but use a do-while loop instead of a while loop.

 

  1. Now let's use a do-while loop to check for valid user input.  In a file called part3.c, implement a number guessing game.  #define a number called RIGHT_NUM that is between 1 and 10 (inclusive).  You may pick any number you like.  In your main, use a do-while loop to ask the user to guess a number a number between 1 and 10.  Exit the loop only when they enter a valid number.  Then compare the number they entered to the RIGHT_NUM you already defined.  Print to the screen whether or not they guessed correctly.

Two possible sample runs.  Your I/O does not need to match mine exactly.

Run 1:
Input a number between 1 - 10: 88
Input a number between 1 - 10: -4
Input a number between 1 - 10: 8
Wrong! The correct number was 3!

Run 2:
Input a number between 1 - 10: 0
Input a number between 1 - 10: 3
You got it!

  1. Finally, use a for loop to print a given character to the screen a given number of times.  In a file called part4.c, prompt the user for the character to print.  Then prompt the user for the number of times to print the character.  Use a for loop to print the character in a row the given number of times.

Two possible sample runs.  Again, your I/O does not need to match mine exactly.

Run 1:
What character should I print? *
How many times should I print it? 9
*********

Run 2:
What character should I print? j
How many times should I print it? 15
jjjjjjjjjjjjjjj

 

Handing in Your Source Electronically . . .

  1. If necessary, move your source (part1.c, part2.c, part3.c, and part4.c) to vogon.

 

  1. Log on to vogon via some terminal somewhere.

 

  1. Change directory (cd), as necessary, to the directory where your source file(s) are.

 

  1. Compile and test your source on vogon using the required compiler flags (-Wall --ansi --pedantic)

 

  1. Use the handin command being sure to replace the yy with your lecture section number.

 

11:59 vogon ~$ handin mhaungs Lab4-yy part1.c part2.c part3.c part4.c

 


 

Additional Challenges
(Or the answer to "I'm done already. Got anything else for me to try even though I won't get points for it?")

  1. Write nested for loops (a for loop within a for loop) to print out a 5x5 'X' using asterisks (*).  For an additional challenge, prompt the user for the size of the X.

*   *
 * *
  * 
 * *
*   *

  1. Write a program to determine and print all the prime numbers less than one million.  If you do this the long way it will take your code around 15 minutes to run.  If you make some simple changes to optimize the code, it can run in 5 seconds.