Loop does not continue correctly - c++

I have been programming in C++ for the past 3 years, and I have always used the continue keyword in loops with success. But right now, a simple code of mine with continue is not working properly. Here is the code that is showing the problem:
int main()
{
int num = 2, result = 0;
while (num > 1 && num < 50)
{
if (num % 2 != 0)
{
result += num;
}
else
{
continue;
}
num++;
}
cout << "The result is: " << result << endl;
return 0;
}
As stated above, this does not print anything on the console. When I remove the else statement with continue in it, it successfully calculates the result and prints the said result. Does anyone have any idea why the given code is not working correctly (or why the loop in it does not break)? Any sound answer would be much appreciated.

Loop is indeed continuing (continue works properly) correctly
Initially, num = 2, so if condition fails and goes to else. So it will call continue. Then again the loop starts from the beginning with num = 2. This continues forever.
In short, num value is not changing and if condition always fails.

It's a very simple issue. Look at this block of code properly:
else
{
continue;
}
Due to continue, n++ is never called because due to the non-changing value of n, num % 2 != 0 is always false. This is resulting in an infinite loop.
So to fix this issue, just remove the above block of code:
#include <iostream>
int main()
{
int num = 2, result = 0;
while (num > 1 && num < 50)
{
if (num % 2 != 0)
{
result += num;
}
/*else
{
continue;
}*/
num++;
}
std::cout << "The result is: " << result << std::endl;
return 0;
}
Also, consider not using the following in your code:
using namespace std;
..as it's considered as a bad practice. For more info on this, look up why is "using namespace std" considered as a bad practice.

You just have to remove your else part because of no use and terminated cause of continue keyword.
int main()
{
int num = 2, result = 0;
while (num > 1 && num < 50)
{
if (num % 2 != 0)
{
result += num;
}
num++;
}
std::cout << "The result is: " << result << std::endl;
return 0;
}

Since continue is just a thinly disguised goto, rewriting the loop with explicit gotos might make it clearer:
start:
if (num > 1 && num < 50)
{
if (num % 2 != 0)
{
result += num;
}
else
{
goto start;
}
num++;
goto start;
}
Now you see clearly that num isn't incremented when num % 2 != 0 is false.
Just remove the else branch.

Related

How can I find prime reversed numbers?

