Kardo Kamal Kardo Kamal - 28 days ago 6
C++ Question

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

Answer

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

}
Comments