C++/c++
Expert: Zlatko - 1/9/2010
Questionwrite a program in c++ to get the following structure:
* * * * *
* * * *
* * *
* *
*
* *
* * *
* * * *
* * * * *
AnswerHello Anusree.
To solve this puzzle, you should break it down into three pieces or functions. Many times solving a problem becomes easier if you break it down into simpler problems. Here you need to print many lines, so one function you need is to print a line of stars. The function can be made flexible by passing to it the number of stars to print.
#include <iostream>
#define MAX_LINE_LEN 5
void printLine(int count)
{
printSpace(count);
for(int star = 0; star < count; ++star) std::cout << "* ";
std::cout << std::endl;
}
You see that you also need a function to print a certain number of spaces before the first star when the count parameter is less than the maximum line length. I will leave the printSpace that as an exercise for you.
The third function you need is the main program which calls printLine. Again, you can break the problem down into two smaller problems. The first subproblem is to print the top half of the structure. The second subproblem is to print the bottom half.
Here is part of the main function. You can finish it based on my example.
int main(void)
{
// Print the top half of the structure
for(int line = MAX_LINE_LEN; line > 0; --line) printLine(line);
// TODO finish
}
I hope that helps you out.
Best regards
Zlatko