
























Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!

























CS 16: Solving Problems with Computers I Lecture # Ziad Matni Dept. of Computer Science, UCSB
Recall: x! = 1 * 2 * 3 … * x You could code this out as either:
an = an-1 + 5
The BASE case The RECURSION (i.e. the function calling itself)
void write_vertical( int n ); //Precondition: n >= 0 //Postcondition: n is written to the screen vertically // with each digit on a separate line
Algorithm design
The write_vertical algorithm:
void write_vertical( int n ) { if (n < 10) cout << n << endl; // n < 10 means n is only one digit else // n is two or more digits long { write_vertical ( n-with-the-least-significant-digit-removed ); cout << the least-significant digit of n << endl; } }
The write_vertical function in C++
void write_vertical( int n ) { if (n < 10) cout << n << endl; // n < 10 means n is only one digit else // n is two or more digits long { write_vertical (n / 10); cout << (n % 10) << endl; } }
write_vertical(543)
write_vertical(54)
write_vertical(5) (^) cout << 5 << endl;
void write_vertical( int n ){ if (n < 10) cout << n << endl;else { write_vertical(n / 10); } cout << n % 10 << endl; }
cout << 4 << endl;
cout << 3 << endl;
stdout: 5 4 3
①
②
③
④
⑤