LOOP EXERCISES



 1. What are the value of i and j after the following code is executed?

    (a)    int i, j;
           for (i = 0, j = 0; i < 10; i++)
              j += i;

    (b)    int i, j;
           for (i = 0, j = 1; i < 10; i++)
              j += j;

    (c)    int i, j;
           for (i = 0; i < 10; i++)
              i += i;


 2. What does the following program do?

           #include <stdio.h>
           int main(void) {
              int val, sum = 0;
              while (scanf("%d", &val) != EOF) { 
                 sum += val;
              }
              printf("The sum is %d\n", sum);
              return 0;
           }


 3. Write a program that reads in a sequence of real numbers and
    prints their average and standard deviation. The average and
    standard deviation of the values x_1, x_2, ..., x_n is given by

        avg    = (x_1 + ... + x_n) / n
        stddev = sqrt( (x_1*x_1 + ... + x_n*x_n) / n  -  avg*avg )


 4. Write a program that reads in a sequence of positive and 
    negative integers and prints whether there were more positive
    or negative integers.

 5. Write a program that reads in a sequence of positive integers
    and prints out the longest streak of the same value. E.g.,

         % a.out
         2 6 4 3 3 2 3 2 2 2 2 6 6 6 1 6 6 6
          
         Streak of 4 2's in a row.

 6. Write a program that reads in two integers m and n,
    and prints out an m-by-n rectangle of asterisks.
    
    (a) Use two nested while loops.
    (b) Use two nested for loops.

    yuma.Princeton.EDU% a.out
    Enter the height followed by the width:
    3 10
    **********
    **********
    **********

7.  Write a program that reads in an integer n, and prints out
    the n-by-n triangle pattern below. Use two for loops and
    one if-else statement.

    yuma.Princeton.EDU% a.out
    Enter the size:
    6     
    ******
    .*****
    ..****
    ...***
    ....**
    .....*

 8. Write a program that reads in two integers m and n,
    and prints out the mn gridpoints in the unit square.

    Enter number of x and y points.
    5
    4
    (0.00, 1.00) (0.25, 1.00) (0.50, 1.00) (0.75, 1.00) (1.00, 1.00) 
    (0.00, 0.67) (0.25, 0.67) (0.50, 0.67) (0.75, 0.67) (1.00, 0.67) 
    (0.00, 0.33) (0.25, 0.33) (0.50, 0.33) (0.75, 0.33) (1.00, 0.33) 
    (0.00, 0.00) (0.25, 0.00) (0.50, 0.00) (0.75, 0.00) (1.00, 0.00)