Summming odd and even numbers in an undetermined range - c++

My assignment is to create a program in which the user inputs a starting value and ending value. The program should then sum all the numbers within that range. In addition it should sum the odd numbers and the even numbers. My issue is determining which numbers in the users range is odd and which is even and then summing these values. The total sum loop works but I have tried multiple other loops for the odd and even sums and have had no success. So if someone could help me sum these numbers based on whether there even or odd.
#include <iostream>
using namespace std;
int main()
{
int sum = 0, start, endnumber;
int sumall = 0, c=0;
cout << "Please enter the starting integer\n";
cin >> start;
cout << "Please enter the ending integer\n";
cin >> endnumber;
while (endnumber <= start)
{
cout << "Please enter the starting integer\n";
cin >> start;
cout << "Please enter the ending integer\n";
cin >> endnumber;
}
while (start <= endnumber)
{
sumall = sumall + start;
++start;
}
std::cout << "The sum is: " << sumall << std::endl;
return 0;
}

You need to check each number in the range with modulo.
For ex:
if( start%2 == 0 ) // even
{
evenSum+=start;
}
else // Odd
{
oddSum+=start;
}
That will do the job.

You can test for odd numbers by anding with 1.
if ((start & 1) == 0)
evenSum += start;
else
oddSum += start;
Small note when talking to mathematicians: don't use modulo and modulus interchangeably (even though wikipedia says they are the same):
modulo is % for positive numbers.
modulus is the abs function.

Related

Total number of odd/even numbers

Hello I'm trying to display only the amount of odd/even numbers for the digits entered. I've tried multiple methods but failed to find any solution. This is the problem and what I have so far.
Write a program that allows the user to enter 10 separate whole numbers. After accepting these 10 numbers from the user, the program should display output to the user informing them how many of the numbers entered were odd numbers and how many were even numbers.
#include <iostream>
using namespace std;
int main() {
char even, odd;
int number;
for(int i = 1;i<=10;i++) {
cout << "Enter Number " << i << ":" ;
i=i+0;
cin >> number ;
}
if (number%2==0){
number = even;
}
cout<< "You entered:\n";
cout << "Odd Numbers: " << odd << endl;
cout << "Even Numbers: " << even << endl;
return 0;
}
There are a few things in your code that do not look right.
for(int i = 1; i <= 10; i++)
{
cout << "Enter Number " << i << ":";
i = i + 0;
cin >> number;
}
What are you hoping to accomplish with the line i = i + 0? Your loop will work just fine without it.
char even, odd;
Technically, since char is a numeric type, you may keep track of the number of even and odd numbers encountered by keeping track of them. However, you aren't doing that.
The statement:
if (number%2==0){
number = even;
}
Is saying that if the input number is even, assign the current value of char even to number. However, this doesn't make sense, since you never stored a value in even earlier. Also, you're doing this outside the loop, so effectively only the last of the 10 values read into number would ever be counted in your calculations (if you had that done correctly).
What you should do:
int even = 0, odd = 0;
for(...)
{
// read input into "number"...
if(number % 2 == 0)
{
even++;
}
else
{
odd++;
}
}

Ignoring invalid input from a count and average

The program requires the user to input numbers and when finished to exit the loop by entering a negative number. The program will then output the average of the numbers and the count of the numbers. The negative number should be removed from the series though. So if we have three numbers and exit on the (fourth) negative number, the average will only be of the three numbers and not include the negative number. Neat, I somehow made that work. Now, I need to expand upon this to make it so that the input is verified to be an integer and less than 100 also using a Boolean equation. It is at this point that I cannot determine how to exclude the erroneous input from the results.
#include <iostream>
#include <iomanip>
using namespace std;
int main ()
{
float inScore= 1;
float sumScore= 0.0;
int scoreCount= 0;
float avgScore= 0.0;
bool moreNumbers = true;
bool notNumbers = true;
for ( inScore =1; inScore >=1; inScore++) //for loop some kind of blackmagic not really sure about this right now
{
cout << "Please enter grades (enter a negative integer to exit): ";
cin >> inScore;
if (!cin || inScore > 100)
{
notNumbers = false; //boolean to ignore non integers or numbers greater than 100
cin.clear();
cin.ignore(256, '\n');
scoreCount--;
cout << "Invalid number!" << endl;
} //something is wrong in this section and I can't get it to ignore the invalid inputs
else if (inScore < 0)
{
moreNumbers = false;
} //breaks the loop upon a negative number being entered
else
sumScore+=inScore;
scoreCount++;
}
avgScore = (sumScore+=inScore)/(scoreCount-1);
cout << "Number of Grades: " << scoreCount-1 << endl; //number of entries
cout << "Average: " << avgScore << endl; // average grade except I cannot figure out how to remove negative number from the array
return 0;
}

How do I determine the highest and lowest value using do while loops

