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

#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]);

Related

Loop does not continue correctly

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.

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.

Getting a Segmentation Fault: 11. I Have Seen Other Posts, but I Don't Know How I Can Add Memory to my Program

This code is trying to check if a number is prime, I know there are more efficient methods, using sets of numbers, but I just want this to work, but I get a Segmentation fault.
If you want to test the code, it happens to me when I plug in 10000877, or any greater number.
#include <math.h>
#include <iostream>
int main () {
int prime/*???*/;
std::cout << "Please input a number: ";
std::cin >> prime;
bool isPrime = true;
int biggestFactor = ceil((prime^(1/2)));
bool odd = prime%2 == 1 ? true : false;
int multiple = 0;
int ranges[biggestFactor];
bool boolean = false;
for(int i = biggestFactor; i!=1; i--) {
ranges[i-2] = ceil(prime / i);
}
if(odd) {
for(int i = 1; i<prime; i++) {
if(multiple > biggestFactor) {
break;
} else if(boolean) {
} else if(i* ranges [multiple] > prime) {
multiple++;
} else if(i*ranges[multiple] == prime) {
isPrime = false;
break;
}
}
} else {
if(prime != 2) {
isPrime = false;
}
}
if(isPrime) {
std::cout << "That number is prime." << std::endl;
} else {
std::cout << "That number is composite." << std::endl;
}
}
Aside from noted fact that prime^(1/2) is not square root of prime, your code (even though it's wrong) sort of works. You just overestimate the square root by using prime instead (the 1/2 is converted to int which is 0 and XOR with it is itself).
It works on small numbers, I tried.
Now with the large numbers you are running out of memory here, trying to allocate 4 * 10000877 bytes
int ranges[biggestFactor];

How to programmatically see which conditions were not met in C++ when using logical AND (&&)?

I am trying to efficiently deduct which conditions caused an if statement to be overlooked by the program without using a sequence of if statements to verify each variable's relative integrity individually.
Is this possible?
bool state = false;
int x = 0;
int y = 1;
int z = 3;
if(x == 0 && y == 1 && z == 2) {
// Do something...
state == true;
}
if(state == false) {
std::cout << "I did not execute the if statement because the following
conditions were not met: " << std::endl;
/*Find a way to make the program output that z != 3 stopped the
conditional from running without directly using if(z != 2)*/
}
You could introduce a counter as a "condition" between each of the conditions in the if to see when short-circuit evaluation of operator && prohibits execution of the latter conditions:
int nrOfConditionFailing = 1;
if(x == 0 &&
nrOfConditionFailing++ && y == 1 &&
nrOfConditionFailing++ && z == 2) {
state = true;
}
if (!state) {
cout << "failed due to condition nr " << nrOfConditionFailing << endl;
}
If you want to check all the conditions, you cannot do it in a single if-statement; Short-circuit evaluation of operator && will prevent the latter conditions to be even checked/evaluated if one of the former conditions evaluates to false.
However, you could do such a check as an expression that marks a bit in an unsigned int for each condition that is not met:
int x = 1;
int y = 1;
int z = 3;
unsigned int c1 = !(x == 0);
unsigned int c2 = !(y == 1);
unsigned int c3 = !(z == 2);
unsigned int failures =
(c1 << 0)
| (c2 << 1)
| (c3 << 2);
if (failures) {
for(int i=0; i<3; i++) {
if (failures & (1 << i)) {
cout << "condition " << (i+1) << " failed." << endl;
}
}
}
else {
cout << "no failures." << endl;
}
If this is something you want to display to the end user, and not just while debugging, as suggested in the comments, you can design a simple data structure for yourself. It would be a list / vector / array of entries, each of which contain a) a value to compare against, b) a value to test, and optionally c) a description of the test.
Then simply iterate the list, and check if equality holds for all of them. If not, you can stop the flow of the programme and print out the description.
To more directly answer your question: no, there is nothing in C++ that would allow you to examine the results of previous statements. The statements and operations you see in the source code get compiled and possibly won't even be trivially recognisable among the assembly instructions. Being able to check the results would mean the data has to be stored somewhere, which would be an incredible waste of memory and processing time. That is why you have to do this yourself.
Is this possible?
It is not possible in the way you were thinking about the problem. You can solve your problem instead by running each test individually, storing the result, and then identifying which of them were false:
std::vector<std::tuple<std::string,bool> > tests = {
{"x==0",x==0}, // test name as a string followed by the actual test
{"y==1",y==1},
{"z==2",z==2}
};
if(!all_of(tests.begin(),tests.end(),[](std::tuple<std::string,bool> &t) { return std::get<1>(t); }))
{
std::cout << "The following tests failed: ";
//remove all tests that passed
tests.erase(
std::remove_if(tests.begin(),tests.end(),[](std::tuple<std::string,bool> &t) { return std::get<1>(t); }),
tests.end());
//This will only print out the tests that failed
std::transform(tests.begin(),tests.end(),std::ostream_iterator<std::string>(std::cout, " "),[](std::tuple<std::string,bool> &t) { return std::get<0>(t); });
std::cout << std::endl;
} else {
//what to do if all tests were true
}
This will evaluate all tests (i.e., it won't use &&'s short-circuiting) and print all the ones that failed. You could likely wrap this into a class to make this more generalizable and user friendly.
The original code tests each variable individually. The && series is exactly equivalent to a series of if...else statements. There's nothing inefficient about one compared to the other, and there's nothing "clever" about using some tricky solution that achieves the same end result as straightforward code.
I might write:
char const *reason = nullptr;
if(x != 0)
reason = "x failed";
else if (y != 1)
reason = "y failed";
else if (z != 2 )
reason = "z failed";
if ( reason )
std::cout << reason << '\n';
else
{
// success code here...
}
I would typically do something like the following to determine if a series of validity checks worked and to mark which ones failed.
unsigned long ulFlags = 0;
int x = 0;
int y = 1;
int z = 3;
ulFlags |= (x == 0) : 0 ? 0x0001; // if bit set then condition failed.
ulFlags |= (y == 1) : 0 ? 0x0002; // if bit set then condition failed.
ulFlags |= (z == 2) : 0 ? 0x0004; // if bit set then condition failed.
if(ulFlags == 0) {
// Do something since all conditions are met and valid ...
} else {
std::cout << "I did not execute if statement because: " << std::hex << ulFlags << std::endl;
/* Find a way to make the program output that z != 3 stopped the
conditional from running without directly using if(z != 2) */
}
This is the same idea as some of the other answers, but with a template to simplify the syntax to use it. Stores all the individual checks in an std::array<bool, N> and one additional bool to be able to re-check the full statement without going through the individual results again.
No dynamic allocation is a plus as well.
#include <iostream>
#include <array>
#include <type_traits>
template <typename... N>
struct what_failed {
what_failed(N... n) : arr{n...}, status{(... && n)} {
static_assert(std::conjunction_v<std::is_same<N, bool>...>, "Only pass bools");
}
std::array<bool, sizeof...(N)> arr;
bool status;
operator bool() { return status; }
};
int main() {
auto check = what_failed(2 == 5, 2 < 5, 2 > 5, 1 == 1);
if (check)
std::cout << "Check: All true";
else {
std::cout << "Check: ";
for (auto c : check.arr)
std::cout << c << ' ';
}
return 0;
}
This requires c++17 due to fold expressions and template deduction in a constructor, but that can be worked around for c++11 with a couple of extra help-templates.

