C++ : Count even / odd numbers in a range - c++

My program has to count how many numbers in a range are even and how many of them are odd but I can't seem to figure it out.It kinda works
but when I put numbers in it spouts out nonsense. I'm an extreme nooob when it comes to programing, I think that the problem has to be at line 21 for (i=n; i<=m; i++) { ?
But I'm not sure. I have a programing book but it does not help much,maybe someone can help?
#include <iostream>
using namespace std;
int main()
{
int n;
int m;
int i;
int a;
int b;
cout << "Enter a number that begins interval: ";
cin >> n;
cout << "Enter a number that ends interval: ";
cin >> m;
a=0;
b=0;
for (i=n; i<=m; i++) {
if (i%2 == 0){
a=a+i;
}
else {
b=b+i;
}
}
cout << " unequal numbers: " << a << endl;
cout << " equal numbers: " << b << endl;

Assuming you mean even and odd numbers your problem lies in this code:
for (i=n; i<=m; i++) {
if (i%2 == 0){
a=a+i; // increase number of even numbers by i
}
else {
b=b+i; // increase number of odd numbers by i
}
}
What you might want do to do is add 1 (instead of whatever i is):
for (i = n; i <= m; ++i) {
if (i % 2 == 0)
++a; // increase number of even numbers by one
else
++b; // increase number of odd numbers by one
}
Also I'd suggest using better variable names, for example even and odd instead of a and b and so on. It makes code easier to understand for everybody, even for you.
Just a little more tips. Assigning variables as soon as you declare them is good practice:
int m = 0;
You can declare variable inside of for loop, and in your case there is no need to declare it out of it:
for (int i = n; i <= m; ++i) { ... }
Example how it can change look and clarity of your code:
#include <iostream>
using namespace std;
int main() {
int from = 0,
to = 0,
even = 0,
odd = 0;
cout << "Enter a number that begins interval: ";
cin >> from;
cout << "Enter a number that ends interval: ";
cin >> to;
for (int i = from; i <= to; ++i) {
if (i % 2 == 0)
++even;
else
++odd;
}
cout << " even numbers: " << even << endl;
cout << " odd numbers: " << odd << endl;
return 0; // don't forget this! main is function returning int so it should return something
}

Ok, so as per the new clarification the following should work
#include <iostream>
using namespace std;
int main()
{
int n;
int m;
int i;
int a;
int b;
cout << "Enter a number that begins interval: ";
cin >> n;
cout << "Enter a number that ends interval: ";
cin >> m;
a=0;
b=0;
for (i=n; i<=m; i++) {
if (i%2 == 0){
a++;
}else {
b++;
}
}
cout << " unequal numbers: " << a << endl;
cout << " equal numbers: " << b << endl;
}
So the following changes were done:
The for loop was closed
a = a + i or b = b + i was wrong as you are adding the counter value to the count which should be a++ or b++. Changed that also
The last two lines where you are showing your result was out of the main method, brought them inside the main method
Hope you find this useful.

You don't need to use loop to count even and odd numbers in a range.
#include <iostream>
int main ()
{
int n,m,even,count;
std::cin >> n >> m;
count=m-n+1;
even=(count>>1)+(count&1 && !(n&1));
std::cout << "Even numbers: " << even << std::endl;
std::cout << "Odd numbers: " << count-even << std::endl;
}

#include <iostream>
using namespace std;
int main()
{
int n, i;
cin >> n;
cout << " even : ";
for (i = 1; i <= n * 2; i++)
{
if (i % 2 == 0)
cout << i << " ";
}
cout << " odd : ";
for (i = 1; i <= n * 2; i++)
{
if (i % 2 != 0)
cout << i << " ";
}
return 0;
}
//input n = 5
// output is even : 2 4 6 8 10
// odd : 1 3 5 7 9

#include <iostream>
using namespace std;
int main()
{
int n;
int m;
int i;
int a;
int b;
cout << "Enter a number that begins interval: ";
cin >> n;
cout << "Enter a number that ends interval: ";
cin >> m;
a = 0;
b = 0;
for (i = n; i < = m; i++) {
if (i%2 == 0){
a = a + 1;
} else {
b = b + 1;
}
}
cout << " unequal numbers: " << a << endl;
cout << " equal numbers: " << b << endl;
}

Not sure why you are looping through all the elements (half of them are going to be even and the other half odd). The only case where you have to consider when the interval length is not divisible by two.
using namespace std;
int main()
{
int n;
int m;
int x;
int odds;
int evens;
cout << "Enter a number that begins interval: ";
cin >> n;
cout << "Enter a number that ends interval: ";
cin >> m;
cout << n << " " << m << endl;
x = m - n + 1;
odds = x / 2;
evens = odds;
if (x % 2 != 0) {
if (n % 2 == 0) {
evens++;
} else {
odds++;
}
}
cout << " even numbers: " << evens << endl;
cout << " odd numbers: " << odds << endl;
}
This is a more readable version of #Lassie's answer

Related

Using an Array[10] and incrementing it with a While loop using modulo 10 to Pair User inputs together

#include <iostream>
using namespace std;
int main()
{
long int number;
int digits;
cout << "Enter Number: ";
cin >> number;
int counter[10] = { 0,0,0,0,0,0,0,0,0,0 };
while (number != 0) {
digits = number % 10;
counter[digits] = counter[digits] + 1;
number = number / 10;
}
for (int i = 0; i<10; i++) {
if (counter[i] != 0) {
cout << i << ": " << counter[i] << endl;
}
}
return 0;
system("pause");
}
I'm having an issue with my code that when I run it and enter a Number nothing really happens. It is supposed to run something like 1234556789 and the output should look like
1 : 9
2 : 8
3 : 7
4 : 6
5 : 5
I know sometimes if there isn't a system pause this happens where it runs part of the code and just ends, but I'm not sure whats wrong here.
#include <iostream>
using namespace std;
int main()
{
long int number;
int digits;
cout << "Enter Number: ";
cin >> number;
int counter[10]={0},a=0;
while (number != 0) {
digits = number % 10;
counter[a] = digits; //made changes to this line
number = number / 10;
++a;
}
for (int i = 0; i<10; i++) {
if (counter[i] != 0) {
cout << i << ": " << counter[i] << endl;
}
}
return 0;
}
All you are doing right now is printing how many digits there are of each number 0-9 in the number. If you want to pair elements together, then you can use std::vector and iterators. The number of digits in your input can be either even or odd and you would have to account for both cases.
#include <iostream>
#include <vector>
using namespace std;
int main()
{
long int number;
cout << "Enter Number: ";
cin >> number;
vector<int> digits;
if (number == 0)
{
digits.push_back(number);
}
while (number != 0)
{
digits.push_back(number % 10);
number /= 10;
}
auto it_begin = digits.begin();
auto it_end = digits.end() - 1;
if (digits.size() % 2 == 1)
{
for (; it_end != it_begin; ++it_begin, --it_end)
{
cout << *it_end << ": " << *it_begin << endl;
}
cout << *it_end << endl;
}
else
{
for (; it_begin < it_end; ++it_begin, --it_end)
{
cout << *it_end << ": " << *it_begin << endl;
}
}
}
With number = 1234556789, the output is:
1: 9
2: 8
3: 7
4: 6
5: 5
If you want first 10 no. Only use this code
include using namespace std;int main() {long int number;cout << "Enter Number: ";cin >> number;for (int i = 1; i<=10; i++) {cout << i << ": "<

Not taking the input

I want to write a program that only takes odd numbers, and if you input 0 it will output the addition and average, without taking any even number values to the average and the addition. I'm stuck with not letting it take the even values..
Heres my code so far:
int num = 0;
int addition = 0;
int numberOfInputs = 0;
cout << "Enter your numbers (only odd numbers), the program will continue asking for numbers until you input 0.." << endl;
for (; ;) {
cin >> num;
numberOfInputs++;
addition = addition + num;
if (num % 2 != 0) {
//my issue is with this part
cout << "ignored" << endl;
}
if (num == 0) {
cout << "Addition: " << addition << endl;
cout << "Average: " << addition / numberOfInputs << endl;
}
}
Solution of your code:
Your code doesn't working because of following reasons:
Issue 1: You adding inputs number without checking whether it's even or not
Issue 2: If would like skip even then your condition should be as follow inside of the loop:
if (num%2==0) {
cout << "ignored:" <<num << endl;
continue;
}
Solving your issues, I have update your program as following :
#include <iostream>
#include <string>
using namespace std;
int main()
{
int num = 0;
int addition = 0;
int numberOfInputs = 0;
cout << "Enter your numbers (only odd numbers), the program will continue asking for numbers until you input 0.." << endl;
for (; ;) {
cin>> num;
if (num%2==0) {
cout << "ignored:" <<num << endl;
continue;
}
numberOfInputs++;
addition = addition + num;
if (num == 0) {
cout << "Addition: " << addition << endl;
cout << "Average: " << addition / numberOfInputs << endl;
break;
}
}
}
#include <iostream>
#include <stdio.h>
using namespace std;
int main() {
int number;
int sum=0;
int average=0;
int inputArray[20]; // will take only 20 inputs at a time
int i,index = 0;
int size;
do{
cout<<"Enter number\n";
cin>>number;
if(number==0){
for(i=0;i<index;i++){
sum = sum + inputArray[i];
}
cout << sum;
average = sum / index;
cout << average;
} else if(number % 2 != 0){
inputArray[index++] = number;
} else
cout<<"skip";
}
while(number!=0);
return 0;
}
You can run and check this code here https://www.codechef.com/ide
by providing custom input

Greedy Algorithm for coin change c++

So, I'm creating a coin change algorithm that take a Value N and any number of denomination and if it doesn't have a 1, i have to include 1 automatically. I already did this, but there is a flaw now i have 2 matrix and i need to use 1 of them. Is it possible to rewrite S[i] matrix and still increase the size of array.... Also how can i find the max denomination and the second highest and sooo on till the smallest? Should i just sort it out in an highest to lowest to make it easier or is there a simpler way to look for them one after another?
int main()
{
int N,coin;
bool hasOne;
cout << "Enter the value N to produce: " << endl;
cin >> N;
cout << "Enter number of different coins: " << endl;
cin >> coin;
int *S = new int[coin];
cout << "Enter the denominations to use with a space after it" << endl;
cout << "(1 will be added if necessary): " << endl;
for(int i = 0; i < coin; i++)
{
cin >> S[i];
if(S[i] == 1)
{
hasOne = true;
}
cout << S[i] << " ";
}
cout << endl;
if(!hasOne)
{
int *newS = new int[coin];
for(int i = 0; i < coin; i++)
{
newS[i] = S[i];
newS[coin-1] = 1;
cout << newS[i] << " ";
}
cout << endl;
cout << "1 has been included" << endl;
}
//system("PAUSE");
return 0;
}
You could implement it with std::vector, then you only need to use push_back.
std::sort can be used to sort the denominations into descending order, then it's just a matter of checking whether the last is 1 and adding it if it was missing. (There is a lot of error checking missing in this code, for instance, you should probably check that no denomination is >= 0, since you are using signed integers).
#include <iostream> // for std::cout/std::cin
#include <vector> // for std::vector
#include <algorithm> // for std::sort
int main()
{
std::cout << "Enter the value N to produce:\n";
int N;
std::cin >> N;
std::cout << "Enter the number of different denominations:\n";
size_t denomCount;
std::cin >> denomCount;
std::vector<int> denominations(denomCount);
for (size_t i = 0; i < denomCount; ++i) {
std::cout << "Enter denomination #" << (i + 1) << ":\n";
std::cin >> denominations[i];
}
// sort into descending order.
std::sort(denominations.begin(), denominations.end(),
[](int lhs, int rhs) { return lhs > rhs; });
// if the lowest denom isn't 1... add 1.
if (denominations.back() != 1)
denominations.push_back(1);
for (int coin: denominations) {
int numCoins = N / coin;
N %= coin;
if (numCoins > 0)
std::cout << numCoins << " x " << coin << '\n';
}
return 0;
}
Live demo: http://ideone.com/h2SIHs

Why is my function not working properly

My function that checks if numbers in the vector are even or odd doesn't work properly.
This function prints the numbers that i have typed in the vector and puts them in 2 categories EVENS/ODDS. But if i have a negative number there is a problem with the odds not printing it but evens work.
problematic code is here:
void printEvensAndOddsVector(const vector <int>& new_v1)
{
cout << "Vector Evens: ";
for (unsigned int i = 0; i < new_v1.size(); ++i)
{
if (new_v1.at(i) % 2 == 0)
{
cout << new_v1.at(i) << " ";
}
}
cout << " \n";
cout << "Vector Odds: ";
for (unsigned int i = 0; i < new_v1.size(); ++i)
{
if (new_v1.at(i) % 2 == 1) // Here is the problem.
{
cout << new_v1.at(i) << " ";
}
}
cout << " \n";
}
Or more exactly this line: if (new_v1.at(i) % 2 == 1)
It prints the numbers that are odd but only the positive ones not the negative ones.
But if i change it to if (new_v1.at(i) % 2 != 0) then it works correctly.
Why does that happen and is there a problem with the equal operator?
If yes then why are the evens getting printed even if they are negatives while still using the equal operator?
Code here for reference.
clude <iostream>
#include <vector>
using namespace std;
void fillVector(vector <int>&);
void printVector(const vector <int>&);
void printEvensAndOddsVector(const vector <int>&); // Prints Evens and Odds.
int main()
{
vector <int> v1;
fillVector(v1);
printVector(v1);
printEvensAndOddsVector(v1);
cout << "\n\n\n";
system( "pause");
return 0;
}
// Function Definitions
void fillVector(vector <int>& new_v1)
{
int number;
cout << "Type in numbers and type -100 to stop: ";
cin >> number;
while (number != -100)
{
new_v1.push_back(number);
cin >> number;
}
}
void printVector(const vector <int>& new_v1)
{
cout << "\nVector: ";
for (unsigned int i = 0; i < new_v1.size(); ++i)
{
cout << new_v1.at(i) << " ";
}
cout << " \n";
}
void printEvensAndOddsVector(const vector <int>& new_v1)
{
cout << "Vector Evens: ";
for (unsigned int i = 0; i < new_v1.size(); ++i)
{
if (new_v1.at(i) % 2 == 0)
{
cout << new_v1.at(i) << " ";
}
}
cout << " \n";
cout << "Vector Odds: ";
for (unsigned int i = 0; i < new_v1.size(); ++i)
{
if (new_v1.at(i) % 2 == 1)
{
cout << new_v1.at(i) << " ";
}
}
cout << " \n";
}
This line: if (new_v1.at(i) % 2 == 1). It prints the numbers that are odd but only the positive ones not the negative ones.
For negative n, n % 2 returns either 0 or -1 in C++. It never returns 1, so the condition cannot be true for negative inputs.
As you've discovered, comparing to zero would work.
See Modulo operator with negative values

C++ Sum of factorial -Request 2nd code

I would like to analyze the complexity of my code algorithm.Therefore,i must have 2 different programs giving the same functions to allow me to start off.
Currently this is my own code.
I'm not sure if it is allowed that i would like to have someone that could volunteer his own way code to compute summation of factorial for me as the 2nd program code.
Preferrably a nested loop.
#include <iostream>
using namespace std;
int main()
{
int val;
int i;
int a = 0;
int c = 1;
cout << "Please enter a number: ";
cin >> val;
cout << endl;
for (i = 1; i <= val; i++)
{
c = c * i;
a = a + c;
}
cout << "The sum of the factorials is " << a << endl;
system("pause");
return 0;
}
#include <iostream>
using namespace std;
int main()
{
int val;
cout << "Please enter a number: ";
cin >> val;
cout << endl;
static const int results[] = {
0, 1, 3, 9, 33, 153, 873, 5913, 46233, 409113,
4037913, 43954713, 522956313
};
cout << "The sum of the factorials is " << results[val < 0 ? 0 : val] << endl;
system("pause");
return 0;
}
Note that I replicated the defect in the original program which causes it to return the incorrect value if the user enters 0.
This alternate version assumes 32-bit integers because it takes advantage of overflow behavior. Extending to 64-bit integers is left as an exercise.
I do not understand what you do with another nested way but i hope this can help...
#include <iostream>
using namespace std;
int main()
{
int val;
int i;
int a = 0;
int c = 1;
cout << "Please enter a number: ";
cin >> val;
cout << endl;
for (i = 1; i <= val; i++){
c *= i;
a += c;
}
int c2=1;
for (i = val; i > 1; i--){
c2*=i;
c2++;
}
cout << "The sum of the factorials is " << a << endl;
cout << "The sum of the factorials is " << c2 << endl;
system("pause");
return 0;
}
#include <iostream>
using namespace std;
int main()
{
int suma = 0;
int n = 0;
cout << "Sum of factorials\n";
cout << "-------------------------------\n";
cout << "Insert number of n: ";
cin >> n;
int i = 1;
while (i <= n)
{
int factorial = 1;
for(int j=1; j<=i; j++)
{
factorial = factorial * j;
}
suma += factorial;
i++;
}
cout << "Sum of factorials is: " << suma;
system("pause");
return 0;
}