C++/c++

Advertisement


Question
write a program in c++ to get the following structure:

* * * * *
* * * *
 * * *
  * *
   *
  * *
 * * *
* * * *
* * * * *

Answer
Hello 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

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Zlatko

Expertise

No longer taking questions.

Experience

No longer taking questions.

Education/Credentials
No longer taking questions.

©2012 About.com, a part of The New York Times Company. All rights reserved.