Simple multidimensional array problem

Hi, I'm new to C++ and have just started using multidimensional arrays. I created a program (following a book) that creates a multidimensional array to lookup a number's square. The program is very short so I have included the full code:

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

#include <iostream>

using namespace std;

int main()
{

	int squares[10][2] = {
	{1,1},
	{2,4},
	{3,9},
	{4,16},
	{5,25},
	{6,36},
	{7,49},
	{8,64},
	{9,81},
	{10,100}
	};

	int choice,i;

	cout << "Enter a number for its square: ";
	cin >> choice;

	for (i=0;i<10;++i) if (squares[i][0] == choice) break;
	cout << "\nThe square of " << squares[i][0] << " is " << squares[i][1];
	cout << "\n";	

	return 0;

}


The program appears to work properly if any of the expected numbers are entered. However, I would expect that if a number was entered that is not in the range 1-10, the program should always give the response for the number 10, since the integer "i" would be equal to 9. What actually happens though is that the program says:

The square of 10 is [value of the number entered]. So, if I enter 71 it says that the square of 10 is 71. I cannot understand how this is happening since the program should just lookup the value in the array. Can anyone help me to understand the problem here?

Thanks a lot.

Your code looks like this:
1
2
3
4
5
   
 for (i=0;i<10;++i)
     if (squares[i][0] == choice) 
      break;//go to next line
 cout << "\nThe square of " << squares[i][0] << " is " << squares[i][1];

You can see that if the square is found - or - if it is not found and the for loop finishes at which time i will be equal to 10
You will always execute cout << "\nThe square of " << squares[i][0] << " is " << squares[i][1]
Thanks for your reply. I understand the problem now. I initially thought that the “i” variable would be equal to 9 at the end of the loop; I didn't realise that it is incremented THEN compared, and so ends at one number higher than the last iteration.

It seems that the integers “i” and “choice” were stored in the two memory locations immediately after the final array element: I mistakenly thought that the 10 was the value from squares[9][0], and not the value of “i” itself. I didn't realise that I had gone past the array's boundaries and was actually referring to the int variables declared later in the program. Adding some pointer variables at the start revealed the three consecutive memory addresses of squares[9][1], “i” and “choice”.

Thanks again for your post.
Topic archived. No new replies allowed.