CMSC 104

Problems with the for and do/while statements


1.) State which values of the control variable x are printed by each of the following:

a.) for ( x = 2; x <= 13 ; x +=2 ) { printf("%d \n", x); } b.) for ( x = 5; x <= 22; x += 7 ) { printf("%d \n", x ); } c.) for ( x = 3; x <= 15; x +=3) { printf("%d \n", x ); } d.) for ( x = 1; x <= 5; x += 7) { printf("%d \n", x); } e.) for ( x = 12; x >= 2; x -= 3 ) { printf("%d \n", x ); }

2.) Find the errors in the following:

a.) For ( x = 100, x >= 1, x++) { printf("%d\n", x); }

b.) The following code should print whether a given integer is odd or even:

switch (value % 2 ) { case 0: printf( "Even integer\n"); case 1: printf("Odd integer\n"); } c.) for ( x = .000001; x <= .0001; x += .000001) { printf("%.7f\n", x ); }

d.) The following code should output the odd integers from 999 to 1:

for ( x = 999; x >= 1; x += 2) { printf("%d\n", x); }

e.) The following code should output the even integers from 2 to 100:

counter = 2; Do { if ( counter % 2 == 0) { printf("%d \n", counter); } counter += 2 } While ( counter < 100);

3.) Write for statements that print each of the following sequences:

  • a.) 1, 2, 3, 4, 5, 6, 7
  • b.) 3, 8, 13, 18, 23
  • c.) 20, 14, 8, 2, -4, -10
  • d.) 19, 27, 35, 43, 51
  • 4.) What does the following program do?

    #include <stdio.h> main() { int i, j, x, y; printf("Enter integers in the range 1-20: "); scanf("%d%d", &x, &y); for ( i = 1; i <= y; i++ ) { for ( j = 1; j <= x; j++) { printf("@"); } printf( "\n" ); } }