C++ (Using for loop)



#include <iostream>
using namespace std;

int main()

{
char asterisk = '*';



for (int no = 7 ; no >0 ; no--)
{

if (no ==7)
cout << "1" ;

else if (no==6)
cout << "12";

else if (no==5)
cout << "123";

else if (no==4)
cout << "1234";
else if (no==3)
cout << "12345";

else if (no==2)
cout << "123456";
else if (no==1)
{
cout << "1234567\n\n";
break;
}

for ( int count = no-1 ; count > 0 ; count --)

{

cout << asterisk ;


}

cout << endl << endl;
}


}

My question is im able to print the output of asterisk in a decreasing pyramid order but when it comes to print the number of 1 to 7 part by part im using the if else statement, so do you have any suggestion to help me to print the number by using loop ?


1******
12*****
123****
1234***
12345**
123456*
1234567
I'd try thinking of this as a square with 7 rows and 7 columns. Then find the relationship between the row number and column number in terms of what is being output.

e.g. if the row is 1, you output a digit in one column and * in the remaining columns. if the row is 7, you output a digit in 7 columns and no *.

So you can use a format like this with whatever conditions and output will produce the character display you want.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>

int main()

{
    for (int row = 1; row <=7; row++)
    {
        for (int col = 1; col <=7; col++)
        {
            if //some condition
                //output this
            else
                //output this
        }
        std::cout << std::endl;
    }
    return 0;
}


and this could be generalized to accept any number, not just 7.
HI wildblue thanks anyway , besides i just figure out a better way to produce the output


#include<iostream>
using namespace std;


int main()
{
for(int row=1; row<=7; row++)
{
for(int column=1,j=1; column<=row; column++)
{
cout<<j;
j++;
}

for(int asterisk=6; asterisk>=row; asterisk--)
cout<<"*";
cout<<endl<<endl;
}
return 0;
}
Last edited on
Glad you got it working. You don't really need to add an extra variable j, but it works.
Thanks man once again :D
Topic archived. No new replies allowed.