so i want a output like this, example input = 4
*
** **
*** *** ***
**** **** **** ****
its repeating the same with the patern ( row and colomn)
i already make the program, but i dont know how to show only the last colomn, until all colomn shown
this is the program i made
#include <iostream>
using namespace std;
int main() {
int x;
int repeat = 0;
cin >> x;
do {
for (int b = 0; b <= x; b )
{
for (int c = b; c <= x; c )
{
cout << " ";
}
for (int c = 0; c < b; c )
{
cout << "*";
}
cout << endl;
}
repeat;
} while (repeat != x);
return 0;
}
CodePudding user response:
I suppose the exercise has two goals. It tries to teach you how to break down a task into smaller ones, and it asks you to print some *
and spaces. I'll help you with the first but at least leave the lattter for you.
There is not only one way to divide a bigger problem into smaller ones. I will do the following: You want to print columns and rows made up of some pieces.
columns ->
* rows
** ** |
*** *** *** v
**** **** **** ****
^--^ one piece
The main
part can look like this:
#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>
std::string get_piece(int row, int col,int width);
int main() {
int x = 4;
for (int row=0; row < x; row){
for (int col = 0; col < x ; col){
std::cout << get_piece(row,col,x) << " ";
}
std::cout << "\n";
}
}
It prints x
rows each with x
columns. Now you just need to figure out the pieces. This is something to get started (it uses std::setw
and std::setfill
):
std::string get_piece(int row, int col,int width){
std::stringstream ss;
ss << std::setw(width) << std::setfill('x') << row << col;
// ^^ this is actually flawed, but you wont notice unless row or col are >9
return ss.str();
}
It produces the following output:
xxx00 xxx01 xxx02 xxx03
xxx10 xxx11 xxx12 xxx13
xxx20 xxx21 xxx22 xxx23
xxx30 xxx31 xxx32 xxx33
A completely different pattern you get with this implementation (this time using std::string
constructor that takes a character and the number to repeat that character):
std::string get_piece(int row, int col,int width){
int num_stars = (row col)/2;
return std::string(num_stars,' ') std::string(width-num_stars,'*');
}
It results in:
**** **** *** ***
**** *** *** **
*** *** ** **
*** ** ** *
Now you just have to figure out how the pieces have to look like depending on row
, col
and width
.
CodePudding user response:
One way to do it would be to actually do it in reverse. Create this:
*
**
...
**** **** **** ****
and space-fill each line so that all your lines are the same length. But instead of printing each line from 0 to n, print them from n to zero. That is, you don't actually PRINT them that way -- you just build an array of strings, but then print the strings in reverse order.
The other choice is ahead of most of your current code, for each line, determine how many groups of stars shouldn't exist yet and then space-fill at the front. That would retain most of your existing code as it is.