Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

nested loops

Status
Not open for further replies.

Guest_imported

New member
Jan 1, 1970
0
0
0
help. i'm taking a c++ course, and i need to do something very simple. i need to write a program that uses nested loops to output this:
1
1 2
1 2 3
1 2 3 4

what i come up w/ is this:
1
2
3
4

so i know i'm using counters properly. but how do i repeat previous results on each line? i would so appreciate any help!

here's what i have so far:

#include <iostream>

int main()
{
int counter;
counter = 1; // Starting position
int nextNumber;

while( counter <= 4 ) // Condition
{
cout << counter << endl;
counter = counter + 1; // Increment variable
}
}


jenny
 
these should do it:

#include <iostream.h>
int main()
{
int counter = 1;
int lines = 4;
int k = 0;

for( int i = 0; i < lines; i++ )
{
for( int k = 1; k <= counter; k++ )
{
cout<<k;
}
cout<<endl;
counter++;
}
return 0;
}
 
you wont need to declare the variable &quot;k&quot; two times like i did,so you can remove the line &quot;int k = 0;&quot;.
 
hi Liebnitz. thanx so much for your help. is there a way to do it that kind of follows the style i was using? this is my first c++ course, and we've never used multiple statements inside of the parentheses w/ a &quot;for&quot; statement.

jenny
 
Ok i see,these should work !

#include <iostream.h>
int main()
{
int counter = 1;
int lines = 4;
int k = 1;
int i = 0;
while( i < lines )
{
i++;
while( k <= counter )
{
cout<<k;
k++;
}
cout<<endl;
counter++;
k = 1;
}
return 0;
}
 
L,
in case you're interested, here's what i did, to make it seem simpler to those of us w/ aching brains.

thanx again!

J

#include <iostream>
int main()

{
int counter = 1;
int lines = 4;

// Outer loop - runs while the old number is less than 4 lines

for( int oldNumber = 0; oldNumber < lines; oldNumber++)
{

// Inner loop - runs while the new number is <= counter

for( int newNumber = 1; newNumber <= counter; newNumber++)
{
cout << &quot; &quot; << newNumber;
}

// End of inner loop

cout << endl;
counter++;

// End of outer loop

}
return 0;
}
 
This was a good idea and the commentaries are well chosen !
 
really? thanx! :) i do whatever i can to SOMEHOW try to grasp this new way of thinking!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top