c++ Arrays

Hi, I've read over the lessons for arrays and I can't figure out how to use arrays in math problems. The example I was given uses the array in math with a for loop, but I want to uses the arrays in just basic math statements.

Thanks for the answers. whOOper.
Arrays are just groups of variables. For example if you have 3 things you need to keep track of, you could either store them individually as 3 variables:

1
2
3
4
5
6
int var0;
int var1;
int var2;
...
if(var1 == 15)
  var1 = 10;


Or you could group them together as an array:
1
2
3
4
int var[3];
...
if(var[1] == 15)
  var[1] = 10;


The above two code snippits pretty much do exactly the same thing. The advantage to using arrays is that you can use an "index" to select a specific variable. Like say you get the input from the user:

1
2
3
int which;
cout << "Input which var you would like to see (0-2): "
cin >> which;  // assume user inputs 0,1, or 2 


to print the appropriate variable if they're all defined seperately is a chore, and would require a large if/else chain or a switch statement:

1
2
3
4
5
6
7
8
9
10
11
12
     if(which == 0)   cout << var0;
else if(which == 1) cout << var1;
else if(which == 2) cout << var2;  // blech!

// or

switch(which)
{
case 0:  cout << var0; break;
case 1:  cout << var1; break;
case 2:  cout << var2; break;  // also blech!
}


However, using an array, you can simply use the variable as an "index" to select the appropriate variable:

 
cout << var[which];
Ok that clarified it a little bit, but could you give an example with an array in a math operation and thanks for the answer.
I did, well, maybe not a mathmatical operation, but I showed several statements using an array (comparison, assignment, output with cout)

But okay:

1
2
3
4
5
6
7
int numbers[3];   // make an array with 3 elements

numbers[0] = 5;  // set the first two elements to 5 and 6, respectively
numbers[1] = 6;

// sum the first two elements, store result in the last element
numbers[2] = numbers[0] + numbers[1];


That's not a very practical thing to do, of course.

Anyway the index of the variable you want to use goes in the brakets. That's all there is to it.
Thank you for clearing that up for me that really helped.
Topic archived. No new replies allowed.