Nested While Loops

I have a program here:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
//David Scheip
//Created 4.27.13
//Page 523 Number 3
//Use a nested for loop to  print array a[3][2] and a nested while loop to print array b[2][3]
//defined here and print both in matrix form:
//int a[3][2] = {11,22,33,44,55,66}; b[2][3] = {111,222,333,444,555,666}

#include <iostream>

using namespace std;

int main()
{
	int a[3][2] = {11,22,33,44,55,66},
		b[2][3] = {111,222,333,444,555,666},
		i, j, l;
	int k = 0;

	for (i=0; i<3; i++)
		{
		for (j=0; j<2; j++)
			{
				cout << a[i][j] << "  ";
			}
		cout << endl;
		}

	while(k <=2)
	{
		l=0;
			while(l <=3)
			{
				cout << b[k][l] << "   ";
				++l;
			}
		++k;
		cout << endl;
	}


	cin.get();
}

My problem is with the nested while loop. I can get the loop to output the data correctly (in matrix format) but there is a lot of extra garbage. I'm not exactly sure where it's coming from.

I'm not looking for the answer, but more a point in the right direction.

So my understanding of the code is: while k <2 and l <3 i am incrementing both and passing them to the array b[k][l]. This should then print to the console the value for the array (ie b[0][0] = 111).

The program runs, and outputs the 6 values as intended, but with the addition of an additional 444 and -858993460 (which I understand to be just 'garbage').

Any help would be great, I am sure it's a simple, "I've been staring at this to long", error I am missing.

Thanks,

David
Look at your conditions for both of your while loops:
1
2
while(k <= 2)
while(l <= 3)


The loop will run an iteration when k == 2 and l == 3. This means that the program will attempt to access b[2][l] and b[2][3]. These indices are out of bounds. Hence, the garbage.

Remember that array indices range from 0 to n-1, so if the array size is 3, you should only iterate from 0 to 2 and so forth.
while(k <=2)
suppose that k is 2, the loop executes, but k is out of bounds.
Thank you both... I can't believe I did that!! I was staring at this for like 2 hours and couldn't figure out what was wrong.

Thank you very much!!

David
Topic archived. No new replies allowed.