You are using a version without Ads of this website. Please, consider donating:

### I could use some assistance with "for loops" please.

I have a pretty horrible programming teacher. She doesn't explain much or do any coding with us in class so I'm sorry but I'm not really sure what she's looking for exactly. I'm really struggling to figure this out.

Anyways, she gave us an assignment saying:
1. Write nested C++ for loops that display the output below.

0
0 1
0 1 2
0 1 2 3
0 1 2 3 4
0 1 2 3 4 5

__________________________________________________________________

 ``1234567891011121314151617181920`` ``````#include #include using namespace std; int main() { for ( int i = 0; i < 6; i++ ) { for ( int k = 0; k < 2; k++ ) { cout << (i * k); } cout << endl; } system("PAUSE"); return EXIT_SUCCESS; }``````

Which gives an output of:

00
01
02
03
04
05

Can anyone give me a hand and point me in the right direction?
Last edited on
First you should notice that your output is one line short.

Second what is the purpose of the "magic number" 2 in the following snippet?
` for ( int k = 0; k < 2; k++ )`

Why are you multiplying i * k?

Doesn't your output always start at zero and increment by one each time?
Oh sorry. It does start off with 00. I forgot to add that.
So, when dealing with small loops like this it usually helps to think about every step you want your program to make:

First: you want only one number to be outputted, and you want this number to be a zero:
so starting k = 0 is a good start, because you want to output 0 in the begining each time, but you want to change how many numbers it outputs each time.

so in your inner loop, you want the number that k is less then "<" to change each time.
once everything is said and done, you should have something like this:

 ``123456789`` `````` for ( int i = 0; i <=5; i++ ) { for ( int k = 0; k <= i; k++ ) { cout << k; } cout << endl; } ``````

the "magic number" 2 that jlb was speaking of, is the reason why you are only getting 2 numbers on each of your lines.

and I'm not sure why you were multiplying, but it makes things a lot easier not to do that.

Good Luck
Thank you! I didn't even think to make k equal to i. Wow I feel dumb.
I appreciate that though thank you.
Topic archived. No new replies allowed.