I am currently stuck in my homework and the problem is that I need to create a program that will ask for 5 integer numbers from which I should determine the highest and lowest value. I am quite confused as of now, and my initial code is this:
#include<iostream>
using namespace std;
int main(){
int num1,num2,num3,num4,num5,min=0,max=0;
cout << " Enter 1st number : ";
cin >> num1;
cout << " Enter 2nd number : ";
cin >> num2;
cout << " Enter 3rd number : ";
cin >> num3;
cout << " Enter 4th number : ";
cin >> num4;
cout << " Enter 5th number : ";
cin >> num5;
do{
if(num1<num2 && num1<num3 && num1<num4 && num1<num5 ){
max = num1;}
if(num2<num1 && num2<num3 && num2<num4 && num2<num5 ){
max = num2;}
if(num3<num1 && num3<num2 && num3<num4 && num3<num5 ){
max = num3;}
if(num4<num1 && num4<num3 && num4<num2 && num4<num5 ){
max = num4;}
if(num5<num1 && num5<num3 && num5<num4 && num5<num2 ){
max = num2;}
}while(max>0);
cout << " The highest number is : " <<max;
return 0;
}
Any help would be appreciated. Thanks in advance!
You should store your numbers into a std::vector<int> or std::array and then use the std::minmax_element algorithm to obtain the largest and smallest number.
If you are allowed to use std::max and std::min, you can use:
max = std::max({num1, num2, num3, num4, num5});
min = std::min({num1, num2, num3, num4, num5});
to simplify the code in the loop.
This would be my solution without using arrays.
I'd suggest you to try it yourself before. You don't learn when you just copy code.
#include <iostream>
int main() {
int i=0, num, min=INT_MAX, max=INT_MIN;
do {
std::cout << "Enter number: ";
std::cin >> num;
if (num < min) {
min = num;
}
if (num > max) {
max = num;
}
i++;
} while (i < 5);
std::cout << "The max number is: " << max << std::endl;
std::cout << "The min number is: " << min << std::endl;
return 0;
}
If you don't need to remember, you can loop for e.g. 5 times, then have a comparison before asking the next number.
so generally (idea, write it yourself and learn):
for (5 times)
ask user input, save as input
if largest number is null, then equal to input
else if largest number is smaller, then set input equal to largest number
Continue for loop times.
Rather than compare all the numbers each time. Simply compare your current smallest against the numbers in sequence.
int data[5];
// read numbers into data.
int min = data[0]; // Guess that number 0 is the smallst number.
// Now check if the guess is correct and update if you are wrong.
for(int loop = 0; loop < 5; ++loop)
{
// check if data[loop] is smaller than your current guess.
// if it is smaller than update your guess.
// when you have checked all the values exit the loop.
}
std::cout << "Smallest: " << min << "\n";
There is no need to use a loop to do this you can do that without it else if it's necessary to use a loop you must use an array or some other data structure

C++ - Check if there are no even numbers in given interval

I have to write a program on C++ which finds all even numbers in range given by user. Here's the code I have written so far:
#pragma hdrstop
#pragma argsused
#include <tchar.h>
#include <iostream.h>
#include <conio.h>
#include <stdio.h>
#include <math.h>
void main() {
int m, n, j = 1; // m and n- numbers entered by user, j- product of all even numbers in interval
char atbilde; // A letter entered by user, of which system decides wether to continue or to stop programme
do {
j = 1;
cout << "Enter the min number of interval! ";
cin >> n;
cout << "Enter the max number of interval! ";
cin >> m;
if (n > m) { // Detects wether „n” is larger than „m”
cout << "Max number of interval has to be larger than min number!";
do { // If max number is larger than min number, screen is cleared
cin.clear();
cin.ignore();
cout << "Enter the numbers again!";
cout << "\n Enter the min number of interval! ";
cin >> n;
cout << "\n Enter the max number of interval! ";
cin >> m;
}
while (n > m);
}
cout << "Even numbers in given interval: ";
for (; n <= m; n++)
{
if (n % 2 == 0)
{ // Detects, wether there are even numbers in given interval
if (n != 0) {
cout << n << " ";
j *= n;
}
if ((n == m) && (n % 2 != 0)) {
j=0;
}
}
}
cout << "\n The product of found even numbers: " << j << " ";
cout << "\n Repeat? (Y/N) ";
cin >> answer;
system("cls");
}
while (tolower(answer) != 'n');
}
But I have a small problem, so I can't get the program 100% done because of the problem.
Like, user enters range, whose min and max number is the same and it's odd. In that case program has to print out a sentence "there were no even numbers in interval" in place of "The product of found even numbers:". I have searched the solution in internet, but haven't found it.
I hope you'll know the right solution.
Some hints to help you along the way: If there was no even number in the range, you will not enter into the loop. What will j be then? How do you react on that value?
I tried to fix your code, I did the best I could from what I understood you were tring to do.
I cleaned it up, fixed spelling and grammer, I deleted unnecessary stuff, I also made it more compact and nice to look at.
#include <iostream>
int main() {
int max=0, min=1, sum=0; product = 1, amount = 0; // max, min - entered by user, product - product of all even numbers in interval, sum - sum of all even numbers in interval. amount - amount of even numbers in interval
char x=Y; // Entered by user to know if to quit or continue to continue.
while ((x == Y) || (x == y))
{
while (min > max) { // System detects whether minimum is bigger than maximum
cin.clear(); // Clears screen so if this part runs again it wouldn't get messy.
cin.ignore();
cout << "Max has to be larger than min!";
cout << "\n Enter the min number of interval! ";
cin >> min;
cout << "\n Enter the max number of interval! ";
cin >> max;
}
for (; min <= max; min++)
{
if (min % 2 == 0)
{
sum+=n;
count++;
product*=n;
}
}
if (count == 0)
{
product=0;
cout << "There are no even numbers in interval!";
}
else
{
cout << "\n The amount of the even numbers in interval: " << amount << ",the product of the even numbers: " << product << ",the sum of the even numbers: " sum << "\n\n";
}
cout << "Repeat? (Y/N) ";
x=getchar;
system("cls");
}
return 0;
}

