Array Indexing Question

Hello,

I am very new to C++ and have started to teach myself from a book; which I am enjoying mostly.
Ok to start of this program(below) was inside my C++ book and I've been reading this topic for a while now and I don't understand the array indexing bit like why you have to have a for loop each time for a array, as this is what I understand from my C++ book.

Also, I don't understand when numbers[i] is assigned like that with "i" does that just mean so "numbers" has somewhere to be stored in the memory? So to sum up my question: how does the indexing work in this program as I don't understand it and why you have a for loop; and why "i" is assigned to "numbers" like that; also I don't understand this if statement:
1
2
3
4
if(!strcmp(str, numbers[i])) {
			cout << "Number is " << numbers[i+1] << "\n\n";
			break;
}

Here is the whole program if that helps:

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
 #include <iostream>
#include <cstdio>
using namespace std;

int main() {

	int i;
	char str[80];
	char numbers[10][80] = {
		"Tom", "555-3322",
		"Mary", "555-8976",
		"Jon", "555-1037",
		"Rachel", "555-8873",
		 "Sherry", "555-8873"
	};
	cout << "Enter a number: ";
	cin >> str;

	for(i=0; i< 10; i +=2)
		if(!strcmp(str, numbers[i])) {
			cout << "Number is " << numbers[i+1] << "\n\n";
			break;
		}
		if(i==10) cout << "Not found.\n\n";

		return 0;
}



Thank you for your time and effort.

Last edited on
Arrays are just a group of variables that are accessed through the same name.

This example is a little confusing because you actually have a 2D array of chars instead of a 1D array of strings which would be simpler and easier for a beginner to understand.... (but you can ignore me here... I have beef with the way a lot of C++ books are written and/or how the language is taught in general).


So I'm going to use a slightly different example that might be easier for you to understand:

1
2
3
4
5
6
7
8
int array[5] = { 6, 10, 15, 1, 30 };

cout << "index 2 is " << array[2] << endl;

for(int j = 0; j < 5; ++j)
{
    cout << array[j] << endl;
}
outputs:

index 2 is 15
6
10
15
1
30



In this example we have an array of ints. The array is of size '5' as illustrated by the number in the brackets:

 
int array[   5  ] = ...


This means we actually have 5 different ints. Each int is considered an "element" of the array.

You can treat these elements just as you would if they were 5 individual variables. The way you choose which of the 5 vars you want to access is you specify an "index". Indexes start at 0 and count up... so array[0] would be the first element in the array, array[1] would be the one after that... etc etc... up until array[4] which is the last element in the array.

Therefore this line:
 
cout << "index 2 is " << array[2] << endl;


Prints "index 2 is 15" because it's accessing the 'index 2' element in the array... which was 15.


but we don't need to use a fixed value for that. Saying array[2] is fine.. but we can also use another variable to index the array. Which is what is done in the following for loop:

 
for(int j = 0; j < 5; ++j)


Let's start with how this for loop actually works. 'j' will start at 0, the loop body will run, then it will be incremented to 1, then the loop body runs again, etc, etc until j < 5 becomes false. This means the body of the loop will run exactly 5 times:

once when j==0
once when j==1
once when j==2
once when j==3
once when j==4


Since j is different each time the loop body is run... we can use it as an index to our array to print each element:

1
2
3
{
    cout << array[j] << endl;
}


The first time this loop body runs... j==0, so this will print array[0]... which is 6.

The next time, j==1, so this will print array[1]... which is 10.

etc
etc
Wow, I wish I had you as a teacher much easier than my book.

Thanks, I understand what the for loop does now, all down to you!

If you wouldn't mind could you explain this if statement to me:
1
2
3
4
if(!strcmp(str, numbers[i])) {
			cout << "Number is " << numbers[i+1] << "\n\n";
			break;
		}


So does the if compare the number array until it say it gets to "Tom and then display that array string and what does the numbers[i+1] mean?


cheers for helping me out#
Luke.
There are 2 things that should be explained before we look at that code.

#1: The 'numbers' array actually contains 2 different kinds of info: 1 = the person's name, and 2 = the person's number.

The person's name is in even elements, with their number being in the odd elements. IE... array[0] is someone's name... and array [1] is their number. array[2] is the next person's name, and array[3] is their number. Etc.

Note... in real world situations you'd never do this, but rather would use a data structure. Which makes this a really bad example. I can only assume that the book did not get to structs yet.


#2: The loop counter 'i' actually increases by 2 each time it loops. This is because the loop is not doing ++i but instead is doing i += 2

So the loop will not run 10 times... it will only run 5 times:
i = 0
i = 2
i = 4
i = 6
i = 8




Notice how 'i' will always be even.... so using 'i' as an index will get you someone's name.

'i+1' will be odd... so using 'i+1' as an index will get you someone's number.

And that's exactly what the for loop is doing here:

 
if(!strcmp(str, numbers[i])) {

This compares the given 'str' string to 'numbers[i]'. Since 'i' is even, this is comparing it to someone's name.

(again this would be much easier with strings instead of char arrays... but whatever... this book's example is nuts... I should stop ranting about it)

So if the given 'str' matches this person's name... it executes the body of that if block:

1
2
3
			cout << "Number is " << numbers[i+1] << "\n\n";
			break;
		}


Which prints 'numbers[i+1]'. Again since 'i' is even... 'i+1' will be odd... which means it will print that person's number.
Last edited on
I just want to add this for the future, as I have been confused by it in my self-taught experiences...

There is a general format for a for loop, and it goes like this:

for( [variable initialization]; [condition in which not to break the loop]; [any post actions])

So, the variable doesn't have to be an integer, and the post-action doesn't have to be the addition of 1 to that integer.

1
2
for(unsigned int x = 0; x < 5; x++) //will loop 5 times, probably the only thing you need
//to worry about right now. 

will add 1 to x after every loop.

I just thought I would let you know, as I have a couple of C++ textbooks that seem to stray from the code above. I know I would have been confused if I saw some of the things in there.
Wow, thanks guys; you've really helped me out.

Man! My book is so confusing, when I brought it from Amazon I didn't really know which one to buy mean its been ok but just not very good on the explaining side of things.

Thank you Disch; you are a star!
Cheers for letting me know about them for loops IwishIknew, thank you.


Wish you were my teacher ;)

When I get confused about arrays of this topic ill read this post again.

My book was: C++ A beginner's guide second edition by Herbert Schildt.
cout << "Is that book any good?";

haha.
Thanks again guys! Fab job on explaining.
Schildt is notorious for bad books. He's known for being riddled with errors and incorrect information.

A running gag is that you can pick any page at random from the book and there'll be at least 1 error. Here's a page which mocks him:

http://www.seebs.net/c/c_tcn4e.html


Personally I haven't read any of his books. But if he's explaining arrays to beginners by using 2D arrays and putting two different types of data in the same array, then my gut instinct tells me the book probably isn't great.
So I've got a terrible book then. Dam it.

Well yeah I agree you; with the explaining is not up to standard for beginner's.

I might as well finish this book, its something like 542 pages and I'm page 146; then I will continue onto a better one.

Thanks for the help Disch.
Last edited on
Topic archived. No new replies allowed.