C++ Nested for loop and break - c++

I am new to computer science and had a quick question. I was trying to make a program that would take two integer inputs and print out all of the prime numbers in between them.
The problem I am having is that when I use break in the nested for loop. After it finds a prime number, it does not hit the nested for loop on the next go around of the outside for loop. Therefore, when searching for prime numbers between say 8 and 15, it will print out "11 12 13 14 15." It is correct at first but after finding a prime, it states that the rest of the bounded numbers are also primes.
#include <iostream>
using namespace std;
int main()
{
// Prime number finder:
cout << "Enter two numbers and I will find the prime numbers between them.\n\n";
int num1, num2, i = 2;
bool valid;
cout << "Enter the lower limit: ";
cin >> num1;
cout << endl << "Enter the higher limit: ";
cin >> num2;
if (num2 <= num1)
{
cout << "Enter a number that is larger than the lower limit./n";
}
if (num1 <= 1)
{
cout << "1 2 ";
num1 = 3;
}
else if (num1 == 2)
{
cout << "2 ";
num1 = 3;
}
for (num1; num1 <= num2; num1++)
{
valid = true;
for (i; i < num1; i++)
{
if ((num1 % i) == 0)
{
valid = false;
break;
}
}
if (valid == true)
cout << num1 << " ";
}
return 0;
}

The problem is that you don't reset the value of i. Change your loop to:
for (int i = 2; i < num1; i++)
And delete your earlier definition of i, since it's not needed at that point.
Even better, change the whole check of whether the number is prime to a separate funcion which returns a bool.
This should teach you to write functions with a single responsibility. Your function loops through a bunch of numbers, and for each of them it checks whether it is a prime. This latter part belongs to a separate function. What is interesting is that your bug is highly unlikely to appear if you write the separate functions in the first place.

In the for loop below i is uninitialized, you have to set i=2, also set the upper bound as sqrt(num1).
for (i=2; i <= sqrt(num1); i++)
{
if ((num1 % i) == 0)
{
valid = false;
break;
}
}
To use sqrt() also include the following header file as follows,
#include<cmath.h>

Related

C++ program to calculate the factorial of even numbers between 5 and 15

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.

How do I determine the highest and lowest value using do while loops

I am currently stuck in my homework and the problem is that I need to create a program that will ask for 5 integer numbers from which I should determine the highest and lowest value. I am quite confused as of now, and my initial code is this:
#include<iostream>
using namespace std;
int main(){
int num1,num2,num3,num4,num5,min=0,max=0;
cout << " Enter 1st number : ";
cin >> num1;
cout << " Enter 2nd number : ";
cin >> num2;
cout << " Enter 3rd number : ";
cin >> num3;
cout << " Enter 4th number : ";
cin >> num4;
cout << " Enter 5th number : ";
cin >> num5;
do{
if(num1<num2 && num1<num3 && num1<num4 && num1<num5 ){
max = num1;}
if(num2<num1 && num2<num3 && num2<num4 && num2<num5 ){
max = num2;}
if(num3<num1 && num3<num2 && num3<num4 && num3<num5 ){
max = num3;}
if(num4<num1 && num4<num3 && num4<num2 && num4<num5 ){
max = num4;}
if(num5<num1 && num5<num3 && num5<num4 && num5<num2 ){
max = num2;}
}while(max>0);
cout << " The highest number is : " <<max;
return 0;
}
Any help would be appreciated. Thanks in advance!
You should store your numbers into a std::vector<int> or std::array and then use the std::minmax_element algorithm to obtain the largest and smallest number.
If you are allowed to use std::max and std::min, you can use:
max = std::max({num1, num2, num3, num4, num5});
min = std::min({num1, num2, num3, num4, num5});
to simplify the code in the loop.
This would be my solution without using arrays.
I'd suggest you to try it yourself before. You don't learn when you just copy code.
#include <iostream>
int main() {
int i=0, num, min=INT_MAX, max=INT_MIN;
do {
std::cout << "Enter number: ";
std::cin >> num;
if (num < min) {
min = num;
}
if (num > max) {
max = num;
}
i++;
} while (i < 5);
std::cout << "The max number is: " << max << std::endl;
std::cout << "The min number is: " << min << std::endl;
return 0;
}
If you don't need to remember, you can loop for e.g. 5 times, then have a comparison before asking the next number.
so generally (idea, write it yourself and learn):
for (5 times)
ask user input, save as input
if largest number is null, then equal to input
else if largest number is smaller, then set input equal to largest number
Continue for loop times.
Rather than compare all the numbers each time. Simply compare your current smallest against the numbers in sequence.
int data[5];
// read numbers into data.
int min = data[0]; // Guess that number 0 is the smallst number.
// Now check if the guess is correct and update if you are wrong.
for(int loop = 0; loop < 5; ++loop)
{
// check if data[loop] is smaller than your current guess.
// if it is smaller than update your guess.
// when you have checked all the values exit the loop.
}
std::cout << "Smallest: " << min << "\n";
There is no need to use a loop to do this you can do that without it else if it's necessary to use a loop you must use an array or some other data structure