I have to write a program to check if the entered number has these qualifications:
A number that is prime it self, the reverse of that number is also prime, and the number's digits are prime numbers too (Like this number: 7523).
If the needs meet, it has to show "yes" when you enter and run the program otherwise "no".
I know both codes for prime and reverse numbers but I don't know how to merge them.
This is the code:
#include <iostream>
#include <conio.h>
using namespace std;
void prime_check(int x) {
int a, i, flag = 1;
cin >> a;
for (i = 2; i <= a / 2 && flag == 1; i++) {
if (a % i == 0)
flag = 0;
}
if (flag == 1)
cout << "prime";
else
break;
}
int main() {
int a, r, sum = 0;
cin >> a;
while (a != 0) {
r = a % 10;
sum = (sum * 10) + r;
a = a / 10;
}
}
The program has to check each digit of the number entered to see if it is prime or not in every step, then show "yes", but it doesn't work.
Welcome to the site.
I don't know how to merge them.
void prime_check(int n) { /*code*/ }
I'd understand that you don't know how to use this.
It's very easy!
int main()
{
int i = 0;
prime_check(i);
}
If you are confused about how the program executes, you could use a debugger to see where it goes. But since using a debugger can be a bit hard at first, I would suggest to add debug prints to see how the program executes.
This line of code prints the file and line number automatically.
std::cout << __FILE__ << ":" << __LINE__ << "\n";
I'd suggest to add it at the start of every function you wish to understand.
One step further is to make it into a macro, just so that it's easy to use.
#define DEBUGPRINT std::cout << __FILE__ << ":" << __LINE__ << "\n";
Check a working example here:
http://www.cpp.sh/2hpam
Note that it says <stdin>::14 instead of the filename because it's running on a webpage.
I have done some changes to your code, and added comments everywhere I've made changes. Check it out:
#include <iostream>
#include <conio.h>
using namespace std;
bool prime_check(int x) { // I have changed the datatype of this function to bool, because I want to store if all the digits are prime or not
int i, flag = 1; // Removed the variable a, because the function is already taking x as input
for (i = 2; i <= x / 2 && flag == 1; i++) {
if (x % i == 0)
flag = 0;
}
return flag == 1;
}
int main() {
int a, r, sum = 0, original; // added original variable, to store the number added
bool eachDigit = true; // added to keep track of each digit
cin >> a;
original = a;
while (a != 0) {
r = a % 10;
eachDigit = prime_check(r); // Here Each digit of entered number is checked for prime
sum = (sum * 10) + r;
a = a / 10;
}
if (eachDigit && prime_check(original) && prime_check(sum)) // At the end checking if all the digits, entered number and the revered number are prime
cout << "yes";
else
cout<< "no";
}
For optimization, you can check if the entered number is prime or not before starting that loop, and also you can break the loop right away if one of the digits of the entered number is not prime, Like this:
#include <iostream>
#include <conio.h>
using namespace std;
bool prime_check(int x) { // I have changed the datatype of this function to bool, because I want to store if all the digits are prime or not
int i, flag = 1; // Removed the variable a, because the function is already taking x as input
for (i = 2; i <= x / 2 && flag == 1; i++) {
if (x % i == 0)
flag = 0;
}
return flag == 1;
}
int main() {
int a, r, sum = 0;
bool eachDigit = true, entered; // added to keep track of each digit
cin >> a;
entered = prime_check(a);
while (a != 0 && entered && eachDigit) {
r = a % 10;
eachDigit = prime_check(r); // Here Each digit of entered number is checked for prime
sum = (sum * 10) + r;
a = a / 10;
}
if (eachDigit && entered && prime_check(sum)) // At the end checking if all the digits, entered number and the revered number are prime
cout << "yes";
else
cout<< "no";
}
Suppose you have an int variable num which you want to check for your conditions, you can achieve your target by the following:
int rev_num = 0;
bool flag = true; // Assuming 'num' satisfies your conditions, until proven otherwise
if (prime_check(num) == false) {
flag = false;
}
else while (num != 0) {
int digit = num % 10;
rev_num = rev_num * 10 + digit;
// Assuming your prime_check function returns 'true' and 'false'
if (prime_check(digit) == false) {
flag = false;
break;
}
num /= 10;
}
if (prime_check(rev_num) == false) {
flag = false;
}
if (flag) {
cout << "Number satisfies all conditions\n";
}
else {
cout << "Number does not satisfy all conditions\n";
}
The problem is that each of your functions is doing three things, 1) inputting the number, 2) testing the number and 3) outputting the result. To combine these functions you need to have two functions that are only testing the number. Then you can use both functions on the same number, instead of inputting two different numbers and printing two different results. You will need to use function parameters, to pass the input number to the two functions, and function return values to return the result of the test. The inputting of the number and the outputting of the result go in main. Here's an outline
// returns true if the number is a prime, false otherwise
bool prime_check(int a)
{
...
}
// returns true if the number is a reverse prime, false otherwise
bool reverse_prime_check(int a)
{
...
}
int main()
{
int a;
cin >> a;
if (prime_check(a) && reverse_prime_check(a))
cout << "prime\n";
else
cout << "not prime\n";
}
I'll leave you to write the functions themselves, and there's nothing here to do the digit checks either. I'll leave you do to that.

Why else if (a != 65) is not executing?

#include <iostream>
#include <Windows.h>
using namespace std;
void noret()
{
for (int i = 1; i < 11; i++)
{
cout << "Line number : " << i << endl;
}
system("pause");
}
void StartProgram(string filename)
{
ShellExecute(NULL, "open", filename.c_str(), NULL, NULL, SW_SHOWNORMAL);
}
int main()
{
for (int a = 1; a < 100; a += 3)
{
cout << "The number is: " << a << endl;
if (a == 65)
{
StartProgram("mspaint");
}
else if (a != 65);
{
StartProgram("devenv");
}
}
system("pause");
return 0;
}
Here is the code I made(I am still new to programming). Please ignore the void noret() part. The code is Fully working, but in the part with else if (a != 65), I want to make it open the program only if it isn't equal to 65.
The program counts from 1-100. a = a+3 where "a" is equal to 1. While it counts to 100, if "a" is never equal to 65 it will open "devenv". But the way I did it it's made that "devenv" will open to very number that isn't equal to 65. How can I make it so that it will open ONCE if throughout the counting it never was 65... Does it make any sense?
This code is wrong many ways:
if (a == 65)
{
StartProgram("mspaint");
}
else if (a != 65);
{
StartProgram("devenv");
}
first of all semicolon after if makes it noop and terminates your else so that code is convoluted way to write:
if (a == 65)
{
StartProgram("mspaint");
}
StartProgram("devenv");
just remove second if completely:
if (a == 65)
{
StartProgram("mspaint");
}
else
{
StartProgram("devenv");
}
that to fix your code, to fix the logic of your program just use flag:
int main()
{
bool found = false;
for (int a = 1; a < 100; a += 3)
{
if (a == 65) found = true;
}
if( found )
StartProgram("devenv");
else
StartProgram("mspaint");
}
If you want to know if all numbers in the loop are not 65, you need to remember whether you have seen 65 as you go through the loop:
auto found65 = false;
for (int a = 1; a < 100; a += 3)
{
cout << "The number is: " << a << endl;
found65 = found65 || (a == 65);
}
if (found65)
{
StartProgram("mspaint");
}
else
{
StartProgram("devenv");
}
I assume that you have figured out the problems with your syntax, so I'll concentrate on high-level issues with the algorithm.
You don't need a loop to determine if counting by 3 would print 65. This can be done with simple math: when you start counting from a to z by x, you would hit n if (n-a) produces no remainder when divided by x:
bool see65 = (65-1) % 3 == 0;
This assumes that numbers a and z are on the opposite sides of n.
Since your conditional controls a single parameter, you can rewrite your call as a conditional expression:
StartProgram(see65 ? "mspaint" : "devenv");
Moreover, if you recall that bool in C++ is an integral type, you can eliminate conditional:
array<string,2> prog {"mspaint", "devenv"}
...
StartProgram(prog[see65]);

