My program is suppose to read positive and odd numbers and add their sums but any negative numbers they are not suppose to count or be added to the sum. My error message is coming up when I type a negative number in but I think it's still being counted and added to the sum. Can someone take a look and help me out?

#include <iostream>
using std::cout;
using std::cin;
using std::endl;

int main ()
{
	
	int number1;
	int sumeven=0;
	int sumodd=0;
	int evencounter=0;
	int oddcounter=0;
	int counter;
	

	cout<<"Please enter 10 integers: \n";
	
	for( counter=1; counter<=10; counter++)
	{
		cin>> number1;
		if (number1 % 2 == 0)
		{
			evencounter++;
			sumeven=sumeven+number1;
		}
		else
		{		
			oddcounter++;
			sumodd=sumodd+number1;
		} 
		if (number1 < 0)
		cout<<"One number is invalid. Enter positive number: \n"<<number1;
		
	} 
cout<<"There are " <<evencounter<<" even numbers \n ";
cout<< "and the sum of all even numbers is: \n"<<sumeven;

cout<<"\nThere are " <<oddcounter<<" odd numbers \n";
cout<< "and the sum of all odd numbers is: \n"<<sumodd;


	return 0;

}

Recommended Answers

All 3 Replies

Whenever you enter a negative number your counter increases by 1 which i think you do not want.....rest is fine.....Modify the code like this....

if (number1 < 0)
		{
			cout<<"One number is invalid. Enter positive number: \n"<<number1<<"\n";
			counter=counter-1;
		}

hi i think you should do it like that

#include <iostream>
using std::cout;
using std::cin;
using std::endl;

int main ()
{
	
	int number1;
	int sumeven=0;
	int sumodd=0;
	int evencounter=0;
	int oddcounter=0;
	int counter;
	

	cout<<"Please enter 10 integers: \n";
	
	for( counter=1; counter<=10; counter++)
	{
		cin>> number1;
		if (number1 < 0){
		cout<<"One number is invalid. Enter positive number: \n"<<number1<<endl;
cout<<"Please enter the correct number: \n";
		cin >>number1 ;
		}
		if (number1 % 2 == 0)
		{
			evencounter++;
			sumeven=sumeven+number1;
		}
		else
		{		
			oddcounter++;
			sumodd=sumodd+number1;
		} 
	
		
	} 
cout<<"There are " <<evencounter<<" even numbers \n ";
cout<< "and the sum of all even numbers is: \n"<<sumeven;

cout<<"\nThere are " <<oddcounter<<" odd numbers \n";
cout<< "and the sum of all odd numbers is: \n"<<sumodd<<endl;


	return 0;

}

<< moderator edit: added [co[u][/u]de][/co[u][/u]de] tags >>

Thanks for all help :) . I can't believe all it was missing was one line.

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.