3_Answers_6_3_for-1

3_Answers_6_3_for-1 - CIS 15AG Answers Chapter 6:...

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

View Full Document Right Arrow Icon
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!
Background image of page 1

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

View Full DocumentRight Arrow Icon
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)
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 09/02/2011 for the course CIS 15BG taught by Professor Staff during the Spring '10 term at DeAnza College.

Page1 / 7

3_Answers_6_3_for-1 - CIS 15AG Answers Chapter 6:...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online