Arrays

im having trouble with arrays. I kniw how to declare them and add them in at one particular time. But i want to know how to enter one at a time. because im making a menu. this is my function at the moment

void runMenu()
{ int option;
do
{
const int NUMELS = 1;
int i, grade[1000];
option=numericalMenu();
switch(option)
{
case 1:
for (i = 0; i < NUMELS; i++)
cout << "enter a grade";
cin>>grade[i];
break;

case 2:
cout <<"all the marks entered are:"<< grade[i]<<endl;
break;

}
}

while (option!=0);
}

the trouble is it declares the number i enter as the whole array
closed account (zb0S216C)
The for loop in case 1 has two statements. However, a for loop without braces must only have one statement. Placing braces around the for loop may help you.

1
2
3
4
5
6
7
8
9
// ...
case 1:
    for (i = 0; i < NUMELS; i++)
    {
        cout << "enter a grade";
        cin>>grade[i];
    }
    break;
// ... 


Wazzak
Last edited on
grade[i] refers to the ith element of the grade array (ie, a single element, not the whole array).
You have several problems here.

#1:

1
2
3
4
5
case 1:
    for (i = 0; i < NUMELS; i++)
        cout << "enter a grade";
    cin>>grade[i];
    break;


Note that since you don't have any braces in that for statement, the cin line is not part of the loop. This code will simply print "enter a grade" NUMELS number of times, then actually get input from the user only once.

If you the user to enter several grades, you'll need to put that cin >> grade[i]; line as part of the loop.


#2:
1
2
3
const int NUMELS = 1;
//...
for (i = 0; i < NUMELS; i++)


NUMELS is 1, so you're only looping once. If you want to loop more times, you'll need to increase NUMELS.


#3:
1
2
3
case 2:
cout <<"all the marks entered are:"<< grade[i]<<endl;
break;


What is i? Which grade are you trying to print?

If you want to print all the grades, you'll need to loop. grade[i] only gives you a single grade from the array, it does not give you all grades.

Last edited on
Topic archived. No new replies allowed.