Why is the "if" not executed within a loop? - c++

The cout << "Fin", it is never executed
int main(){
int num, suma=0, divisor=0;
cout<<"Escribe un nĂºmero"<<endl;
cin>>num;
cout<<num<<": ";
while(divisor<num){
if(num % divisor==0){
cout<<divisor;
}
}
cout<<"Fin";

num % divisor with divisor=0 does division by zero, which typically leads to aborting.
You should give another initial value (maybe 1 or 2 looks good, depending on the purpose) to that.
Also, as #KfirVentura pointed out, you should update divisor (or num) in the loop, or the loop will run infinitely if divisor<num initially becomes true.

"if" loop would not run as divisor is 0 and for all conditions will give a runtime exception error, which is apparent. Try changing the value of divisor.

Related

How do i find GCD with while loop? How does modulus operator work?

#include <iostream>
int GCD()
{
int a,b,k;
cout<<"Enter a and b"<<endl;
cin>>a>>b;
cout<<endl;
if (a>b)
{
k=a;
}
else
{
k=b;
}
cout<<k<<endl;
do
{
k=k-1;
} while(a%k !=0 && b%k !=0);
cout<<k<<endl;
return 0;
}
Why programm like this doesnt work correctly? For example when i enter 125 and 5 answer is 25, but supposed to be 5? Am wrong with logic in while loop? As i understood problem is in modulus operator. When k hits 25 it says that 125%25=0 and 5%=25=0. How can i fix this?
You have some mistakes here:
The GCD is lower or equal to the lower number. Currently, you start checking with the larger number. You need to flip the if block to if (a<b). (not exactly an error, but you check much more numbers than needed)
You need to check if the inital k is the GCD. When using a do {} while() the first number you check is k-1. Use a simple while instead. Also the loop condition has a logic flaw.
while (!((a % k == 0) && (b % k == 0)))
{
k--;
}
Note that the brackets around the modulo are not neccessary, but improve readability a bit.
Your code will not compile under all compilers and you should not omit the namespace std::.
Your while statement has logic error. It needs to be
while(!(a%k == 0 && b%k == 0));
When k is equal to 25, 125%25==0 so in your while statement a%k !=0 part is equals to false so it exit your do-while but it needs to test if b%k is equal to 0 or not!
Also your implementation tends to execute slow when a and b is big. You can take a look efficent solutions.

Why is this loop outputting 0 every time to sqdNumber_result?

I am trying to find the sum of each digit in an integer squared, and for any integer that is input to sqdnumber, it outputs 0 to sqdNumber_result, and I can't figure out why.
Also, this is through edX, but I have been stuck for a week or so on this problem, and I have looked at a lot of different topics, but haven't found anything of use to me.
I used codeblocks to write this, but the system testing it uses codeboard
void squaredSum(int sqdnumber,int &sqdNumber_result) {
for (int i=1; i>1; i++){
if (sqdnumber >= ((10^(i-1))-1)){
int rem = (sqdnumber % (10^i));
int rem1 = (sqdnumber % (10^(i-1)));
int temp = (rem - rem1);
sqdNumber_result = sqdNumber_result + (temp^2);
}
else{
break;
}
}
}
I am new to coding, and just learning to do loops in C++.
This is the first iteration of the loop I have gotten their system to actually give me an output for it(I've written and rewritten it 20 or so times), but it isn't giving me an output that makes sense.
I wouldn't ask but I am at my wit's end.
In C++, ^ is the xor operator, not the nth power. for that, you should use pow.
The for statement does not loop. The condition is false the first iteration
There are two issues:
for (int i=1; i>1; i++){
This loop will not loop at all, since the condition i>1 is never met.
The second issue is the usage of ^ to do a power operation. The ^ in C++ is not a power operator, it is the exclusive-or operator.
So the answer at first glance would be to use the std::pow function to compute powers. However there can be drawbacks using it if the exponent is an integer. The reason is that pow is not guaranteed to work perfectly for integer powers.
See this as to dangers of using pow() for integral exponents
It is advised to just use a simple array of values with the powers of 10 and doing a lookup.
you said you were new to C++ so I tried to get a solution without using the for loop and tried to make it as simple as I could.
Let me know if this was any help.
//Code to calculate the sum of each digit squared//
#include<iostream>
using namespace std;
int main ()
{
int integer1,integer2,sum, square;
cout<<"Please enter two integers"<<endl;
cin>>integer1>>integer2 ;
cout<<"The sum of your integers is"<<" "<<endl;
sum = (integer1+integer2);
cout<<sum<<endl;
cout<<"The square of your sum is"<<" "<<endl;
square = (sum*sum);
cout<<square<<endl;
return 0;
}

Inifinite loop makes variable come out as 0

I have this piece of code in my school book.
#include<iostream>
using namespace std;
int main() {
int x=10,c=1;
while (c < 5) {
x += x*c;
c *= 2;
c++;
c -= 2;
cout << "X=" << x<<'\n';
}
system("pause");
return 0;
}
As you can see it's an infinite loop, when logically traced, it should show 20,40,80 and so on.
However it always shows 0.
when adding system("pause") after each loop cycle it shows the correct values, but when left as shown above (infinitely looping) it shows zero.
Any ideas of the reason?
c is always 1 no matter what. The loop becomes infinite. Eventually, X becomes 0 due to integer overflow.
c = 1
c *= 2; c = 2
c++; c = 3
c -= 2; c = 1 <-- infinite
Here is my answer for your questions:
Why do you get infinitely looping?
awesomeyi did answer you above, because the condition of the while loop is always true, so it is never ended.
Why does X always equal to 0?
Please pay your attention on X varable, its value will be increased after ending one loop x += x*c. Because you are in the infinitely loop, x's value will be increased forever until greater than the limited value of an integer variable. Then, the value will be set as zero. Please see my output when running your code.
Removing the pause doesn't cause it to always show zero. It just prints output so quickly that zeroes are all you see at the bottom. Add the pause back in and click through about 30-40 iterations and see if it helps you understand what is happening.

Error in while loop?

I made a simple example for counting decimal points but it doesn't stop and doesn't give me the right answer here's my code:
double b=76327741.125;
int count=0;
while(b - (int)b > 0.0)
{
b*=10;
count++;
}
cout<<count;
the answer is supposed to be:
3
but instead the while loop keeps running Indefinitely .. what's wrong with my code?
You should have checked the INT_MAX first. The number would be different. It depends on whether you are running the code on a 32-bit or 64-bit machine. If it is way smaller than your initial b, you would definitely end up in the infinite loop. For example, the max of short integer type is 32767. In that case, the condition of your loop would be like this: 76327741.125 - some negative number, larger than 0. however, in the loop, you increased the value of b. The next time, when we hit the condition line, it would be something like this: 76327741.125*10 - some negative number
You should probably set b to be b - int(b), to make sure it doesn't keep increasing (and potentially overflowing).
double b=76327741.125;
int count=0;
while(b - (int)b > 0.0)
{
b = b - int(b); // Note the change here.
b*=10;
count++;
}
cout<<count;

Floating Point Exception C++ Why and what is it?

I'm building a program for the Euler projects question 3, and while that might not really matter as a result I'm current trying to make this code take a number and test if it is prime or not. Now then before I get to troubleshoot the function it gives me the error "floating point exception" right after inputting the number. Here's the code:
int main()
{
int input;
cout << "Enter number: " << endl;
cin>> input;
int i = input/2;
int c;
for (i>0; i--;) {
c= input%i;
if (c==0 || i == 1)
cout << "not prime" << endl;
else
cout << "prime" << endl;
}
return 0;
}
so essentially why is it giving me a floating point exception and what does that even mean?
A "floating point number" is how computers usually represent numbers that are not integers -- basically, a number with a decimal point. In C++ you declare them with float instead of int. A floating point exception is an error that occurs when you try to do something impossible with a floating point number, such as divide by zero.
for (i>0; i--;)
is probably wrong and should be
for (; i>0; i--)
instead. Note where I put the semicolons. The condition goes in the middle, not at the start.
Lots of reasons for a floating point exception. Looking at your code your for loop seems to be a bit "incorrect". Looks like a possible division by zero.
for (i>0; i--;){
c= input%i;
Thats division by zero at some point since you are decrementing i.
Since this page is the number 1 result for the google search "c++ floating point exception", I want to add another thing that can cause such a problem: use of undefined variables.
Problem is in the for loop in the code snippet:
for (i > 0; i--;)
Here, your intention seems to be entering the loop if (i > 0) and
decrement the value of i by one after the completion of for loop.
Does it work like that? lets see.
Look at the for() loop syntax:
**for ( initialization; condition check; increment/decrement ) {
statements;
}**
Initialization gets executed only once in the beginning of the loop.
Pay close attention to ";" in your code snippet and map it with for loop syntax.
Initialization : i > 0 : Gets executed only once. Doesn't have any impact in your code.
Condition check : i -- : post decrement.
Here, i is used for condition check and then it is decremented.
Decremented value will be used in statements within for loop.
This condition check is working as increment/decrement too in your code.
Lets stop here and see floating point exception.
what is it? One easy example is Divide by 0. Same is happening with your code.
When i reaches 1 in condition check, condition check validates to be true.
Because of post decrement i will be 0 when it enters for loop.
Modulo operation at line #9 results in divide by zero operation.
With this background you should be able to fix the problem in for loop.