943,633 Members | Top Members by Rank

Ad:
  • C++ Discussion Thread
  • Marked Solved
  • Views: 4514
  • C++ RSS
You are currently viewing page 1 of this multi-page discussion thread
Aug 15th, 2008
0

Average and sum with array

Expand Post »
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)
  1. #include <iostream>
  2. #include <cmath>
  3.  
  4. using namespace std;
  5.  
  6. const int MAX = 10;
  7.  
  8. //Main Module
  9. int main()
  10. {
  11. int A[MAX] ; // declare the size of the array
  12. int sum ; // declare sum as integer
  13. float mean ; // declare average as a float
  14. int i; // declare i as integer
  15. int number; // declare number as integer
  16.  
  17. cout << "This program computes the average of 10 numbers";
  18. cout << endl ;
  19.  
  20. //create for loop
  21. for (i = 0; i < MAX; i++)
  22. {
  23. cout << "Enter a positive number" << i << ":" ;
  24. cin >> number;
  25.  
  26. // while else statement (INSIDE the loop) to calculate for user error
  27.  
  28. if (number >= 0)
  29. cout << "Invalid Entry! Enter a number greater than or equal to zero." ;
  30.  
  31. else (number < 0)
  32.  
  33. sum= 0;
  34. sum = sum + number;
  35. i++;
  36.  
  37.  
  38. }
  39. mean = 1 * sum / 10;
  40.  
  41.  
  42. cout << "The sum is: " << sum << endl ;
  43. cout << "The average is: " << mean << endl ;
  44.  
  45.  
  46. return (0); // terminate with success
  47. }
Last edited by Tekmaven; Aug 15th, 2008 at 2:48 pm. Reason: Code tags
Similar Threads
Reputation Points: 10
Solved Threads: 0
Newbie Poster
cicigirl04 is offline Offline
17 posts
since Aug 2008
Aug 15th, 2008
0

Re: Average and sum with array

>I get a error if I don't have ; after else statement, before sum = 0
else (number < 0)
The else statement doesn't have a condition; the condition is implied by the accompanying if and else if clauses:
C++ Syntax (Toggle Plain Text)
  1. if (number >= 0)
  2. cout << "Invalid Entry! Enter a number greater than or equal to zero." ;
  3. else
  4. sum = 0;
>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:
C++ Syntax (Toggle Plain Text)
  1. mean = 1.0f * sum / 10.0f;
>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.
Last edited by Radical Edward; Aug 15th, 2008 at 12:19 pm.
Reputation Points: 361
Solved Threads: 97
Posting Pro
Radical Edward is offline Offline
526 posts
since May 2008
Aug 15th, 2008
0

Re: Average and sum with array

hmmm...lemme analyze this abit:
C++ Syntax (Toggle Plain Text)
  1. #include <iostream>
  2. #include <cmath>
  3.  
  4. using namespace std;
  5.  
  6. const int MAX = 10 + 1; //let it have more space
  7.  
  8. //Main Module
  9. int main()
  10. {
  11. int A[MAX] ; // declare the size of the array
  12. int sum ; // declare sum as integer
  13. float mean ; // declare average as a float
  14. int i; // declare i as integer
  15. int number; // declare number as integer
  16.  
  17. cout << "This program computes the average of 10 numbers";
  18. cout << endl ;
  19.  
  20. //create for loop
  21. for (i = 0; i < MAX; i++)
  22. {
  23. cout << "Enter a positive number" << i << ":" ;
  24. cin >> number;
  25.  
  26. // while else statement (INSIDE the loop) to calculate for user error
  27.  
  28. if (number >= 0) // this here says: if the number is greater than or equal to zero it's invalid
  29. cout << "Invalid Entry! Enter a number greater than or equal to zero." ;
  30.  
  31. else (number < 0) // dunno what you're trying to do here
  32.  
  33. sum= 0; // this will set your sum to 0 each and every time..so you'll never sum all the numbers
  34. sum = sum + number; //sum should be initialized at the start
  35. i++;
  36.  
  37.  
  38. }
  39. mean = 1 * sum / 10;
  40.  
  41.  
  42. cout << "The sum is: " << sum << endl ;
  43. cout << "The average is: " << mean << endl ;
  44.  
  45.  
  46. return (0); // terminate with success
  47. }
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...
Reputation Points: 12
Solved Threads: 5
Junior Poster in Training
gregorynoob is offline Offline
86 posts
since Jun 2008
Aug 15th, 2008
0

Re: Average and sum with array