C++ Do-while loop stopping

I got an assignment where we make a cmd prompt show up and display a flashcard game for multiplication. After inputting a correct answer a prompt shows up and asks the user to go "Again? Y/N." after the second input answer the prompt to ask the user doesn't show up and it's stuck on a "congratulations" message. This happens when I write in code to randomly generate two numbers for the game twice. one outside the while loop, and one inside while loop. If I leave one out the 2nd code for the random numbers it will run fine but will only display the same numbers over again. what I'm asking is how do I fix it so that it won't get stuck after the second answer input?
sample code below:
#include <iostream>
using namespace std;
int main()
{
int num1, num2, ans, guess, count = 0;
char choice;
num1 = rand() % 12 + 1;
num2 = rand() % 12 + 1;
//first number generator.
ans = num1 * num2;
do
{
{
cout << num1 << " X " << num2 << " = ";
cin >> guess;
cout << "Wow~! Congratulations~! ";
count++;
num1 = rand() % 12 + 1;
num2 = rand() % 12 + 1;
//second number generator.
} while (guess != ans);
cout << "\nAgain? Y/N: ";
cin >> choice;
} while ((choice == 'y') || (choice == 'Y'));
//after two turns the loop stops. Can't make a choice.
cout << " Thanks for playing! Number of tries:" << count << endl;
return 0;
}
I'd guess the problem is because your loops aren't quite what you think they are.
do
{
The code above has started a do loop.
{
I suspect you intended to start another (nested) do loop here--but you left off the do, so it's just a block that gets entered, executed, and exited. Useless and pointless in this case.
cout << num1 << " X " << num2 << " = ";
cin >> guess;
cout << "Wow~! Congratulations~! ";
count++;
num1 = rand() % 12 + 1;
num2 = rand() % 12 + 1;
//second number generator.
} while (guess != ans);
You've formatted this as if the while were closing the nested do loop--but since you didn't actually create a nested do loop, this is just a while loop with an empty body. Its meaning would be more apparent with a little re-formatting:
// second number generator
}
while (guess != ans)
/* do nothing */
;
The problem can be found here:
do
{
{
cout << num1 << " X " << num2 << " = ";
cin >> guess;
As you can see, the second scope has no do statement. As a result it is only a codeblock.
You can solve it by writing a do statement for the second code block.
Because the do is not present in the second bracket ({), the while is interpreted as a while loop:
while (guess != ans);
or
while (guess != ans) {
}
this thus keeps looping until guess is not equal to ans. But since in the loop does not modify any of the two variables, the loop will keep iterating.
Other errors: note that the program is still incorrect, since it will claim you have answered the question, regardless of the answer. You can fix it by implementing this as follows:
int main()
{
int num1, num2, ans, guess, count = 0;
char choice;
do {
num1 = rand() % 12 + 1;
num2 = rand() % 12 + 1;
ans = num1 * num2;
do {
cout << num1 << " X " << num2 << " = ";
cin >> guess;
if(guess == ans) {
cout << "Wow~! Congratulations~! ";
} else {
cout << "No, wrong!\n";
}
count++;
} while (guess != ans);
cout << "\nAgain? Y/N: ";
cin >> choice;
} while ((choice == 'y') || (choice == 'Y'));
//after two turns the loop stops. Can't make a choice.
cout << " Thanks for playing! Number of tries:" << count << endl;
return 0;
}

"Prime or not" program

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.

Summming odd and even numbers in an undetermined range

My assignment is to create a program in which the user inputs a starting value and ending value. The program should then sum all the numbers within that range. In addition it should sum the odd numbers and the even numbers. My issue is determining which numbers in the users range is odd and which is even and then summing these values. The total sum loop works but I have tried multiple other loops for the odd and even sums and have had no success. So if someone could help me sum these numbers based on whether there even or odd.
#include <iostream>
using namespace std;
int main()
{
int sum = 0, start, endnumber;
int sumall = 0, c=0;
cout << "Please enter the starting integer\n";
cin >> start;
cout << "Please enter the ending integer\n";
cin >> endnumber;
while (endnumber <= start)
{
cout << "Please enter the starting integer\n";
cin >> start;
cout << "Please enter the ending integer\n";
cin >> endnumber;
}
while (start <= endnumber)
{
sumall = sumall + start;
++start;
}
std::cout << "The sum is: " << sumall << std::endl;
return 0;
}
You need to check each number in the range with modulo.
For ex:
if( start%2 == 0 ) // even
{
evenSum+=start;
}
else // Odd
{
oddSum+=start;
}
That will do the job.
You can test for odd numbers by anding with 1.
if ((start & 1) == 0)
evenSum += start;
else
oddSum += start;
Small note when talking to mathematicians: don't use modulo and modulus interchangeably (even though wikipedia says they are the same):
modulo is % for positive numbers.
modulus is the abs function.