How to print all prime numbers in c++?

I'm trying to print all the prime numbers in series, the code I ended up with is below, instead of printing all primes it prints random numbers, Some are prime and some are not :/
Why is that so?
#include <iostream>
using namespace std;
long int x,y=3;
int a=3;
bool isprime;
int main()
{
while(a<=100)
{
for(x=2;x<=y;x++)
{
if(y%x==0 && x!=y)
{
isprime=false;
break;
}
else if(y%x!=0 && x!=y)
{
isprime = true;
}
}
if(isprime==true && y%x!=0 && x!=y)
{
cout<<a<<" is a prime number."<<"\n";
isprime=false;
}
a++;
y++;
}
}
This
if(isprime=true && a%x!=0 && a!=y)
should be this
if(isprime==true && a%x!=0 && a!=y)
That's a common mistake. But even better is to realise that you don't need to compare bools against true of false, because they are true or false. So just
if (isprime && a%x!=0 && a!=y)
The logic just looks all wrong (and way too complicated), try this
isprime = true;
for(x=2;x<a;x++)
{
if(a%x==0)
{
isprime = false;
break;
}
}
if (isprime)
{
cout<<a<<"\n";
}
No need for y.
Well what jumps into my eyes is that you never increment y.
y is 3 in the beginning, so you only try if 2 is a possible divisor of a and then go to the next a.
Anyway, I am not sure what you wanted to achieve with y.
Let x run from 2 to a/2, as there is no need to try numbers bigger than a/2.
This is simply because there never will be a divisor bigger than a/2.
Example: a = 30. It would not make sense to try to divide by 16 or bigger, as the result can never be a integer (besides a itself of course)
However, this should do what you want:
int x = 0;
int a = 0;
bool isPrime = false;
for(a=3; a < 100; a+=2)
{
isPrime = true;
for(x = 2; x <= a/2; x++) {
if(a%x == 0) {
isPrime = false;
break;
}
}
if(isPrime) {
cout << a << "\n";
}
}
there are of course other algorithms that can find primes, but I wanted to use your approach basically.
Cheers
Chris
EDIT:
Someone was faster :)
anyway: there is no need to run higher than a/2, this is a important optimization...!
EDIT2:
another optimization is of course skipping all even numbers, so start with a = 3 and increment by 2 for each loop iteration...
I see your code is ok now.
Nevertheless I made small changes, cleaning the code and making it a little bit faster.
#include <iostream>
using namespace std;
long int x, y = 2;
int a = 3;
bool isprime;
int main() {
while (a <= 100) {
while ((y + 1) * (y + 1) <= a) {
y++;
}
isprime = true;
for (x = 3; x <= y; x += 2) {
if (a % x == 0) {
isprime = false;
break;
}
}
if (isprime) {
cout << a << " is a prime number." << "\n";
}
a+=2;
}
}