Assessment Tool

Lecture 9:  Iteration

Content Tested:  Writing loops

Lecture Content:

Goals:

Assessment Technique:  Programming Activity

Purpose:

This programming activity serves to give students experience writing a simple for and while loops.

Activity:



We just saw how loops are created in today's lecture.  This activity will give you experience with writing loops.

For each problem, just write the necessary code for the loops.

1.  Write a loop to print out the numbers from 10 to 20, inclusive.  Print the numbers on separate lines.
 
 
 
 
 

2.  Write a loop to print out the numbers 10 to -10, inclusive.  Print the numbers on separate lines.
 
 
 
 
 

3.  Write a loop to add together double type numbers that the user inputs.  The user will enter a negative number to terminate the calculation.  Print out the resulting value.

For example, if the user types 3.2, 5.6, 2.1, 0.1, -1.0 then the printed value should be 3.2 + 5.6 + 2.1 + 0.1 = 11.000.  This is just an example -- remember, the user could type as many positive numbers as he/she would like.
 
 
 
 
 
 
 

4.  Write a nested loop to print out a triangle of size n by n of *'s.  An example 5 x 5 triangle is below.  You may use the variable n without declaring it.

*****
****
***
**
*
 
 

Possible Solution

1.

int i;
for (i = 10; i <= 20; i++){
    printf("%d\n", i);
}

2.

int i;
for (i = 10; i >= -10; i--){
    printf("%d\n", i);
}

3.

double current;
double total = 0.0;

scanf("%lf", &current);
while (current >= 0){
    total = total + current;
    scanf("%lf", &current);
}
printf("Result:  %f\n", total);

4.

int row, col;

for (row = 0; row < n; row++){
    for (col = 0; col < (n - row); col++){
        printf("*");
    }
    printf("\n");
}

Possible Uses of Activity: