| | |
Average and sum with array
Please support our C++ advertiser: Intel Parallel Studio Home
Thread Solved |
•
•
Join Date: Aug 2008
Posts: 17
Reputation:
Solved Threads: 0
Trying to make a program that where user inputs 10 numbers (no negative numbers) and then displays the sum and average. I get a error if I don't have ; after else statement, before sum = 0. I get a warning of coversion from int to float, and warning of A is unreferenced local variable. Also not sure if indentation is right or where to find rules for how to indent. Here is my code. Please help
C++ Syntax (Toggle Plain Text)
#include <iostream> #include <cmath> using namespace std; const int MAX = 10; //Main Module int main() { int A[MAX] ; // declare the size of the array int sum ; // declare sum as integer float mean ; // declare average as a float int i; // declare i as integer int number; // declare number as integer cout << "This program computes the average of 10 numbers"; cout << endl ; //create for loop for (i = 0; i < MAX; i++) { cout << "Enter a positive number" << i << ":" ; cin >> number; // while else statement (INSIDE the loop) to calculate for user error if (number >= 0) cout << "Invalid Entry! Enter a number greater than or equal to zero." ; else (number < 0) sum= 0; sum = sum + number; i++; } mean = 1 * sum / 10; cout << "The sum is: " << sum << endl ; cout << "The average is: " << mean << endl ; return (0); // terminate with success }
Last edited by Tekmaven; Aug 15th, 2008 at 2:48 pm. Reason: Code tags
>I get a error if I don't have ; after else statement, before sum = 0
The else statement doesn't have a condition; the condition is implied by the accompanying if and else if clauses:
>I get a warning of coversion from int to float
If all of the operands in an expression are int, then the result will be int and any precision is lost. If you want both the float type and an accurate value for the type, change one or more of the operands to float:
>warning of A is unreferenced local variable
You declare A but never use it, that's easy.
>Also not sure if indentation is right or where to find rules for how to indent.
You need to use code tags to keep the indentation in a post.
else (number < 0) C++ Syntax (Toggle Plain Text)
if (number >= 0) cout << "Invalid Entry! Enter a number greater than or equal to zero." ; else sum = 0;
If all of the operands in an expression are int, then the result will be int and any precision is lost. If you want both the float type and an accurate value for the type, change one or more of the operands to float:
C++ Syntax (Toggle Plain Text)
mean = 1.0f * sum / 10.0f;
You declare A but never use it, that's easy.

>Also not sure if indentation is right or where to find rules for how to indent.
You need to use code tags to keep the indentation in a post.
Last edited by Radical Edward; Aug 15th, 2008 at 12:19 pm.
If at first you don't succeed, keep on sucking until you do succeed.
•
•
Join Date: Jun 2008
Posts: 86
Reputation:
Solved Threads: 5
hmmm...lemme analyze this abit:
hmmmm you seem to have programmed in some other language before...
your while else statement is abit bugged, you gotta switch the arguments...bah, i'll just re-code all...
C++ Syntax (Toggle Plain Text)
#include <iostream> #include <cmath> using namespace std; const int MAX = 10 + 1; //let it have more space //Main Module int main() { int A[MAX] ; // declare the size of the array int sum ; // declare sum as integer float mean ; // declare average as a float int i; // declare i as integer int number; // declare number as integer cout << "This program computes the average of 10 numbers"; cout << endl ; //create for loop for (i = 0; i < MAX; i++) { cout << "Enter a positive number" << i << ":" ; cin >> number; // while else statement (INSIDE the loop) to calculate for user error if (number >= 0) // this here says: if the number is greater than or equal to zero it's invalid cout << "Invalid Entry! Enter a number greater than or equal to zero." ; else (number < 0) // dunno what you're trying to do here sum= 0; // this will set your sum to 0 each and every time..so you'll never sum all the numbers sum = sum + number; //sum should be initialized at the start i++; } mean = 1 * sum / 10; cout << "The sum is: " << sum << endl ; cout << "The average is: " << mean << endl ; return (0); // terminate with success }
your while else statement is abit bugged, you gotta switch the arguments...bah, i'll just re-code all...
•
•
Join Date: Jun 2008
Posts: 86
Reputation:
Solved Threads: 5
here...this should work...
C++ Syntax (Toggle Plain Text)
#include <iostream> using namespace std; int number, sum = 0; int main( void ) { cout << "This program computes the average of 10 numbers" << endl; // you can put the endl right away or use "\n" for( int i = 0; i < 10; ++i ) { cout << "Enter a positive number" << i << ": "; cin >> number; if( number < 0 ) cout << "Invalid Entry! Enter a number greater than or equal to zero." ; else ( number >= 0 ); sum += number; } float mean = 1. * sum/10.; cout << "The sum is: " << sum << endl ; cout << "The average is: " << mean << endl ; scanf( "\n" ); return 0; }
Last edited by gregorynoob; Aug 15th, 2008 at 12:34 pm.
•
•
Join Date: Aug 2008
Posts: 17
Reputation:
Solved Threads: 0
Thanks for the quick response. I've made changes to the code. Not sure where to use A, thinking it should go somewhere in the else statement (as part of sum)? If I try to run program it only lets me enter 5 numbers not 10.
C++ Syntax (Toggle Plain Text)
#include <iostream> #include <cmath> using namespace std; const int MAX = 10; //Main Module int main() { int A[MAX] ; // declare the size of the array int sum ; // declare sum as integer float mean ; // declare average as a float int i; // declare i as integer int number; // declare number as integer cout << "This program computes the average of 10 numbers"; cout << endl ; //create for loop for (i = 0; i < MAX; i++) { cout << "Enter a positive number" << i << ":" ; cin >> number; // while else statement (INSIDE the loop) to calculate for user error if (number < 0) cout << "Invalid Entry! Enter a number greater than or equal to zero." ; else sum= 0; sum = sum + number; i++; } mean = 1.0f * sum / 10.0f; cout << "The sum is: " << sum << endl ; cout << "The average is: " << mean << endl ; return (0); // terminate with success }
If you don't mind Edward giving some constructive criticism, read on. 
The effect of using namespace std; is limited to the scope that you do it in. If you do it in main, it only has an effect in main. If you do it in a namespace, it only has an effect in that namespace. If you do it in the global scope, it has an effect everywhere, even if you don't want it to.
Global variables are the same way. They can be seen and used everywhere, and that makes keeping track of them harder. Even if you only use them in small programs like this one, it's still better to keep to the habit of limiting variable scope as much as possible.
There's more to it. endl automatically flushes the stream each time you use it and '\n' or "\n" doesn't. If you don't need the stream flushed, don't bother with endl. In fact, Ed's experience is that most of the time you don't need the stream flushed because a required flush usually happens automatically with tied input streams, the unbuffered effect of "real-time" streams, or the natural lifetime of your stream object.
So Ed's recommendation is to always use '\n' or "\n" instead of endl, and flush if it turns out that you find one of the rare situations where it's needed.
This line doesn't do anything. In the else body, number is compared with 0 and the result is thrown away. The parentheses are the confusing factor because else doesn't have a condition, but any expression can be surrounded in parentheses. This is what actually happens:
>float mean = 1. * sum/10.;
This won't make the warning go away because floating point constants have a type of double, not float. To make it a float you need to add an f or F suffix or cast the value to float:
scanf is declared in <cstdio> or <stdio.h>. It's also a varargs function which means that if you don't provide a prototype the behavior is undefined. Be sure to include either of those headers to fix the problem.
Edward would also suggest that this line is confusing because the behavior is unconventional. If you type any whitespace and/or press enter, nothing happens. If you type anything except whitespace and then press enter, the program ends, but only after that combination. The two most common keys typed when someone says "press any key" are the space bar and the enter key, so users would be stumped by how

// This should never be in the global scope using namespace std; // Global variables should be avoided when possible int number, sum = 0;
Global variables are the same way. They can be seen and used everywhere, and that makes keeping track of them harder. Even if you only use them in small programs like this one, it's still better to keep to the habit of limiting variable scope as much as possible.
C++ Syntax (Toggle Plain Text)
// you can put the endl right away or use "\n"
So Ed's recommendation is to always use '\n' or "\n" instead of endl, and flush if it turns out that you find one of the rare situations where it's needed.

