I'm currently taking C++ and one my assignments is to create a program that checks if the number is a prime number correctly handle the invalid
integer inputs. In addition, user should be able to test as many integers as he or she wants in a single run. In other words, the program should not end unless the user tells you to.
I understand the prime number check part but I cannot figure out to implement the "test as many integers as you want in a single run and handling invalid input"
Any comments and edits to the code would be greatly appreciated. Thank you!
using namespace std;
int main () {
int num, i, count = 0;
cout << "Enter the number to be checked : ";
cin >> num;
if (num == 0)
{
cout << "\n" << num << " is not prime";
exit(1);
}
else {
for(i=2; i < num; i++)
if (num % i == 0)
count++;
}
if (count > 1)
cout << "\n" << num << " is not prime.";
else
cout << "\n" << num << " is prime.";
return 0;
}
Here is the code that you can try. After input the number, the program will ask whether you want to continue or not by inputting y or n.
If the user input y, the program will keep looping and ask the question again otherwise it will break the loop.
Last note : don't use using namespace std (bad habit)
#include <iostream>
#include <string>
int main () {
int num, i, count = 0;
char flag;
while(1)
{
std::cout << "Enter the number to be checked : ";
std::cin >> num;
if (num == 0)
{
std::cout << "\n" << num << " is not prime";
}
else {
for(i=2; i < num; i++)
if (num % i == 0)
count++;
}
if (count > 1)
std::cout << "\n" << num << " is not prime."<<std::endl;
else
std::cout << "\n" << num << " is prime."<<std::endl;
std::cout <<"Do you want to continue? [y/n]";
std::cin >> flag;
if (flag == 'n')
break;
}
return 0;
}
Of course, you can change the y/n to another char or string or int or whatever you want
Related
The loop is not reacting properly when an input outside the parameters is put in. It should only accept 0-9, but I can put any number positive or negative in and it outputs it as is.
I've tried setting the int count to null and 0 on the 4th line, thinking null might allow the while loop which originally said 'while count < 0 or count > 9'. Even at null it skipped the whole loop entirely and didn't allow for any inputs. I set it this way thinking it would loop through as the count is set to 0, but it seems to skip the conditions inside. This is a small function inside a larger lottery program.
void human(int user[], int size) {
const int SIZEOF = 5;
cout << "Enter your 5 lottery number picks.\n";
int count = 0;
while (count == 0) {
if (count >= 0 and count <= 9)
for (count = 0; count < SIZEOF; count++)
{
cout << "Number " << (count + 1) << ": ";
cin >> user[count];
}
else
{
cout << "You must enter 0-9: ";
cin >> user[count];
}
}
}
//EDIT: Here is the code I used based on it being pointed out I was using the //counter
void human(int user[], int size) {
const int SIZEOF = 5;
cout << "Enter your 5 lottery number picks.\n";
for (int count = 0; count < SIZEOF; count++)
{
cout << "Number " << (count + 1) << ": ";
cin >> user[count];
while (user[count] < 0 || user[count] > 9)
{
cout << "You must enter a number between 0 and 9: ";
cin >> user[count];
}
}
}
problems:
your function is missing an output/return value
your outer loop makes no sense
you check count instead of input
you read into a (potentially) out of bounds array
solutions:
use std::vector instead of array
think about input and output of your function
fix input and loops
example:
#include <iostream>
#include <string>
#include <vector>
std::vector<int> lotteryInput(uint32_t count)
{
std::vector<int> numbersPicked;
std::cout << "Enter your " << count << "lottery number picks.\n";
while(numbersPicked.size() < count)
{
int pick;
std::cout << "Number " << numbersPicked.size()+1 << ": ";
std::cin >> pick;
if ((pick >= 0) && (pick <= 9))
{
numbersPicked.push_back(pick);
}
else
{
std::cout << "You must enter 0-9: \n";
}
}
return numbersPicked;
}
int main()
{
auto numbersChosen = lotteryInput(5);
std::cout << "picked numbers: ";
for(const auto& num : numbersChosen)
{
std::cout << num << ", ";
}
}
i was wondering what can I do to prompt an error when I input a negative number. I used a for loop for this program. What this program does, or at least its supposed to do, is to output the factor of any given number (if positive). But I am not sure how to make my code to prompt an error or at least keep asking for a number if the number that input is less or equal to 0.
I used the variable n as the number to input by the user.
I am really new to programming and I am eager to finish this program as soon as possible. Can you please assist?
#include <iostream>
#include <math.h>
#include <stdlib.h>
using namespace std;
int main()
{
double n;
cout << "Welcome to this program... Hope you like it" << flush << endl;
do
{
int i, fact = 1, n;
cout << "Please enter a value for the variable " "n: ";
cin >> n;
for (i = 1; i <= n; i++) {
fact = fact * i;
}
cout << "Factorial of " << n << " is: " << fact << endl;
cout << " Thanks for using this program... hope you liked it!" << endl;
} while (n >= 0);
return 0;
}
Commens in the code:
#include <iostream>
// it's best not to do using namespace std. It's a huge namespace
int main()
{
std::cout << "Welcome to this program... Hope you like it\n";
do
{
int i, fact = 1, n;
std::cout << "Please enter a value for the variable " "n: ";
std::cin >> n;
// if std::cin is in a failed state then break out of the loop.
if (std::cin.fail()) break;
// added check if n<0. if n<0 ptint error on stderr
if (n<0) {
std::clog << "Error: you must supply a number equal to or greater than zero\n";
} else { // if n>=0
for (i = 1; i <= n; i++) {
fact = fact * i;
}
std::cout << "Factorial of " << n << " is: " << fact << "\n";
}
} while (true); // <- now always true
std::cout << "\nThanks for using this program... hope you liked it!\n";
return 0;
}
I'm making a simple guessing game program. The user enters a value out of 100 and the program tells the user if their guess is too high or low. I want to make it so the program lets the user know that they've already entered that current number in previously. How would I implement a loop into my program that would take the users guess and compare it to the array list to look for duplicate values?
#include <ctime>
#include <iostream>
#include <iomanip>
using namespace std;
#include <cstdlib>
int main()
{
srand(time(0));
const int SIZE = 100; //array
int number[SIZE];
int i;
int numb = rand() % 100; //rng
cout <<"Hint: "<< numb << endl;
cout << " " << endl;
cout << "I'm thinking of a number between 1 and 100. Guess what it is: ";
for (i = 0; i < SIZE; i++)
{
cin >> number[i];
if (number[i] == numb)
{
cout << "Correct! It's " << numb << endl; //if user guesses correct
break;
}
else if (number[i] < numb) //if user guesses too low
{
cout << "That's too low! guess again: " ;
}
else if (number[i] > numb) //if user guesses too high
{
cout << "That's too high! guess again: " ;
}
}
}
Create a vector for already typed values:
vector <int> atyped;
Create a function to check and return true or false:
int check(int entered_value, vector <int> atyped) {
ret=0;
for (int i=0;i<atyped.size();i++){
if (enterd_value==atyped[i])
ret=1;
}
return ret;
}
Then all you have to do is:
if (check(number[i])!=0)
cout << "Sorry, you already tried that one!" <<endl;
Hope this can at least give you an idea as to how to solve your problem ;)
Use std::find
for (i = 0; i < SIZE; i++)
{
cin >> number[i];
if (number[i] == numb)
{
cout << "Correct! It's " << numb << endl; //if user guesses correct
break;
}
else if (std::find(number, number + i, number[i]) != number + i)
{
cout << "You already guessed that! guess again: " ;
}
else if ... // existing higher or lower
}
The range of pointers [number, number + i) is all the previous guesses. find returns the first matching pointer, or the end (number + i) if there is no match.
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
I'm a relatively new learner to C++ and I've been having some trouble. If you guys read the title, this is a homework problem (just letting you guys know out there) and I'm not really sure as to where my error is. Using GIT Bash, I can't see why this isn't compiling (or maybe i just don't know how to read it). I feel like i've touched upon all the bases and would appreciate a quick look over to see if my mistake is blaringly obvious. I've done a couple looks through stackoverflow and so the inputting values into a vector was used from another post but i've modified it a bit. In addition, I added in a sort for the vector from smallest to largest.
Also, how can I change the for statement to allow for variable #'s in the vector?
#include <iostream>
#include <vector>
using namespace std;
double showMedian(const vector<int> & vecmedian, int size)
{
int middle;
double average, median;
middle = size / 2.0;
if (size % 2 == 0)
{
median = (vecmedian[middle] + vecmedian[middle + 1]) / 2.0;
cout << "The median is: " << average << endl;
}
else
{
median = vecmedian[middle + 0] / 1.0;
cout << "The median is: " << median << endl;
}
return median;
}
int main()
{
int n,input, i;
vector<int> vecmedian;
vector<int>::iterator itr;
cout << "Enter the amount of numbers: ";
cin >> n;
cout << "Enter your numbers to be evaluated: " << endl;
while (vecmedian.size() < n && cin >> input){
vecmedian.push_back(input);
}
for(i = 1; i < 10; ++i){
for(itr = vecmedian.begin(); itr != vecmedian.end(); ++itr){
if(vecmedian[i] < *itr){
vecmedian.insert(itr, vecmedian[i]);
break;
}
}
if(itr == vecmedian.end())
vecmedian.push_back(vecmedian[i]);
}
showMedian();
return 0;
}
Point 1
When making function prototypes, you need to keep them consistent with the actual definition of the function.
You have:
void showMedian();
As a function-prototype but you have:
double showMedian(int *vecmedian, int size)
As the actual definition. They both need to be consistent.
Since you have not declared an array, maybe change the parameters of showMedian to:
double showMedian(const vector<int> & vecmedian, int size)
Point 2
if(nums[i] < *itr)
Where is nums declared?
Point 3
If you want to use the definition of showMedian, then use the parameters that it uses assuming you made the changes above (and assuming n is size).
showMedian(vecmedian, n);
Edit
With all the consulting in the comment section and the new updated OP Question, here is a fairly solid program which finds the median in a vector:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
double showMedian(const vector<double> & vecmedian, int num);
int main()
{
unsigned int n;
double input;
vector<double> vecmedian;
// cout << "Enter the amount of numbers: ";
do {
cout << "Enter the amount of numbers: ";
while(!(cin >> n)){
cout << "Wrong input" << endl;
cout << "Enter the amount of numbers: ";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
if (n == 0)
{
cout << "Invalid, size must be greater than 0" << endl;
}
} while (n == 0);
// cout << "Enter your numbers to be evaluated: " << endl;
for (int i = 1; i <= n; ++i)
{
cout << "Enter number here (" << ((n + 1) - i) << " number/s remaining): ";
while(!(cin >> input)){
cout << "Wrong input" << endl;
cout << "Enter number here (" << ((n + 1) - i) << " number/s remaining): ";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
vecmedian.push_back(input);
}
// while (vecmedian.size() < n && cin >> input){
// vecmedian.push_back(input);
// }
sort(vecmedian.begin(), vecmedian.end());
showMedian(vecmedian, vecmedian.size());
return 0;
}
double showMedian(const vector<double> & vecmedian, int num)
{
int middle;
double median;
middle = (num / 2);
if (num % 2)
median = vecmedian[middle];
else
median = (vecmedian[middle - 1] + vecmedian[middle]) / 2.0;
cout << "The median is: " << median << endl;
return median;
}