Skip to main content

Loops

Exercises

Question 6.1

What output does the following program fragment produce?

i = 1;
while (i <= 128) {
printf("%d ", i);
i *= 2;
}
1 2 4 8 16 32 64 128

Question 6.2

What output does the following program fragment produce?

i = 9384;
do {
printf("%d ", i);
i /= 10;
} while (i > 0);
9384 938 93 9

Question 6.3

What output does the following for statement produce?

for (i = 5, j = i - 1; i > 0, j > 0; --i, j = i - 1)
printf("%d ", i);

When the value of i is 2, the value of j will be 1. Next the value of i, i.e. 2 is printed, and the third exrepssion of the for loop is executed, i.e. --i => i = 1 and j = i - 1 => j = 0. The comparision is made, the left comparision does not matter as it does not have any side effect, so j > 0 is only used to determine, and since j = 0 is false, the for loop terminates.


Question 6.4

Which one of the following statements is not equivalent to the other two (assuming that the loop bodies are the same)?

  1. for (i = 0; i < 10; i++) ...
  2. for (i = 0; i < 10; ++i) ...
  3. for (i = 0; i++ < 10; ) ...

Since the third expression of the for loop is run only once the end of loop body is reached, it does not affect if we use the post increment operator or the pre increment operator. It would only make sense that the third statement is not equivalent to the other two. Even though it seems like same as other two statements as i++ only increments i on the later statements and uses the current value of i when the condition is being checked. Okay, so the third one is indeed not equivalent since the value of i is incremented before the loop body is executed.


Question 6.5

Which one of the following statements is not equivalent to the other two (assuming that the loop bodies are the same)?

  1. while (i < 10) {...}
  2. for (; i < 10;) {...}
  3. do {...} while (i < 10);

The last statement is not equivalent to the other two since the do loop will atleast execute once. If the value of i is 10 or more, the while loop and the for loop will not execute, but the do loop will.


Question 6.6

Translate the program fragment of Exercise 1 into a single for statement.

#include <stdio.h>

