Click here to Skip to main content
15,902,275 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
/*A program to calculate the average of a set of N numbers in C - Langauge*/

C++
#define N 10
int main() 
{
    int count;
    float sum, average, number;
    sum = 0;
    count = 0;
    
    while(count<n)
    {
        scanf("%f", &number);
        sum += number;
        count = 1;
    }
    average = n;
    printf("n="%d", sum);
    printf("average="%f"," average);
    return 0;
}


What I have tried:

please explain this code clearly, my professor explained in class but, not understand.
So, any expert please explain this code very clearly, please...
Thank you...
Posted
Updated 17-Nov-19 0:24am
v2

The best way to understand a short segment of code is to "play computer":

1. Write down the variables used and their initial values (if any)
2. "Execute" each instruction in turn, updating the values of any variables changed
3. Remember to "loop" when you reach the closing bracket of a while / do .. while / for statement

This code is very simple; it should not take you too long to figure it out.

Good luck!
 
Share this answer
 
I'm not going to explain that, because it won't work: it doesn't show you the average of the entered values, even if it compiled, which it won't: C is case sensitive, so "N" is not the same as "n". And if it never gets out of your while loop, that's probably going to be a problem as well ...

An Average is defined - you know this - as the sum of the elements divided by the number of elements. So your code - if fixed - has a loop to collect the elements and add them all together, which produces the sum of the elements.
You know the number of elements - N - so the average is simple to work out: sum / N

Fix the compilation errors, add the actual calculation, and use the debugger to follow the code through and see what exactly is going on when it runs.
 
Share this answer
 
The best is to try the code yourself. Download Visual Studio and create a project and copy that code into it.

This Learn C++ tutorial has also some good chapters about the usage of Visual Studio and its integrated debugger.

Have a lot of fun by reviewing the first code in your career! Good luck! :-)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900