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

#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
}

Recommended Answers

All 13 Replies

>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:

if (number >= 0)
  cout << "Invalid Entry! Enter a number greater than or equal to zero." ;
else
  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:

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.

hmmm...lemme analyze this abit:

#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
}

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...

here...this should work...

#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;
}

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.

#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
}

hehehe, you have an "i++;" in your for loop...
so it actualy reads every second number.
if you remove it it will read all

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.

// 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. :)

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:

if (number < 0) {
  cout << "...";
}
else {
  (number >= 0); // No effect
}

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:

float mean = 1.f * sum/10.f;

// or

float mean = float(1.) * sum/float(10.);
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. ;)

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
}

It is quite simple. User input the value into number not A[number] . So it should be sum = sum + number .

This:

else
  sum = 0;
  sum = sum + A[number];}

is equivalent to this:

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.

commented: well explained +5

Yet another tip.
There is a wonderful class valarray in C++ STL. It lives in (undeserved) obscurity.
If you declare your array as a valarray, for example:

std::valarray<int> a(10);

and fill it from the console (as an usual array), you may use its member functions, for example:

a.sum()             // to get a sum of all element values
a.sum()/a.size() // to get an average of...

No loops, no troubles...

i love scanf( "\n" ); :) i only use it to keep the program from stopping anyways, you can use system( "pause" ); for that and comment it out afterwards. i only use it cause i don't run my programs through cmd prompt by diring to it first, my compiler opens it in dos.

btw... i didn't know about the valarray thing...pretty awesome. still you have a less memory complexity using 2 variables

Thanks everyone for your help. I have it working now.

I have a question and I want to know how would you put test cases on this program. I have a similar program but i approached it a different way and so I'm trying to figure out how test it. I don't want the answer to my program but this one so I can get an idea of it

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.