My program run and returns 0, but it doesn't display the cout data ive given it

When I Build and run my code it instantly returns 0 saying programing was successful, however i want it to display all the numbers from 100 to 200 that are divisible by 4.
Here's my code...
#include <iostream>
using namespace std;
int main()
{
int num = 200;
int snum;
cout<<"The following numbers are all divisble by 4 and are inbetween 100 and 200\n";
while(num<99)
{
snum = (num % 4) ;
cout<<snum<<endl;
cout<<num<<endl;
if(snum = 0)
{
cout<< num << endl;
}
else
{
}
num--;
}
return 0;
}
The while condition should be while (num > 99) instead of while(num<99)(false at the beginning)
The if condition should be if (snum == 0) instead of if(snum = 0)(= is assignment, not equal operator)
The else part has nothing, you may delete it. I added some other notes in the comments below.
while (num > 99)
{
snum = num % 4 ; // no need for the parenthesizes
if (snum == 0)
{
std::cout<< num << std::endl;
}
--num; //pre-increment is preferred, although doesn't matter in this case
}
Your loop never executes because the condition
(num<99)
is already false from the start. You probably meant
(num>99)
Also, the if statement condition
(snum = 0)
sets snum to zero, always returning zero, so you probably meant
(snum == 0)
You set num to be 200:
int num = 200;
Then you only run the loop if and when the number is less than 99:
while(num<99)
What do you expect will happen?
This is not how you do an equals-test in C:
if(snum = 0)
In C, equality is checked with ==:
if(snum == 0)
In fact, what you have (if (snum = 0)) will NEVER be true, so your if-statement will NEVER be executed.

Prime number C++ program

