This preview shows pages 1–3. Sign up to view the full content.

CIS 15AG Answers Chapter 6: Repetitions (for) 14.Write a C function to print n asterisks using while , then using for . 1 void printStars(int n) { int i; i = 1; while ( i <= n ) { printf("*\n"); i++; } return; } True i i + 1 i 1 i WRITE '*' printStars(n) return void printStars(int n) { int i; for ( i = 1; i <= n; i++ ) printf("*\n"); return; } void printStars(int n) { for ( ; n > 0; n-- ) printf("*\n"); return; } #include<stdio.h> void printStars( int ); int main( void ) { int num = 5; printStars( num ); return 0; } n is initialized by the calling statement!

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
Answers Chapter 6: Repetitions (for) 15. Write a C function to print all even numbers between 2 and n. void printEven(int n) { int i; for ( i = 2; i <= n ; i += 2 ) printf("%d ", i ); return; } 16. This function prints all even numbers between 2 and n. How would you grade it on a scale from 1 (worst) to 10 (best)? void printEven ( int n ) { int i; for ( i = 2; i <= n ; i++ ) { if ( i % 2 == 0 ) printf("%d ", i ); } return; } Not 10, for sure, although it gives the correct output. The test inside the for just adds more operations per iteration! It can be easily eliminated, by changing i++ to i += 2 17. Write a C function to print all odd numbers between 5 and n. void printOdd(int n)
This is the end of the preview. Sign up to access the rest of the document.