int main (void) {

int i;

for (i = 1; i <= 128; i *= 2)
printf("%d ", i);

Question 6.7

Translate the program fragment of Exercise 2 into a single for statement.

#include <stdio.h>

int main (void) {

int i;

for (i = 9384; i > 0; i /= 10)
printf("%d ", i);

Question 6.8

What output does the following for statement produce?

for (i = 10; i >= 1; i /= 2)
printf("%d ", i++);
10 5 3 2 1 1 1 1 1 1 1 1 1 1 (infinite 1s)

Question 6.9

Translate the for statement of Exercise 8 into an equivalent while statement. You will need one statement in addition to the while loop itself.

#include <stdio.h>

int main (void) {

int i = 10;

while (i >= 1) {
printf("%d ", i++);
i /= 2;

Question 6.10

Show how to replace a continue statement by an equivalent goto statement.

#include <stdio.h>

int main (void) {

int i;

// using the continue statement
for (i = 10; i >= 0; i--) {
if (i == 1)

Question 6.11

What output does the following program fragment produce?

sum = 0;
for (i = 0; i < 10; i++) {
if (i % 2)
continue;
sum += i;
}
printf("%d\n", sum);
20

Question 6.12

The following "prime-testing” loop appeared in Section 6.4 as an example:

for (d = 2; d < n; d++)
if (n % d == 0)
break;

This loop isn't very efficient. It's not necessary to divide n by all numbers between 2 and n - 1 to determine whether it's prime. In fact, we need only check divisors up to the square root of n. Modify the loop to take advantage of this fact. Hint: Don't try to compute the square root of n; instead, compare d * d with n.

#include <stdio.h>

int main (void) {

int n, d;

printf("Enter the number to check if it's prime or not: ");
scanf("%d", &n);

Question 6.13

Rewrite the following loop so that its body is empty:

for (n = 0; m > 0; n++)
m /= 2;
for (n = 0; m > 0; n++, m /= 2);

Question 6.14

Find the error in the following program fragment and fix it.

if (n % 2 == 0);
printf("n is even\n");
if (n % 2 == 0)
printf("n is even\n");

Programming Projects

Project 6.1

Write a program that finds the largest in a series of numbers entered by the user. The program must prompt the user to enter numbers one by one. When the user enters 0 or a negative number, the program must display the largest non negative number entered:

Enter a number: 60
Enter a number: 38.3
Enter a number: 4.89
Enter a number: 100.62
Enter a number: 75.2295
Enter a number: 0

The largest number entered was 100.62

Notice that the numbers aren't necessarily integers.

#include <stdio.h>

int main (void) {

float n, max = 0.00f;

do {
printf("Enter a number: ");
scanf("%f", &n);

Project 6.2

Write a program that asks the user to enter two integers, then calculates and displays their greatest common divisor (GCD):

Enter two integers: 12 28
Greatest common divisor: 4

Hint: The classic algorithm for computing the GCD. known as Euclid's algorithm, goes as follows: Let m and n be variables containing the two numbers. If n is 0, then stop: m contains the GCD. Otherwise, compute the remainder when m is divided by n. Copy n into m and copy the remainder into n. Then repeat the process, starting with testing whether n is 0.

#include <stdio.h>

int main (void) {

int n, m, remainder;

printf("Enter two integers: ");
scanf("%d%d", &m, &n);

Project 6.3

Write a program that asks the user to enter a fraction, then reduces the fraction to lowest terms:

Enter a fraction: 6/12
In lowest terms: 1/2

Hint: To reduce a fraction to lowest terms, first compute the GCD of the numerator and denominator. Then divide both the numerator and denominator by the GCD.

#include <stdio.h>

int main (void) {

int numerator, denominator;
int remainder;

printf("Enter a fraction: ");
scanf("%d/%d", &numerator, &denominator);

Project 6.4

Add a loop to the broker.c program of Section 5.2 so that the user can enter more than one trade and the program will calculate the commission on each. The program should terminate when the user enters 0 as the trade value:

Enter value of trade: 30000
Commission: $166.00

Enter value of trade: 20000
Commission: $144.00

Enter value of trade: 0

#include <stdio.h>

int main (void) {

float transaction_size, commission_rate = 0;

for (;;) {
printf("Enter value of trade: ");
scanf("%f", &transaction_size);

Project 6.5

Programming Project 1 in Chapter 4 asked you to write a program that displays a two-digit number with its digits reversed. Generalize the program so that the number can have one, two, three, or more digits. Hint: Use a do loop that repeatedly divides the number by 10, stopping when it reaches 0.

#include <stdio.h>

int main (void) {

int num;
int reverse_num = 0;

printf("Enter a number: ");
scanf("%d", &num);

Project 6.6

Write a program that prompts the user to enter a number n, then prints all even squares between 1 and n. For example, if the user enters 100. the program should print the following:

4
16
36
64
100

#include <stdio.h>

int main (void) {

int n;

printf("Enter a number: ");
scanf("%d", &n);

Project 6.7

Rearrange the square3.c program so that the for loop initializes i, tests i, and increments i. Don't rewrite the program: in particular, don't use any multiplications.

#include <stdio.h>

int main (void) {

int i, n, square = 0;

printf("This program prints a table of squares.\n");
printf("Enter number of entries in table: ");
scanf("%d", &n);

Project 6.8

Write a program that prints a one-month calendar. The user specifies the number of days in the month and the day of the week on which the month begins:

Enter number of days in month: 31
Enter starting day of the week (l=Sun, 7=Sat): 3

       1 2 3 4 5  6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31

Hint: This program isn't as hard as it looks. The most important part is a for statement that uses a variable i to count from 1 to n, where n is the number of days in the month, printing each value of i. Inside the loop, an if statement tests whether i is the last day in a week; if so, it prints a new-line character.

#include <stdio.h>

int main (void) {

int days, starting_day;

printf("Enter number of days in month: ");
scanf("%d", &days);

Project 6.9

Programming Project 8 in Chapter 2 asked you to write a program that calculates the remaining balance on a loan after the first, second, and third monthly payments. Modify the program so that it also asks the user to enter the number of payments and then displays the balance remaining after each of these payments.

#include <stdio.h>

int main (void) {

float loan = 0.0f, interest_rate = 0.0f, monthly_payment = 0.0f;
int num_of_months;

printf("Enter amount of loan: ");
scanf("%f", &loan);

Project 6.10

Programming Project 9 in Chapter 5 asked you to write a program that determines which of two dates comes earlier on the calendar. Generalize the program so that the user may enter any number of dates. The user will enter 0/0/0 to indicate that no more dates will be entered:

Enter a date (mm/dd/yy): 3/6/08
Enter a date (mm/dd/yy): 5/17/07
Enter a date (mm/dd/yy): 6/3/07
Enter a date (mm/dd/yy): 0/0/0
5/17/07 is the earliest date

#include <stdio.h>

int main (void) {

int day, month, year;
int early_day = 31, early_month = 12, early_year = 99;

for (;;) {


Project 6.11

The value of the mathematical constant ee can be expressed as an infinite series:

e=1+1/1!+1/2!+1/3!+...e = 1 + 1/1! + 1/2! + 1/3! + ...

Write a program that approximates ee by computing the value of

1+1/1!+1/2!+1/3!+...+1/n!1 + 1/1! + 1/2! + 1/3! + ... + 1/n!

where nn is an integer entered by the user.

#include <stdio.h>

int main (void) {

int n;
float value_of_e = 1.00f;
float factorial_value = 1.00f;

printf("Enter the value of n: ");

Project 6.12

Modify Programming Project 11 so that the program continues adding terms until the current term becomes less than εε, where εε is a small (floating-point) number entered by the user.

#include <stdio.h>

int main (void) {

float value_of_e = 1.00f;
float factorial_value = 1.00f;
float e, current_term = 1.00f;
int count = 0;