Name: CS 30 Winter 2007 Midterm 1 Solutions to problems 2 through 4. 2. (20 pts) What does the following program print? #include main() { int i; i = 17; while (i <= 28) { printf("%d ", i++); i = i + 3; } } Answer: 17 21 25 3. (20 pts) Rewrite the program in problem 2 using a for loop instead of a while statement. #include main() { int i; i = 17; for (i = 17; i <= 28; i = i+4) { printf("%d ", i); } } 4. (20 pts) What does the following program print out? #include main() { int i,j,k; for (i = 1; i <= 2 ; i++) { for (j = i+1; j <= 4; j++) { for (k = j+2; k <= 7; k++) { printf("%d %d %d\n", i, j, k); } } } } Answer: 1 2 4 1 2 5 1 2 6 1 2 7 1 3 5 1 3 6 1 3 7 1 4 6 1 4 7 2 3 5 2 3 6 2 3 7 2 4 6 2 4 7 5. (40 pts) Write a program that asks the user to input a list of real numbers which can either be positive or negative or zero. Inputing ends when the user enters the EOF symbol. The program counts the number of input numbers that are strictly positive, the number that are zero and the number that are strictly negative, and prints out those three counts, along with appropriate explanation of the output. The program also computes the product of all the strictly positive numbers and prints that number. Answer: /* CS30 midterm 1 problem 5 solution */ #include int main() { float input, product; /* "real" numbers are floats, not ints */ int pos, neg, zero; /* our counters */ pos = 0; neg = 0; zero = 0; product = 1.0; printf("Please enter a number: "); while(scanf("%f",&input) != EOF) { if(input > 0) /* positive input */ { pos++; product *= input; } else if(input < 0) /* negative input */ neg++; else if(input == 0) /* zero input */ zero++; else /* we should never get here */ printf("error: this number is not positive, negative, or zero!\n"); printf("Please enter a number: "); } printf("\nPositive count: %d, Negative count: %d, Zero count: %d\n", pos, neg, zero); printf("Product of positive numbers: %f\n", product); return 0; }