I am not sure whether I should ask here or programmers but I have been trying to work out why this program wont work and although I have found some bugs, it still returns "x is not a prime number", even when it is.
#include <iostream>
using namespace std;
bool primetest(int a) {
int i;
//Halve the user input to find where to stop dividing to (it will remove decimal point as it is an integer)
int b = a / 2;
//Loop through, for each division to test if it has a factor (it starts at 2, as 1 will always divide)
for (i = 2; i < b; i++) {
//If the user input has no remainder then it cannot be a prime and the loop can stop (break)
if (a % i == 0) {
return(0);
break;
}
//Other wise if the user input does have a remainder and is the last of the loop, return true (it is a prime)
else if ((a % i != 0) && (i == a -1)) {
return (1);
break;
}
}
}
int main(void) {
int user;
cout << "Enter a number to test if it is a prime or not: ";
cin >> user;
if (primetest(user)) {
cout << user << " is a prime number.";
}
else {
cout << user<< " is not a prime number.";
}
cout << "\n\nPress enter to exit...";
getchar();
getchar();
return 0;
}
Sorry if this is too localised (in which case could you suggest where I should ask such specific questions?)
I should add that I am VERY new to C++ (and programming in general)
This was simply intended to be a test of functions and controls.
i can never be equal to a - 1 - you're only going up to b - 1. b being a/2, that's never going to cause a match.
That means your loop ending condition that would return 1 is never true.
In the case of a prime number, you run off the end of the loop. That causes undefined behaviour, since you don't have a return statement there. Clang gave a warning, without any special flags:
example.cpp:22:1: warning: control may reach end of non-void function
[-Wreturn-type]
}
^
1 warning generated.
If your compiler didn't warn you, you need to turn on some more warning flags. For example, adding -Wall gives a warning when using GCC:
example.cpp: In function ‘bool primetest(int)’:
example.cpp:22: warning: control reaches end of non-void function
Overall, your prime-checking loop is much more complicated than it needs to be. Assuming you only care about values of a greater than or equal to 2:
bool primetest(int a)
{
int b = sqrt(a); // only need to test up to the square root of the input
for (int i = 2; i <= b; i++)
{
if (a % i == 0)
return false;
}
// if the loop completed, a is prime
return true;
}
If you want to handle all int values, you can just add an if (a < 2) return false; at the beginning.
Your logic is incorrect. You are using this expression (i == a -1)) which can never be true as Carl said.
For example:-
If a = 11
b = a/2 = 5 (Fractional part truncated)
So you are running loop till i<5. So i can never be equal to a-1 as max value of i in this case will be 4 and value of a-1 will be 10
You can do this by just checking till square root. But below is some modification to your code to make it work.
#include <iostream>
using namespace std;
bool primetest(int a) {
int i;
//Halve the user input to find where to stop dividing to (it will remove decimal point as it is an integer)
int b = a / 2;
//Loop through, for each division to test if it has a factor (it starts at 2, as 1 will always divide)
for (i = 2; i <= b; i++) {
//If the user input has no remainder then it cannot be a prime and the loop can stop (break)
if (a % i == 0) {
return(0);
}
}
//this return invokes only when it doesn't has factor
return 1;
}
int main(void) {
int user;
cout << "Enter a number to test if it is a prime or not: ";
cin >> user;
if (primetest(user)) {
cout << user << " is a prime number.";
}
else {
cout << user<< " is not a prime number.";
}
return 0;
}
check this out:
//Prime Numbers generation in C++
//Using for loops and conditional structures
#include <iostream>
using namespace std;
int main()
{
int a = 2; //start from 2
long long int b = 1000; //ends at 1000
for (int i = a; i <= b; i++)
{
for (int j = 2; j <= i; j++)
{
if (!(i%j)&&(i!=j)) //Condition for not prime
{
break;
}
if (j==i) //condition for Prime Numbers
{
cout << i << endl;
}
}
}
}
main()
{
int i,j,x,box;
for (i=10;i<=99;i++)
{
box=0;
x=i/2;
for (j=2;j<=x;j++)
if (i%j==0) box++;
if (box==0) cout<<i<<" is a prime number";
else cout<<i<<" is a composite number";
cout<<"\n";
getch();
}
}
Here is the complete solution for the Finding Prime numbers till any user entered number.
#include <iostream.h>
#include <conio.h>
using namespace std;
main()
{
int num, i, countFactors;
int a;
cout << "Enter number " << endl;
cin >> a;
for (num = 1; num <= a; num++)
{
countFactors = 0;
for (i = 2; i <= num; i++)
{
//if a factor exists from 2 up to the number, count Factors
if (num % i == 0)
{
countFactors++;
}
}
//a prime number has only itself as a factor
if (countFactors == 1)
{
cout << num << ", ";
}
}
getch();
}
One way is to use a Sieving algorithm, such as the sieve of Eratosthenes. This is a very fast method that works exceptionally well.
bool isPrime(int number){
if(number == 2 || number == 3 | number == 5 || number == 7) return true;
return ((number % 2) && (number % 3) && (number % 5) && (number % 7));
}

Nested loops with C++ coin toss

I have to write a program that runs a loop for a coin toss. I am supported to enter a number into the console and have it run a loop of the coin toss for that many times. I need to use nested loops. I have been working on this for hours and cannot make it work.
The console i/o is supposed to look like below:
Enter the number of tosses to perform [0=exit]: 3
Heads
Tails
Heads
Enter the number of tosses to perform [0=exit]: 2
Tails
Tails
Enter the number of tosses to perform [0=exit]: 0
This is the code i have so far:
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int main ()
{
srand(time(0));rand();
int result = rand() % 2;
while (true)
{
int n; // this many tosses
cout << "How many tosses";
cin >> n;
cin.ignore (1000, 10);
if (n == 0)
break;
for (int i = 0; i < n; i++)
//random number generator
{
if (result == 0)
cout<< "Heads"<<endl;
else if (result == 1)
cout << "Tails"<<endl;
else if (result != 0 || result !=1)
return 0;
} //for
}//while
}//main
Your for loop doesn't have the part that you are actually trying to execute inside of {}. Try adding the braces around the part you want to loop and see if that fixes it for you.
I edited the indentation in your code to show you the only line that will actually be looping (the srand(time(0)))
You need brackets around the loop block, i.e.
for( int i = 0; i < n; i++ )
{
// Code goes here
}
As shown above, you need to initialize i.
Put the seeding of rand() before the while(...) loop.
You need to move int result = rand() % 2; inside your for loop! Otherwise you will get the same result every single time until you restart the application.
for (int i = 0; i < n; i++)
//random number generator
{
int result = rand() % 2;
if (result == 0)
cout<< "Heads"<<endl; /* to make your output look like your example you should removed the <<endl from here */
else if (result == 1)
cout << "Tails"<<endl; /* and here */
else if (result != 0 || result !=1)
return 0;
} //for
/* and put it here */
cout << endl;