Question about for loop.

Ok so my class is being taught experimentally where my class is group work, and the other class regular lectures. The program at hand is going to accept as input the names of students. Then the grades of students. Then calculate the average grade. I need help setting my loop to only ask for grades 10 times. What exactly is the syntax here? The program isn't finished yet.

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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include <iostream>
 
 
using namespace std;
 
void instructions()
{
cout<<"Instructions here."<<endl;
}
string studentsName()
 
{
 
string name;
cout<<"Enter the first name or type done"<<endl;
while
( name!= "done.")
 
{
cout<<"Enter next Name or enter done."<<endl;
getline(cin,name);}
return name;
}
 
double tenscores()
{
double sum;
double testScores;
sum=0;
 
for (sum=10000;testScores=0; testScores++){
cout<<"Enters test scores"<<endl;
cin >> testScores;
sum=0+testScores;
}
return sum;
}
double average(double scores)
{
double tscore;
tscore=tenscores()/10.0;
double average(double scores)
{
double tscore;
tscore=tenscores()/10.0;
return tscore;
}
int main()
{
double scores;
string sName;
instructions();
sName= studentsName();
tenscores();
scores=average(scores);
return 0;
} 
You can use

1
2
3
4
5
for(int i=0;i<10;i++){
   //input
   //count the sum
}
//find average 

Or
1
2
3
4
5
6
7
   int i=0;
   while(i<10){
   //input
   //count the sum
   i++
}
//find average 

Or
1
2
3
4
5
6
7
   int i=0;
   do{
   //input
   //count the sum
   i++
}while(i<9);
//find average 
Thanks. I'm going to try this. I'm confused about i though. is i just a loop counter? Does that variable need to be returned? Ugh so confused. THis class is being taught differently and while I have some experience with Java i'm finding c++ kind of strange.
is i just a loop counter?

Yes.

Does that variable need to be returned?

No.

31
32
33
34
35
for (sum=10000;testScores=0; testScores++)
{  cout<<"Enters test scores"<<endl;
    cin >> testScores;
    sum=0+testScores;
}


The first term of the for statement initializes the loop counter, in this case you're setting sum to 10000. The second term of the for statement is the continuation condition. The loop will continue as long as the condition is true. In this case, you will assign 0 to testScores, then test if that is true (0 is false), so it will terminate the loop. You never get to the third term of the for statement which is the step. You don't want to increment testScores.

Lendradwi showed you the three loop forms. The for loop is most commonly used when you want to execute the loop a fixed number of times.

1
2
3
4
5
6
  sum = 0;
  for (int i=0; i<10; i++)
  {  cout<<"Enters test score"<<endl;
      cin >> testScore;
      sum += testScore;
  }

Last edited on
Topic archived. No new replies allowed.