CMSC 104

Problems with the if and while statements


1.)Identify and correct the errors in the following ( Note: there may be more than one error)

if (age >= 65); { printf("Age is greater than or equal to 65\n"); } else { printf("age is less than 65\n"); }
int x = 1, total; while (x <= 10) { total = total + x; x = x + 1; }
while ( y > 0 ) { printf(" %d\n", y ); y = y + 1 ; }
2.) What does the following program print?

main() { int x = 1, total =0, y; while (x <= 6) { y = x * x; printf( "%d\n", y); total = total + y; x = x + 1; } printf("Total is %d\n", total); return 0; }
3.) Determine the output for each of the following when x is 9 and y is 11, and when x is 11 and y is 9. Note: the compiler ignores indentation, and it always associates an else with the previous if unless told to do otherwise by the placement of braces { }. Hint: ( apply indentation conventions you have learned)

a.)

if (x < 10) if (y > 10) printf("******\n"); else printf("######\n"); printf("$$$$$$\n");

b.)

if (x < 10) { if (y > 10) printf("******\n"); } else { printf("######\n"); printf("$$$$$$\n"); }

c.)

float a, b, c; a = 3.0; c = 2.0; a *= b = a + 5.0 ; a *= b += c = c + a ; printf("%f \n", a>b ? a : b ); a>b ? printf("a is larger than b\n") : printf(" b is larger than a\n");

4.) Modify the following code to produce the output shown. Use proper indentation techniques. You may only insert braces. Note: it is possible that no modification is needed for some cases.

if (y = = 8) if (x = = 5) printf("@@@@@@\n"); else printf("######\n"); printf("$$$$$$\n"); printf("&&&&&&\n");

a.) Assuming x = 5 and y = 8, the following output is produced:

@@@@@@ $$$$$$ &&&&&&

b.) Assuming x = 5 and y = 8, the following output is produced:

@@@@@@

c.) Assuming x = 5 and y = 8, the following output is produced:

@@@@@@ &&&&&&

d.) Assuming x = 5 and y = 7, the following output is produced:

###### $$$$$$ &&&&&&