Begginer In c++

Can someone please explain why this code is not working i am new to programming so any tips would be appreciated. I am trying to copy the numbers that exceed the average and put them in a new array in order, but when i run this program the only number that gets copied is 10. I ran the program with these numbers. grades={1,2,3,4,5,6,7,8,9,10} and the average(mo) is 5.5.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
using namespace std;

void copygrades(double grades[],int size, double bestgrades[],double mo){
    int a=0;
    for (int i=0; i<size; i++)
        if (grades[i]>mo)
            bestgrades[a]=grades[i];
            a=a+1;
            
    
}
int main(){
double grades[1000], bestgrades[1000];
  copygrades(grades,10,bestgrades,5.5);
  print(bestgrades,10);
}
  
Indentation is very good to use and necessary for human readability, but it's purely aesthetic to the compiler syntax. To have multiple statements in an if statement or for loop, you need to enclose the blocks with { and }.

1
2
3
4
5
6
7
8
9
    int a=0;
    for (int i=0; i<size; i++)
    {
        if (grades[i]>mo)
        {
            bestgrades[a]=grades[i];
            a=a+1;
        }
    }


I assume you omitted the initialization part of your code for brevity, because right now your code is using uninitialized values in grades.
Last edited on
@george42550,

If you are going to post code, please ensure that it is complete and compileable.

It won't compile as-is, and there is no way of putting any grades in to test it.

For constructs like for-loops and if-blocks you would be well advised to delimit them with curly braces { }. C++ isn't like python: indentation is certainly helpful and highly-recommended, but on its own it won't delimit blocks.

Your current for-loop ends at the end of line 8, and it repeatedly puts grades into bestgrades[0]. At the end, with your given example, 6, 7, 8, 9 and 10 will have gone successively into the same location.

I suspect that you meant
1
2
3
4
5
6
7
8
9
10
11
12
void copygrades(double grades[],int size, double bestgrades[],double mo)
{
    int a=0;
    for (int i=0; i<size; i++)
    {
        if (grades[i]>mo)
        {
            bestgrades[a]=grades[i];
            a=a+1;
        }
    }
}


Last edited on
What happens when a control statement lacks braces? For example the if() statement on line 7 lacks braces how many lines are considered to be part of that if() statement's body?

Thanks a lot now i understand why it didn't work have a good day!!!!
Topic archived. No new replies allowed.