I am trying to write a program that accepts inputs of even numbers until the user enters a odd number then it stops and adds all the even inputs.
The problem I am having is that I'm intending to use an if statement to determine if the number is even or not but once the program has run I need it to run again so the user can keep inputting numbers until they input a odd one.
Here's what I have so far:
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
int value;
cout << "Please enter a possitive number: ";
cin >> value;
if (value%2 == 0) { // divides the value entered by 2 too determine whether or not its even.
cout << "Please enter another even number: ";
}
else
{
}
cin.get();
return 0;
}
You need a loop in order to ask for input again in case the value is even.
You will enter the while loop only if value is even. And you will loop until value input is even.
You then need another int which represents the sum and add the value to the sum each time you enter the loop (each time you have an even number)
Note that with this solution you don't need an if statement. The condition is in the while loop
#include <iostream>
using namespace std;
int main()
{
int value;
int sum=0;
cout << "Please enter a possitive number: "<<endl;
cin >> value;
while (cin && value%2 ==0){
sum+=value;
cout << "Please enter another even number: "<<endl;;
cin >> value;
}
cout<<"Sum of even number: "<<sum<<endl;
return 0;
}
Just do it.
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int value;
vector<int> inputs;
cout << "Please enter a possitive number: ";
while (cin >> value) { // loop while successfully read an integer
if (value%2 == 0) { // divides the value entered by 2 to determine whether or not its even.
inputs.push_back(value);
cout << "Please enter another even number: ";
}
else
{
break; // get out of this loop
}
}
// add all the even inputs
int sum = 0;
for (vector<int>::iterator it = inputs.begin(); it != inputs.end(); it++) {
sum += *it;
}
cout << sum << endl;
return 0;
}
Alternatively, you can do the addition inside the loop.
#include <iostream>
using namespace std;
int main()
{
int value;
int sum = 0;
cout << "Please enter a possitive number: ";
while (cin >> value) { // loop while successfully read an integer
if (value%2 == 0) { // divides the value entered by 2 to determine whether or not its even.
sum += value;
cout << "Please enter another even number: ";
}
else
{
break; // get out of this loop
}
}
cout << sum << endl;
return 0;
}
something like this?
int value;
bool run = true;
cout << "Please enter a possitive number: ";
while(run)
{
cin >> value;
if (value%2 == 0) { // divides the value entered by 2 too determine whether or not its even.
cout << "Please enter another even number: ";
}
else
{
run=false
}
}
It is sudo code modeled similar to your loop, so not the best way, also most likely there might be syntax error, but should give you an idea
one more way to check whether it is even or odd is to check lowest bit:
#include <vector>
#include <iostream>
#include <algorithm>
int main()
{
int enteredValue = 0;
std::vector<int> result;
do {
std::cout<<"Please enter even number : ";
std::cin>>enteredValue;
result.push_back(enteredValue);
std::cout<<'\n';
}while(!(enteredValue & 0x01)); //check the lowest bit
std::for_each(result.begin(), result.end(), [](int x){ std::cout<<x<<' '; });
return 1;
}
Related
I am trying to implement random_function(), which outputs the amount of random numbers within a range (user input), and count_function() to count for the value that the user wants to look up in the outputted random numbers. I made the random numbers to be saved in an array called randomlist[] so that it can be used to count for the value from the outputted random numbers. However, I cannot declare an array without its fixed size in the header file and define its size in the count_function.cpp. So I cannot use randomlist[] in the count_function() without redefining it (which is meaningless...).
Is there a way to declare array without defining its size, in the header file?
Here is the source code:
header file:
#pragma once
using namespace std;
class Rand
{
public:
// Rand();
int range,min,max;
char key;
void Random_function();
void Count_function();
// randomlist[]; something like this, which that is not possible in c++
};
This is randomfunction.cpp:
#include <iostream>
#include "random_function.hpp"
using namespace std;
void Rand::Random_function()
{
beginning:
cout << "Enter amount of numbers to generate: ";
cin >> range;
if (range<=0 || cin.fail())
{
cout <<"Error! Please enter valid number and try again! "<<endl;
goto beginning;
}
else
{
reenter:
cout << "Enter minimum boundary: ";
cin >> min;
cout << "Enter maximum boundary: ";
cin >> max;
cout << "\n";
srand((unsigned)time(NULL));
if(max<min || cin.fail())
{
cout << "\nError! Please enter the valid value and try again! " << endl;
goto reenter;
}
else
{
int randomlist[range]; //I defined the size of the randomlist here but I want to use this outside of the random_fucntion() as well.
for(int i=0 ; i < range; i++)
{
randomlist[i] = min + (rand() % static_cast<int>(max - min + 1));
cout <<i+1<<". "<< randomlist[i] <<endl;
}
}
cout <<"\n"<< "Total random numbers generated: " << range<< endl;
cout <<"Do you want to continue? y/n"<<endl;
cin >> key;
if(key=='y')
{
Count_function();
cout <<"Do you want to restart? y/n"<<endl;
cin >> key;
if(key=='y')
{
goto beginning;
}
else
{
exit(0);
}
}
else
{
cout <<"Do you want to restart? y/n"<<endl;
cin >> key;
if(key=='y')
{
goto beginning;
}
else
{
exit(0);
}
}
}
}
void Rand::Count_function()
{
int n,count=0;
reenter2:
cout<<"Enter the value to count for: ";
cin>>n;
if(cin.fail())
{
cout<<"Please enter valid value to count for"<<endl;
goto reenter2;
}
else
{
for(int i=0 ; i <range; i++)
{
if(randomlist[i]==n)
{
count++;
}
}
}
cout <<"The number of '"<<n<<"'s in the given list is: "<< count <<endl;
}
main:
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <random>
#include "random_function.hpp"
using namespace std;
int main()
{
Rand call;
call.Random_function();
}
When you want to use an array, but the size cannot be known at compile-time, the generally accepted approach in C++ is to use a std::vector.
When running the code to solve for the counting operations the answer will always come out to 3 operations. Why does count always output 3 even when it does not fit the criteria?
#include <string>
#include <iostream>
using namespace std;
int main() {
string input1;
string input2;
cout << "Enter first number: ";
cin >> input1;
cout << endl;
cout << endl;
cout << "Enter second number: ";
cin >> input2;
int count = 0;
for (int i = 0; i < 3; i++) {
int thing = (input1.at(i) + input2.at(i));
if (thing > 9) {
count++;
}
}
cout << count;
return 0;
}
There is internal typecasting being done here. From char to int as the result is required is in integer format and addition is being done. Therefore actually ASCII values are being added. For '0' it is 48. Therefore everytime the sum is greater than 9. And hence output is 3. The answer here will provide a better insight.
For your question this is a better way to do it. (subtract '0' from each digit char), therefore actually internally it becomes ASCII(digit) - ASCII(0), which will give you the actual digit
#include <string>
#include <iostream>
using namespace std;
int main() {
string input1;
string input2;
cout << "Enter first number: ";
cin >> input1;
cout << endl;
cout << endl;
cout << "Enter second number: ";
cin >> input2;
int count = 0;
for (int i = 0; i < 3; i++) {
int thing = (input1.at(i)-'0') + (input2.at(i)-'0');
if (thing > 9) {
count++;
}
}
cout << count;
return 0;
}
If you are doing mathematical operation you must use appropriate types for the variables. Since you have used strings as variable type , it will not give correct result as desired. For the given code to work try this.
int input1;
int input2;
For more examples on user inputs in c++
The user will enter a list of numbers. The user should enter as many numbers as the user wishes. All the numbers should be stored in a variable, I am not trying to add them all up.
#include <iostream>
using namespace std;
int main()
{
// declare variables
double number,listOfNumbers;
bool condition;
cout << "Enter a starting number: ";
cin >> number;
condition = true;
while (condition)
{
if(number > 0)
{
cout << "Enter another number (type 0 to quit): ";
listOfNumbers = number;
cin>>listOfNumbers;
}
else
{
condition=false;
}
}
cout << listOfNumbers;
return 0;
}
Use a std:vector to hold the numbers, eg:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
// declare variables
double number;
vector<double> listOfNumbers;
cout << "Enter numbers (type 0 to quit): ";
while ((cin >> number) && (number != 0))
{
listOfNumbers.push_back(number);
}
for(number : listOfNumbers)
cout << number << ' ';
return 0;
}
Some small modifications and the use of a std::listor std::vector to store the values, the vector will grow dynamicly as you run the program and relocate if it runs out of space, the list will allocate space for every new item both works here.
I also never use using namespace std although it is very common in tutorials to do.
The syntax auto const &i in last for loops requires some of the later C++ standards it will give you a unmutable reference to the item.
#include <iostream>
#include <list>
int main() {
// declare variables
double number;
std::list<double> listOfNumbers;
bool condition;
std::cout << "Enter a starting number: ";
std::cin >> number;
condition = true;
while (condition) {
if (number > 0) {
listOfNumbers.push_back(number);
std::cout << "Enter another number (type 0 to quit): ";
std::cin >> number;
} else {
condition = false;
}
}
for (auto const &i : listOfNumbers) {
std::cout << i << std::endl;
}
return 0;
}
Please disregard some of the undeclared variables. I do not really know what is wrong.
#include <iostream>
using namespace std;
int main()
{
int number{}, tries{}, ans{}, count{};
cout << "Enter an integer greater than 0: ";
cin >> number;
while (number > 0){
ans = number / 10;
++count;
if (ans == 0){
cout << "The number has " << count << "digits";
break;
}
}
return 0;
}
You're never actually changing number, so every iteration, you set ans to the same thing and run the same test.
As indicated by others, you are not updating the loop variable (number) anywhere inside the loop. Hence it is very likely to get in an infinite loop. Here is a sample updated code you can try out.
#include <iostream>
using namespace std;
int main()
{
int number{}, tries{}, ans{}, count{};
cout << "Enter an integer greater than 0: ";
cin >> number;
if (number<=0){
cout << "Incorrect input.";
}
else{
while (number>0){
number = number / 10;
count ++;
}
cout << "The number has " << count << " digits";
}
return 0;
}
I am trying to do a modulus operation. I ask the user to input two numbers, since modulus only works with integers, I have a while loop that checks if the inputs are integers. Then the while loop ask the user to re-enter the two numbers. But the while loop keeps on repeating and does not allow the user a chance to re-enter the numbers. What will be the proper to go about doing this?
#include <iostream>
using namespace std;
int Modulus (int, int,struct Calculator);
struct Calculator
{
int per_numb1, per_numb2;
int per_Result; };
int main ()
{
Calculator Operation1;
cout << "\nPlease enter the first number to calculate as a modulus: ";
cin >> Operation1.per_numb1;
cout << "\nPlease enter the second number to calculate modulus: ";
cin >> Operation1.per_numb2;
while ( !( cin >> Operation1.per_numb1) || !( cin >> Operation1.per_numb2))
{
cout << "\nERROR\nInvalid operation \nThe first number or second number must be an integer";
cout << "\n\nPlease re-enter the first number to begin Modulus: ";
cin >> Operation1.per_numb1;
cout << "\nPlease re-enter the second number to begin Modulus: ";
cin >> Operation1.per_numb2;
}
Operation1.per_Result = Modulus(Operation1.per_numb1, Operation1.per_numb2, Operation1);
cout << "\nThe result is: " << Operation1.per_Result << endl;
}
int Modulus (int n1, int n2, struct Calculator)
{
int Answer;
Answer = n1 % n2;
return Answer;
}
Refactor to something like this:
#include <iostream>
#include <string>
#include <limits>
using namespace std;
class Calculator
{
public:
static int Modulus (int n1, int n2);
};
int Calculator::Modulus (int n1, int n2)
{
return n1 % n2;
}
int getInt(string msg)
{
int aa;
cout << msg;
cin >> aa;
while (cin.fail())
{
cin.clear();
cin.ignore(std::numeric_limits<streamsize>::max(),'\n');
cerr << "Input was not an integer!" << endl;
cout << msg;
cin >> aa;
}
return aa;
}
int main ()
{
int num1 = getInt("Enter first value: ");
int num2 = getInt("Enter second value: ");
int value = Calculator::Modulus(num1,num2);
cout << "Answer:" << value << endl ;
}
When the input parsing fails, invalid input data will remain in the stream. You need to
clear the stream error state by calling cin.clear().
and skip the remaining invalid input.
See the answer to this question.