I am stuck on this really simple program in C++, where I let the user know the number she/he have entered is prime or not, but, because of some reason, everything works fine during the first loop but things go fishy during the second. I would be more than happy if anyone could help ?
#include <iostream>
using namespace std;
int main(int argc, const char* argv[])
{
int number1 = 5;
int number;
int a = 0;
while (number1 == 5)
{
int b = 1;
cout << "Enter your number and we'll tell you if it's prime or not: ";
cin >> number;
while (a <= number)
{
a++;
if (number % a == 0)
b++;
}
if (b == 3)
cout << "Your number is prime" << endl;
else
cout << "Your number is not prime" << endl;
}
}
The are several problems with your program.
The first one is that the loop starting with statement
while (number1 == 5)
is infinite because number1 is not changed within the loop.
The second one is that you must always initialize variable a to zero within the loop. And it should be defined also within the loop because it is not used outside the loop. The same is valid for variable number.
Take into account that a number is prime if it is divisble by 1 and itself (except number 1). So I would initially set variable b to zero and compare it with 2. It is more clear than to compare it with 3.
The program can look the following way
#include <iostream>
int main()
{
while ( true )
{
std::cout << "Enter your number and we'll tell you if it's prime or not (0-exit): ";
unsigned int number = 0;
std::cin >> number;
if ( number == 0 ) break;
unsigned int n = 0;
unsigned int divisor = 0;
while ( divisor++ < number )
{
if ( number % divisor == 0 ) n++;
}
if ( n == 2 )
std::cout << "Your number is prime" << std::endl;
else
std::cout << "Your number is not prime" << std::endl;
}
}
You missed to reinit a to 0 before the inner while.
This makes it work. However, I suggest you take time to learn to code. It does not look educated.
Also your program won't exit. Not sure what your intention is, but you could omit the number1 variable and simply use while(1) (considering your code stands as is; probably you are at the beginning of your development though, so it depends).
#include <iostream>
using namespace std;
int main(int argc, const char* argv[])
{
int number1 = 5;
int number;
int a = 0;
while (number1 == 5)
{
int b = 1;
cout << "Enter your number and we'll tell you if it's prime or not: ";
cin >> number;
a = 0; <-- Reset to 0 would make it work
while (a <= number)
{
a++;
if (number % a == 0)
b++;
}
if (b == 3)
cout << "Your number is prime" << endl;
else
cout << "Your number is not prime" << endl;
}
}
P.S.: You are new to StackOverflow. So you likely take the answer and get away. Please consider accepting the answer. It's a respectful practice when it solved your issue.
Related
I just finished coding a small function for a school project and got the right answer. However, after adding a do-while loop (as it is required), I started running into issues. The first loop works just fine and I get the right answer (i.e., if I input 20 into the function, it outputs 210 which is correct), but if I input that same number or a different one, the number adds ON to the previous total (so if I added 1, then the "total" for that would be 211). I want each loop to find the total, output that total, and then when a new loop occurs, starts fresh. How do I fix this?
#include <iostream>
using namespace std;
int n, total = 0; /* Global variables since I only have to declare it once rather than two times! */
int sum(int n);
// Recursive version to calculate the sum of
// 1 + 2 + .... + n
int main()
{
char choice;
do {
cout << "Enter a positive integer:";
cin >> n;
sum(n);
cout << "The sum of 1+...+" << n << " is: " << total << endl;
cout << "Would you like to try another entry (Y/N): ";
cin >> choice;
}while(choice == 'Y' || choice == 'y');
cout << "Goodbye!" << endl;
return 0;
}
int sum(int n){
if(n == 0)
{
return total;
}
else
{
total = total + n;
return sum(n-1);
}
}
You could try the following code for sum:
int sum(int n) {
if (n == 1) {
return 1;
} else {
return n + sum(n - 1);
}
}
When I run the program for an even number less than 5, It prints out the error message but it also gives me the factorial. I don't want the factorial. Here's the code, how do I correct it?
#include <iostream>
using namespace std;
int main()
{
int number, factorial = 1;
cout << "Enter an even number between 5 & 15 to find it's factorial: ";
cin >> number;
if(number % 2 == 0) {
while(number < 5) {
cout << "Error! Enter an even number greater than five: ";
break;
}
while(number > 15) {
cout << "Error! Enter an even number less than fifteen: ";
break;
}
for(int a = 1; a <= number; a++) {
factorial = factorial * a;
}
cout << "factorial of " << number << " is " << factorial;
}
else {
cout << "Error!Enter an even number between 5 & 15 to find it's "
"factorial: ";
}
return 0;
}
This answer shows some corrections to be in your code and provide a working piece of code.
Corrections:
Not a very good idea to write everything in the main function. Try to follow SOLID principles where S stands for single responsibility. Which tells that functions must be small and do exactly one thing. And in your code, you have defined a very big function which does a lot of things.
Avoid nested loops. In your example, you have an if , inside which you have while, while and inside while you have for. This looks messy and is not readable.
Try to be clear in your expression of code, such that when a person reads they understand the flow of data.
Break is something that comes out of a while loop, but it does not mean it will exit the function. So in your example,
while(number<5){
std::cout<<"Error! Enter an even number greater than five: ";
break;
}
After it comes out of this loop, it will go to the next line which is another while loop and then goes on to calculate the function.
Try to use uniform initialization. Instead of int i = 0 use int i{0}. You can read more about uniform initialization on google.
Try not to use "using namespace std or anything else". Very bad practice.
Working piece of code:
bool check_value(int number){
int range = (number < 5 || number > 15) ? false : true;
int even = (number % 2 == 0) ? true : false;
if(range & even){
return true;
}
else{
std::cout << "Error! Please input even number between 5 & 15\n";
return false;
}}
int main(){
int number,factorial=1;
std::cout<<"Enter an even number between 5 & 15 to find it's factorial: \n";
std::cin >> number;
if(check_value(number)){
for (size_t a{1}; a <= number; a++){
factorial = factorial*a;
}
std::cout<<"factorial of " << number <<" is " << factorial << "\n";
}
return 0;
}
As Karl pointed out in the comments, the break statement will break out of exactly one loop, in this case a while loop, and the code outside of the loop will continue to execute.
Also, as Damien pointed out, you need to use a long long int to compute the factorial since the result can exceed the max size of the int datatype.
You could also reformulate your code to make it more readable, something like this:
#include <iostream>
/* Checks if number is valid and can throw error msg */
bool isValidNumber(int num) {
if(num % 2 != 0 || num < 5 || num > 15) {
std::cout << "Error! The number entered is not valid." << std::endl;
return false;
}
return true;
}
/* Calculates factorial and prints its value */
void calculateFactorial(int num) {
long long int factorial = 1;
for(int a = 1; a <= num; a++) {
factorial = factorial * a;
}
std::cout << "factorial of " << num << " is " << factorial << std::endl;
}
int main()
{
int number;
bool isValid;
do {
std::cout << "Enter an even number between 5 & 15 to find it's factorial: ";
std::cin >> number;
isValid = isValidNumber(number);
if(isValid) {
calculateFactorial(number);
}
} while(!isValid);
return 0;
}
Note: Using using namespace std; is considered bad practice because of the possibility of method collisions between a method or methods in the std namespace and methods of some other nanmespace you might create down the road.
// cai.cpp (Computer Assisted Instruction)
// This program uses random number generation to assist students learn multiplication
#include <iostream>
#include <iomanip>
#include <cstdlib> // contains prototypes for srand and rand
#include <ctime>
#include <cctype>
using namespace std;
int main() {
int question();
string status;
int score{0};
cout << "\nThis program will present you with 10 multiplication problems\n"
<< "enter the correct answer after the prompt\n"
<< "Enter Y for YES and N for NO\n"
<< "Do you want to try a game?";
cin >> status;
while(status == "Y" || status == "y") {
for(int x{0}; x < 11; x++) {
question();
score = score + question();
}
// report total score
cout << "\nTotal score is " << score << " out of 10";
cout << "\nWould you like to play again?";
cin >> status;
if(status == "n" || status == "N") {
break;
}
}
cout << endl;
}
int question() {
string responses();
// use srand to generate the random nmber for the various problems
srand(static_cast<unsigned int> (time(0)));
int number1 = 1 + rand() % 12; // initialize random number
int number2 = 1 + rand() % 12; // initialize random number
int total = number1 * number2;
int response;
int score{0};
cout << "\nWhat is " << number1 << + " times " << + number2 << + " ?";
cin >> response;
while (response != total) { // while answer is wrong, repeat question and wait for response
cout << " \nThat is incorrect, try again: ";
cin >> response;
}
if ( response == total) {
cout << responses();
score++; // increment score after each correct answer
}
return score;
}
string responses() {
string res1 = "Well done, that is correct!\n";
string res2 = "Congratulations, that is very accurate!\n";
string res3 = "Wow!, I'm impressed\n";
string res4 = "You're doing great! Keep up the good work.\n";
srand(static_cast<unsigned int> (time(0)));
int select{1 + rand() % 4};
switch(select) {
case 1: return res1;
break;
case 2: return res2;
break;
case 3: return res3;
break;
case 4: return res4;
break;
default: return " ";
}
}
When I compile and run this program, I expect it to loop only 10 times but it loops more than 10 times, I'm thinking it has to do with the switch statement in the responses function but I do not understand why it should be causing a problem. Any explanation would be greatly appreciated. I have modified the while loop condition in the main function to loop different times but it always loops to display all the possible responses in the switch statement. Screen shot of results attached, I modified the while statement to loop only twice but I still had all my responses showing so it ended up looping 4 times.
expect it to loop only 10 times but it loops more than 10 times
In your loop:
for(int x{0}; x < 11; x++)
x goes from 0 to 10, so it loops 11 times.
A few things to note. Your for loop goes up to < 11, meaning 10. So x from 0 to 10 (inclusive) is actually 11 times. You need to change the condition to < 10, or change x to start at 1.
Second issue, inside the for loop, you are actually calling the question function twice; with the first call's result being ignored. This is why you are getting 4 questions, each answered correctly, but only a score of 2.
Third, not so much an issue, but a bit redundant. At the end of the while loop, you check status == "n" || status == "N", however, this is unnecessary, since the while loop's condition checks for y and Y already.
I've cleaned up your while loop a bit here:
while(status == "Y" || status == "y") {
for(int x = 0; x < 10; ++x) {
score += question();
}
// report total score
cout << "\nTotal score is " << score << " out of 10";
cout << "\nWould you like to play again?";
cin >> status;
}
Unrelated thing to also clean up. You don't need to call srand in the question() function, instead just call it once in main. Also, since this is C++, you can use newer random generators from the <random> header.
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 was writing a code that calculates the two factors of any given number using two nested 'While' loops but after just one iteration the loop just stops
Program
#include <iostream>
#include <conio.h>
using namespace std;
long int Password;
void main()
{
long int n=2,n1=2;
cout<<"Type the number whose factor you need"<<endl;
cin>>Password;
while( n < 3600 )
{
while( n1 < 3600 )
{
if( n*n1 == Password )
{
cout<<"your Factors are "<<n<<" and "<<n1<<endl;
getch();
}
else
{
n1++;
break;
}
}
n++;
}
}
Output is only working for small numbers but when a little big numbers are inserted the program terminates. I am not understanding the problem as the code is perfectly fine. Am I having a less powerful processor?
Your program is not calculating the factors of any given number. Also, naming the number "Password" is confusing.
Maybe you want something like this in C++:
#include <iostream>
using namespace std;
int main() {
unsigned int number;
cout << "Enter a positive integer whose factors you need: " << endl;
cin >> number;
cout << "Factors of " << number << " are ";
for (int i = 1; i <= number; ++i) {
if (number % i == 0)
cout << i << " ";
}
cout << endl;
return 0;
}
As was noted in the comments, in C++ you have int main() not void main(), even though some compilers do support void main().