CSC161 2010F Imperative Problem Solving

Laboratory: Loops in C

Summary: In this laboratory you will study loops and iterative program control using the C programming language.

Prerequisites: Compiling C programs, input/output in C, conditionals in C



Exercise 1: Printing Patterns

Write programs that use loops to print each of the following patterns:


5   4   3   2   1   0  -1  -2  -3


6   8  10  12  14  16  18


Hello!  Hello!  Hello!  Hello!  Hello!


Hello!  Hello!!  Hello!!!  Hello!!!!  Hello!!!!!





Exercise 2: Generalizing Patterns

Rewrite your programs from the prevoius exercise so that they take the number of values to print as a command line parameter.

Exercise 3: Powerful Tables

Write a program that prints a table in which each row contains a number N together with its square, square root, cube, and cube root. The table should include 1 ≤ N ≤ 50. Label each of the columns in the table appropriately.

Exercise 4: Problematic Points

Experiment with each of the following code segments in a program, and explain why the code probably does not do what the programmer intended. (In each case, assume j and sum have type int.)


 for (j = 1; j <= 10; j++);
   printf ("%4d", j);


   sum = 0;
   for (j = 1; j <= 10; j++) {
      sum = sum + j;
      j = j + 1;

Exercise 5: What was that mathematician's name, anyway?

a. Write a program that uses a loop to add the numbers 1 through 10, and then prints the result (which will be 55).

b. As you may know, the sum of the integers from 1 through n is always equal to (n)(n+1)/2. Write a program that verifies this formula, for 1≤n≤100. That is, your program should loop over the values of n from 1 to 100, and for each value it should compute the sum as done in part a above and compare it to the result from the formula. For each discrepancy found, your program should output a message such as formula doesn't work for n=35. (Of course, if your program is correct, there will be no output.)

Exercise 6: Why isn't this exercise 3?

Write a program that outputs the first 10 multiples of the number 3, printing each number on a separate line. In addition, print "even" or "odd" after each number, as appropriate. (Don't you dare write 10 separate printf statements to do this!)

For Those With Extra Time

Read all the extra problems and decide which you want to do first.

Extra 1: Using scanf inside loops

a. The function scanf returns an integer: the number of data values that were correctly read, which may be fewer than the number of reads attempted. A read attempt is unsuccessful if the input characters cannot be converted according to the given format code. For example, if scanf is trying to read an int, but it receives the letter 'a', it will return 0.

If scanf encounters the end of file, it will return EOF. (EOF is a constant defined in stdio.h. Its value is -1, but your code should not depend on this. Rather, you can use EOF literally as shown in the following example.

  int input;
  printf("a prompt: ");
  while (scanf("%d", &input) != EOF) 
      // do something interesting here

Write a short program that prompts the user for an integer, reads the input, and then prints the value read and the value returned by scanf. Experiment with this program by entering integers, real numbers, letters, and ctrl-d. (As you have seen before, entering ctrl-d is a way for the user to signal the end of input.)

b. Modify your program from the previous exercise to continue prompting the user and printing the values entered, as long as the input is read correctly. When the loop terminates, your program should print a message indicating whether it terminated because scanf encountered the "end of file" (EOF) or invalid data.

Of course, you will want to experiment with your program to see how it behaves!

c. Write a program that prompts the user to enter real numbers, and counts the number of input values that are positive, negative, and zero. Your program should contine prompting until the user enters ctrl-d. At that point, print the final counts.

Recall that scanf requires the format codes "%f" and "%lf" for floats and doubles, respectively.

A sample session might look like this:

 Enter a real number: 10.8
 Enter a real number: -4.2
 Enter a real number: 0.0
 Enter a real number: -645
 Enter a real number: 1298
 Enter a real number: -1.1
 Enter a real number: < ctrl-d >

 Number of positives: 2
 Number of zeros:     1
 Number of negatives: 3

Extra 2: The Costs of Credit

Suppose you charge $497.60 on a credit card. The company will require you to make a minimum payment each month, say $15.00. They will also charge interest at the end of each month, say at a monthly rate of 1.5% of the outstanding balance. The balance for the next month is computed by the formula:

new balance = old balance + interest - payment

This problem asks you to investigate the cost of making only the minimum monthly payment.

Write a program that reads the amount borrowed, the monthly interest rate, and the constant monthly payment. Have the program print a labeled table showing the month number and the balance at the beginning of that month (the balance at the beginning of month 1 is the amount borrowed). Continue printing until a payment would cause the balance to drop below zero. Also print the final payment necessary to close the loan, the total amount made in payments, and the "cost" of the loan (total payments - loan).

Extra 3: Primes

Recall that a positive integer is prime if it is greater than 1 and if it is divisible only by 1 and by itself. Thus 7 and 23 are prime, while 22 and 35 are not.

a. Write a C program prime.c that reads a positive integer n and prints whether n is a unit (i.e., 1), a prime, or a composite (i.e., a non-prime integer greater than 1).

b. Modify program prime.c so that it continues reading and processing integers until the value read is zero. For each non-zero number read, the program should print whether n is a unit (i.e., 1), a prime, or a composite (i.e., a non-prime greater than 1).



August 2008 [Marge Coahran]

  • Combined material from two csc201 labs ("getting started" and I/O) and Henry's csc161 lab on loops. (Note that the csc201 labs had previously been cobbled together from labs 2-5 in the UofT csc180 sequence.)

29 September 2010 [Samuel A. Rebelsky]

  • Reformatted.
  • Renumbered problems a bit.
  • Other minor cleanup.


Disclaimer: I usually create these pages on the fly, which means that I rarely proofread them and they may contain bad grammar and incorrect details. It also means that I tend to update them regularly (see the history for more details). Feel free to contact me with any suggestions for changes.

This document was generated by Siteweaver on Wed Sep 29 08:40:01 2010.
The source to the document was last modified on Wed Sep 29 08:39:59 2010.
This document may be found at

Samuel A. Rebelsky,