C++ Syntax (Toggle Plain Text)
else ( number >= 0 );
C++ Syntax (Toggle Plain Text)
if (number < 0) { cout << "..."; } else { (number >= 0); // No effect } sum += number;
This won't make the warning go away because floating point constants have a type of double, not float. To make it a float you need to add an f or F suffix or cast the value to float:
C++ Syntax (Toggle Plain Text)
float mean = 1.f * sum/10.f; // or float mean = float(1.) * sum/float(10.);
C++ Syntax (Toggle Plain Text)
scanf( "\n" );
Edward would also suggest that this line is confusing because the behavior is unconventional. If you type any whitespace and/or press enter, nothing happens. If you type anything except whitespace and then press enter, the program ends, but only after that combination. The two most common keys typed when someone says "press any key" are the space bar and the enter key, so users would be stumped by how
scanf("\n") works.
If at first you don't succeed, keep on sucking until you do succeed.
•
•
Join Date: Aug 2008
Posts: 17
Reputation:
Solved Threads: 0
not sure what you mean with global scope. I can now enter all numbers but having trouble with the sum part
#include <iostream>
#include <cmath>
using namespace std;
const int MAX = 10;
//Main Module
int main()
{
int A[MAX] ; // declare the size of the array
int sum ; // declare sum as integer
float mean ; // declare average as a float
int i; // declare i as integer
int number; // declare number as integer
cout << "This program computes the average of 10 numbers";
cout << endl ;
//create for loop
for (i = 0; i < MAX; i++)
{
cout << "Enter a positive number" << i << ":" ;
cin >> number;
// while else statement (INSIDE the loop) to calculate for user error
if (number < 0)
cout << "Invalid Entry! Enter a number greater than or equal to zero." ;
else
sum = 0;
sum = sum + A[number];[/ COLOR]}
mean = 1.0f * sum / 10.0f;
cout << "The sum is: " << sum << endl ;
cout << "The average is: " << mean << endl ;
return (0); // terminate with success
} Last edited by cicigirl04; Aug 15th, 2008 at 1:54 pm.
•
•
Join Date: Jul 2005
Posts: 1,753
Reputation:
Solved Threads: 283
This: is equivalent to this:
meaning sum is set to zero everytime through the loop and then a junk value, called A[number] is added to it, so it is still junk, unless the value of number is above 9 in which case your program will (hopefully) crash, since you are accessing memory you don't have control over.
Lesson #1: use curly brackets appropriately.
Lesson #2: always initialize variables
Lesson #3: always be aware of the valid range for indexes of the array.
If you are going to do the sumation on data entry then get rid of A. Otherwise do this program in three steps.
1) obtain values for A using loop #1
2) after loop #1 is done sum the values in A using loop #2
3) calculate the mean after both loops are done.
C++ Syntax (Toggle Plain Text)
else sum = 0; sum = sum + A[number];}
C++ Syntax (Toggle Plain Text)
else { sum = 0; } sum = sum + A[number];}
meaning sum is set to zero everytime through the loop and then a junk value, called A[number] is added to it, so it is still junk, unless the value of number is above 9 in which case your program will (hopefully) crash, since you are accessing memory you don't have control over.
Lesson #1: use curly brackets appropriately.
Lesson #2: always initialize variables
Lesson #3: always be aware of the valid range for indexes of the array.
If you are going to do the sumation on data entry then get rid of A. Otherwise do this program in three steps.
1) obtain values for A using loop #1
2) after loop #1 is done sum the values in A using loop #2
3) calculate the mean after both loops are done.
Last edited by Lerner; Aug 15th, 2008 at 2:50 pm.
![]() |
Similar Threads
- Finding Max Number in Array (Java)
- Pseudocode (Simply Array Process) (Computer Science)
- number of times each number in array occurs? (C)
- array help (C++)
- Output problems (C++)
- C++ : Calculating the average value of an array (C++)
- c++ array using a for loop (C++)
- Functions and Array help (C++)
- question about array (C++)
Other Threads in the C++ Forum
- Previous Thread: C++ OpenGL help.
- Next Thread: DLL Function Call
| Thread Tools | Search this Thread |
Tag cloud for C++
api application array arrays assignment beginner binary bitmap c++ c/c++ calculator char char* class classes code coding compile compiler console conversion convert count data database delete developer display dll email encryption error file forms fstream function functions game generator getline givemetehcodez graph homeworkhelper iamthwee ifstream image input int java lazy lib loop looping loops map math matrix memory multidimensional multiple newbie news node number numbertoword output parameter pointer problem program programming project proxy python random read recursion recursive reference return sorting string strings struct template templates text tree url variable vector video visual visualstudio win32 windows winsock word wordfrequency wxwidgets






