For my CE 21 class. The problem discussed earlier was, draw a triangle of stars given the length for a side of the triangle n. It can be illustrated as follows for n = 3.
* * * * * *
The next task is to center the triangle:
* * * * * *
Then we want to be able to print a diamond
* * * * * * * * *
This C++ code is one of the solutions to the problem:
#include <iostream> int main() { int n; std::cin >> n; int i = 1; // upper triangle while( i <= n ) { int space = n - i; for(int j = 1 ; j <= space ; j++ ) { std::cout << " "; } int j = 1; while( j <= i ) { std::cout << "* "; j++; } std::cout << std::endl; i++; } // lower triangle i = n - 1; while( i >= 1 ) { int space = n - i; for(int j = 1 ; j <= space ; j++ ) { std::cout << " "; } int j = 1; while( j <= i ) { std::cout << "* "; j++; } std::cout << std::endl; i--; } return 0;}
For the homework, answer the Challenge section of the lecture slides on iterations:
- Draw a pine tree with 3 sections
- Each section should have n lines of stars
- The start of the next section should have one less star than the end of the previous section
- Add n lines of single asterisks for a stand
Example for n = 3:
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Technorati Tags: ce21, c++, programming, loops, iterations


Add New Comment
Thanks. Your comment is awaiting approval by a moderator.
Do you already have an account? Log in and claim this comment.
Add New Comment