FSC1331 – Introduction to Programming Tutorial
Chapter 7 – Iteration
1. Rewrite these while loops using the for statements.
x = 14; y = 65;
While (x >= 3) while (y <= 85)
{ {
printf(“%i\n”, x); printf(“%i\n”, y);
x -= 5; y += 5;
} }
2. Rewrite these for statements using while loops.
x = 250;
for (; x >= 100; x -= 50)
printf(“%i\n”, x);
for (y = 1226; y <= 1426; y += 2)
printf(“%i\n”,y);
3. What will be the output be from the following program segment?
for (a = 1; a <= 5; ++a)
{
printf(“%i”, a);
for (b = a; b >= 1; --b)
printf(“%i”, b);
printf(“\n”);
}
printf(“%i %i\n”, a, b);
1/4
FSC1331 – Introduction to Programming Tutorial
4. Which of the following code segment is functionally equivalent to the statement
below?
y += a * c++;
a. y += a * ++c;
b. y = (y + a) * c; c++;
c. y = y + a * c; c++;
d. c++; y = y + a * c;
e. none of the above
5. Use the following code to answer questions (i) to (x).
int t = 0; b = 0; s = 0; z = 0;
scanf(“%i”, &t);
{
s += t;
++z; (z = z+1; z++ || ++z z = 1+z)
scanf(“%i”, &t);
}
b = s / z;
i. Which of the variable is called an accumulator variable?
ii. Which of the variable is called a counter variable?
iii. Which of the variable is tested against a sentinel?
iv. Is it necessary to initialize t to zero in the code?
v. –1 is known as what?
vi. Is it necessary to initialize z to zero in the code?
vii. Is it necessary to initialize b to zero in the code?
viii. Is it necessary to initialize s to zero in the code?
ix. All for loop can be rewritten as a while loop.
x. All for loop counter variables must be incremented/decremented with either
++ or --
Sentinel - value when reached terminates
loop condition
6. How does accumulation work?
7. Why is initialization of an accumulator variable important?
8. How does counting differ from accumulation?
9. What five elements are necessary in a counter-controlled loop?
10. State the possible error found within the for loop statement below.
for (; x >= 100; x -= 50)
printf(“%d\n”, x);
2/4
FSC1331 – Introduction to Programming Tutorial
11. State the output produce by the following C codes.
int x = 1;
for (x=11; x >= 1; x -= 3)
printf(“%4i”, x * x);
12. Given the following C program, indicate the output produce.
void main( void)
{ int i = 0, x = 0;
for (i = 1; i < 20; i *= 2)
{
x++;
printf(“%4i ”, x);
}
printf(“\nx = %i”, i);
}
13. Rewrite the following while loops using double for loop statements.
x = 14;
while (x >= 3)
{
printf(“%d”, x);
x -= 5;
}
y = x;
while (y <= 85)
{
printf(“%d”, y);
y += 5;
}
3/4
FSC1331 – Introduction to Programming Tutorial
Answer questions (i) through (iii) by using the following C codes.
#include <stdio.h>
main( )
{
int a, b;
for (a = 1; a < 3; ++a)
for (b = 1; b <= 3; b++)
printf(“%4d”, a+b);
}
i. Indicate what would be the final value stored in variable a?
ii. Indicate what would be the final value stored in variable b?
iii. Indicate the output produce by the program.
4/4