here...this should work...
C++ Syntax (Toggle Plain Text)
  1. #include <iostream>
  2.  
  3. using namespace std;
  4. int number, sum = 0;
  5.  
  6. int main( void )
  7. {
  8. cout << "This program computes the average of 10 numbers" << endl; // you can put the endl right away or use "\n"
  9. for( int i = 0; i < 10; ++i ) {
  10. cout << "Enter a positive number" << i << ": ";
  11. cin >> number;
  12. if( number < 0 ) cout << "Invalid Entry! Enter a number greater than or equal to zero." ;
  13. else ( number >= 0 );
  14. sum += number;
  15. }
  16. float mean = 1. * sum/10.;
  17.  
  18. cout << "The sum is: " << sum << endl ;
  19. cout << "The average is: " << mean << endl ;
  20.  
  21. scanf( "\n" );
  22. return 0;
  23. }
Last edited by gregorynoob; Aug 15th, 2008 at 12:34 pm.
Reputation Points: 12
Solved Threads: 5
Junior Poster in Training
gregorynoob is offline Offline
86 posts
since Jun 2008
Aug 15th, 2008
0

Re: Average and sum with array

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)
  1. #include <iostream>
  2. #include <cmath>
  3.  
  4. using namespace std;
  5.  
  6. const int MAX = 10;
  7.  
  8. //Main Module
  9. int main()
  10. {
  11. int A[MAX] ; // declare the size of the array
  12. int sum ; // declare sum as integer
  13. float mean ; // declare average as a float
  14. int i; // declare i as integer
  15. int number; // declare number as integer
  16.  
  17. cout << "This program computes the average of 10 numbers";
  18. cout << endl ;
  19.  
  20. //create for loop
  21. for (i = 0; i < MAX; i++)
  22. {
  23. cout << "Enter a positive number" << i << ":" ;
  24. cin >> number;
  25.  
  26. // while else statement (INSIDE the loop) to calculate for user error
  27.  
  28. if (number < 0)
  29. cout << "Invalid Entry! Enter a number greater than or equal to zero." ;
  30.  
  31. else
  32.  
  33. sum= 0;
  34. sum = sum + number;
  35. i++;
  36.  
  37.  
  38. }
  39. mean = 1.0f * sum / 10.0f;
  40.  
  41.  
  42. cout << "The sum is: " << sum << endl ;
  43. cout << "The average is: " << mean << endl ;
  44.  
  45.  
  46. return (0); // terminate with success
  47. }
Reputation Points: 10
Solved Threads: 0
Newbie Poster
cicigirl04 is offline Offline
17 posts
since Aug 2008
Aug 15th, 2008
0

Re: Average and sum with array

hehehe, you have an "i++;" in your for loop...
so it actualy reads every second number.
if you remove it it will read all
Reputation Points: 12
Solved Threads: 5
Junior Poster in Training
gregorynoob is offline Offline
86 posts
since Jun 2008
Aug 15th, 2008
0

Re: Average and sum with array

If you don't mind Edward giving some constructive criticism, read on.
// This should never be in the global scope
using namespace std;

// Global variables should be avoided when possible
int number, sum = 0;
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.
C++ Syntax (Toggle Plain Text)
  1. // you can put the endl right away or use "\n"
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.
C++ Syntax (Toggle Plain Text)
  1. else ( number >= 0 );
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:
C++ Syntax (Toggle Plain Text)
  1. if (number < 0) {
  2. cout << "...";
  3. }
  4. else {
  5. (number >= 0); // No effect
  6. }
  7.  
  8. sum += number;
>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:
C++ Syntax (Toggle Plain Text)
  1. float mean = 1.f * sum/10.f;
  2.  
  3. // or
  4.  
  5. float mean = float(1.) * sum/float(10.);
C++ Syntax (Toggle Plain Text)
  1. scanf( "\n" );
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 scanf("\n") works.
Reputation Points: 361
Solved Threads: 97
Posting Pro
Radical Edward is offline Offline
526 posts
since May 2008
Aug 15th, 2008
0

Re: Average and sum with array

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.
Reputation Points: 10
Solved Threads: 0
Newbie Poster
cicigirl04 is offline Offline
17 posts
since Aug 2008
Aug 15th, 2008
0

Re: Average and sum with array

It is quite simple. User input the value into number not A[number] . So it should be sum = sum + number .
Reputation Points: 350
Solved Threads: 63
Posting Pro
invisal is offline Offline
562 posts
since Mar 2005
Aug 15th, 2008
1

Re: Average and sum with array

This:
C++ Syntax (Toggle Plain Text)
  1. else
  2. sum = 0;
  3. sum = sum + A[number];}
is equivalent to this:
C++ Syntax (Toggle Plain Text)
  1. else
  2. {
  3. sum = 0;
  4. }
  5. 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.
Reputation Points: 718
Solved Threads: 373
Nearly a Posting Maven
Lerner is offline Offline
2,253 posts
since Jul 2005

This thread is solved

Either the thread starter or a moderator has marked this thread as solved. You can most likely trust the responses and answers given. There is most likely no reason for any further responses to be posted here. If you have a related question, please start a new thread in this forum instead.

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in C++ Forum Timeline: C++ OpenGL help.
Next Thread in C++ Forum Timeline: DLL Function Call





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC