// Course: CS 12 // Lecture Section: 1 // Lab Section: 21 // Assignment #: In-lab exercise 1 // First Name: Wagner // Last Name: Truppel // ID Number: 12-345-678 // Email address: wagner@cs.ucr.edu // ======================================================================= #include void f(const unsigned char c, const unsigned int n); int main () { unsigned char c; std::cout << "Please enter the character to be used: \n"; std::cin >> c; unsigned int n; std::cout << "Please enter the number of lines per branch, n: \n"; std::cin >> n; unsigned int h; std::cout << "Please enter the number of tree branches, h: \n"; std::cin >> h; // print h branches for (unsigned int i = 0; i < h; i++) { f(c, n); } return 0; } // f(c, n) prints n lines, where the top one has a single // appearance of the character c, the second one has three // appearances of c, the third one has five appearances of // c, and so on, all of them centered. // // The key idea is to notice the patterns. If the 1st // line has 1 character, the 2nd has 3, the 3rd has 5, // and so on, then the n-th line will have (2*n - 1) // characters. Also, the last line [the n-th line] has // no blank spaces, the next-to-last [the (n-1)-th line] // has 1 blank at the start and 1 at the end, the (n-2)-th // line has 2 blanks at the start and 2 at the end, and so // on. Thus, the first line has (n-1) blanks at the start // and (n-1) blanks at the end. We can ignore the blanks // at the end; we only need to print the blanks at the // start and the correct number of characters. // // To summarize, the k-th line must have (n-k) blanks and // then (2*k - 1) copies of the character c. We need to // print n such lines. void f(const unsigned char c, const unsigned int n) { for (unsigned int k = 1; k <= n; k++) { // print (n-k) blanks for (unsigned int r = 0; r < (n - k); r++) std::cout << " "; // print (2*k - 1) c's for (unsigned int r = 0; r < (2*k - 1); r++) std::cout << c; // print a newline character at the end of each line std::cout << std::endl; } }