• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

SOMEONE please help me with this c++ program

Raj

Senior member
this is what i am trying to do.

take any number x. and output the following up to x numbers

1
--2
----3
------4
--------5
------4
----3
--2
1



i split it in to two for loops from the top to the 5

#include <iostream>
#include <iomanip>

int input;
cout <<&quot;please input value to be calculated; &quot; <<endl;
cin >>input:


for (int i = 1; i <= input; i++)
{
cout <<i <<endl;
for (int j = 1; j <= i; j++)
cout <<setw(3 * j);
}


this displays

1
--2
----3
------4
--------5

but, can't figure out how to display


------4
----3
--2
1


please help
 

int snum = 5; // start number
int dir = 1;
for(int count = 1; count >= -1; count -= 2)
{
for(int i=dir; i<=snum &amp;&amp; i >=1; i+=count)
{
for(int j=1; j<i; j++)
cout << &quot;.&quot;;
cout << i << endl;
}
dir = i-2;
}


edit...a little explenation:

the first for loop for(int count = 1; count >= -1; count -= 2) indicates the direction of counting. first snum iterations will be done in positive direction and when the inner loops are done count will go negative and we will count down to 1. for(int i=dir; i<=snum &amp;&amp; i >=1; i+=count) loop starts at at 1 and than again at snum - 1 dir = i-2;. So initially this loop will count up to snum and than we will reverse the count down (thats why condition i<=snum &amp;&amp; i >=1 is applied to catch limits on both ends;
 
for (i = input - 1; i <= 1; i--) {
for (j = i; j <= 1; j--)
cout << setw(3 * j);
cout << i << endl;
}

This should work, just decrement yourself back through the loop and change the position of your output line.
 
edit...

here's an elegant one loop solution

int dir = 1;
int start = 1;
for(int i = start; i <= input &amp;&amp; i >= 1; i+=dir)
{
cout <<setw(3 * (i-1)) << i <<endl;
if(i == input) // reverse and count down
{
dir = -1;
start = input;
}
}


hehe, damn it's early....
i thought these...

1
--2
----3

were . (periods) and you wanted the output to look like this

1
.2
..3
...4
..3
.2
1

maybe i should think about getting me some glasses 🙂
 
Back
Top