Trouble with counters

I'm very new to C++ and have an assignment to edit this code to make it work. For some reason, when I use a combination of multiple positive or negative numbers, it gives the answer that I've entered multiple numbers an extra number.
Example:
I enter 3 postive numbers and 1 negative number. The counter displays 4 positive and 1 negative. Same thing happens if I start with negative numbers instead of positive.
Any help would be greatly appreciated. Here's the code:
#include <iostream>
using namespace std;
int main()
{
int number = 0;
int positive = 0; //counter
int negative = 0; //counter
int totalPositive = 0;
int totalNegative = 0;
//get a number
cout << "Enter a positive or negative integer (enter 0 to end): ";
cin >> number;
while (number != 0)
{
//update counters
if (number > 0)
{
positive =+ 1;
}
else
negative =+ 1;
//end if
//get another number
cout << "Enter another positive or negative integer (enter 0 to end): ";
cin >> number;
totalPositive += positive;
totalNegative += negative;
}//end while
//display counters
cout << endl;
cout << "Total positive numbers: " << totalPositive << endl;
cout << "Total negative numbers: " << totalNegative << endl;
system("pause");
return 0;
} //end of main function
Try this code:
#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
int number;
int positive = 0;
int negative = 0;
do{
cout << "Enter a positive or negative integer (enter 0 to end): ";
cin >> number;
if (number > 0)
positive += 1;
else if(number<0)
negative += 1;
}while(number!=0);
//end while
//display counters
cout << endl;
cout << "Total positive numbers: " << positive << endl;
cout << "Total negative numbers: " << negative << endl;
system("pause");
return 0;
} //end of main function
You don't have to use total positive and total negative, unless you want to have the summation of the positive numbers and the negative ones.
positive is accumulating, but totalPositive is accumulating your accumulation. Try totalPositive++ (and the negative version) in your if statement, and eliminate variables positive and negative.
The logic error in your program is that positive and negative never get reset to 0 once they are set to 1.
If your first two numbers are such that one is a negative number and the other is a positive number, totalPositive and totalNegative will keep increasing after that regardless of the value of number.
You can simplify your logic to:
//get a number
cout << "Enter a positive or negative integer (enter 0 to end): ";
while (cin >> number && number != 0)
{
//update counters
if (number > 0)
{
++totalPositive;
}
else
{
++totalNegative;
}
//get another number
cout << "Enter another positive or negative integer (enter 0 to end): ";
}//end while
Firstly note the =+ is not an operator (Unlike += which increments the value)
The line
positive =+ 1
is just interpreted as assigned +1 to positive (which is what you want) but can be just written as
positive = 1
This though brings us to the actual point which is that you don't reset positive or negative back to zero each time around the loop.
Once both positive and negative are assigned to 1 (i.e. when you have entered at least one of each), every time both totalPositive and totalNegative will be incremented.
You may want to consider whether you need the variables positive or negative at all.
SOmething that might help is to do this for the while loop instead
while (number != 0)
{
positive = 0;
negative = 0;
//update counters
if (number > 0)
{
positive = 1;
}
else
negative = 1;
//end if
//get another number
cout << "Enter another positive or negative integer (enter 0 to end): ";
cin >> number;
totalPositive +=positive;
totalNegative +=negative;
}
Otherwise you're doing this thing that's basically 1 + 2 + 3 + 4... for every time the loop runs. By setting each value to 0, it ensures that totalPositive only increases once every loop. Otherwise it grows exponentially
Well your counters are not reset to 0 after your loop finishes.
When you enter your loop the first time, the counters are 0 (positive, negative), but the second time around, the counters are still 1, resulting in a bad counter.
When entering the loop:
positive = 0;
negative = 0;
//update counters
This code, could be highly refactored to be more efficent, but that's for another question.