954,499 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Help with C++ code

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;

}
Dee_Dee
Newbie Poster
4 posts since Oct 2005
Reputation Points: 10
Solved Threads: 0
 

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;
		}
SpS
Posting Pro
599 posts since Aug 2005
Reputation Points: 70
Solved Threads: 32
 

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 [code][/code] tags >>

some one
Junior Poster
129 posts since Apr 2005
Reputation Points: 10
Solved Threads: 0
 

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

Dee_Dee
Newbie Poster
4 posts since Oct 2005
Reputation Points: 10
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You