Program crash while using if statement inside a for loop - c++

I am trying to give a shot at Project Euler problem 3 until codeblocks or whatever caused it pissed me off. This is my code, What is wrong with it? I guess more of a bug?
#include <iostream>
using namespace std;
int main()
{
int x=0;
for(int y=0;y<=10;y++)
{
if(13195%x==0)
{
cout<<"I don't know why the program crashes!";
}
}
}

You can't use a 0 as the second operand while doing / or %. What you're essentially saying is "Hey divide by 0 and give me the remainder." Please see the following:
Can't Mod Zero?

Modulus operator divides it by zero and next finds the remainder, thus you will get divide by zero error

x must not be equal to 0 otherwise division by zero.
Just think how many zeroes in 13195?

x = 0. Dividing a number with zero will crash your code. Make sure x is not 0 before 13195 % x.

The operation A modulo B is defined as: the remainder of the division of A by B.
In your code, you have B=0 which means you are trying to divide by zero.

Related

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.

Finding the square of a number without multiplication [duplicate]

This question already has answers here:
Making a square() function without x*x in C++
(7 answers)
Closed 4 years ago.
I'm a beginner in programming and trying to learn C++ by the book Programming principles and practice using C++. In some parts of the book there are little exercises that you can try to do, one of this exercises is about calculating the square of a number, here is what my book says :
Implement square() without using the multiply operator, that is, do the x * x by repetead addition (start a variable result to 0 and add x to it x times).
I've already found a solution for this program but my first tentative was something like this :
#include <iostream>
int main()
{
int a = 0;
std::cout << "Enter an integer value : ";
std::cin >> a;
while (a < a * a)
{
a += a;
std::cout << a << "\n";
}
}
I know this code is wrong but I can't understand the output of the progam, if I enter 5 the program prints 10 20 30 40 50 until 8000, why the for loop doesn't stop when a is greater than its square ? I'm just curious to undersant why
Using multiplication when trying to avoid multiplication seems broken. What about this:
int r = 0;
for (int n = 0; n < a; ++n) {
r += a;
}
why the for loop doesn't stop when a is greater than its square ?
Because it never is. If you compare the graph of y=x^2 against the graph of y=x, you will see that the only time y=x is above, is when 0 < x < 1. That's never the case for integers1. Now, since we're talking about computers with limited storage here, there is a thing called overflow, which will cause a very large number to become a very small number. However, signed integer overflow is undefined behavior in C++. So once your loop gets to the point where overflow would happen, you cannot rely on the results.
1. Note that your loop is not set to stop just when a is greater than its square, but when it is greater than or equal to its square. So, your loop will actually stop if a is 0 or 1.

code blocks power function is not working in c

i am using code block for learning c. my code is
#include<stdio.h>
#include<math.h>
int main()
{
int x;
x = pow(5,2);
printf("%d", x);
}
Output is 25
When i am using this code
#include<stdio.h>
#include<math.h>
int main()
{
int x,i,j;
printf("please enter first value");
scanf("%d", &i);//5
printf("please enter second value");//2
scanf("%d", &j);
x = pow(i,j);
printf("%d", x);
}
Output is 24
what is wrong here? i am just taking value using scan function and also using pow function in a same way.
I suspect you have a naive implementation of pow in your libm (I get 25, as it should be). If that computes pow(x,y) as exp(y*log(x)) for positive x without checking for (small) integral exponents and treating them specially, you get
Prelude> 2 * log 5
3.2188758248682006
Prelude> exp it
24.999999999999996
a double result slightly smaller than 25, so when that is converted to int it is truncated to 24.
To check, assign the result of pow(i,j) to a double and print that out.
With hardcoded pow(5,2), the compiler (most likely, it's what gcc does even without optimisation) computes the result during compilation exactly.
Try changing initialization to this:
int x=-1 ,i=-1 ,j=-1;
And last print to this:
printf("pow(%d, %d) == %d\n", i, j, x);
That should give good hint about the problem. Also, check return values of scanf, they should return number of items read, ie. 1 with code above.
It's almost certain, that you entered invalid input for scanf, and i or j were left uninitialized, and that 24 is just garbage value.
Also, compile with warnings enabled, and fix them (like, add return 0; to end of main).
Your code correctly gives 25 on my windows x64.
You probably needs to run it again see if you just read it wrong...
The missing "return 0;" is not the problem here.
If, anything, could ever go wrong,
you can try adding
fflush(stdin);//or out
after very scanf and printf.
If any of the flushes solves your problem, you know what is going wrong.
It seems that there is nothing wrong with the second program, except that you must add at the end
return 0;
If you read the value j with 2 then the result will be just 25.
Using your code i got result 25 which is correct.
Although Try changing the data type of result such as float or double.

Running first Instance of while

The assignment:
Write a program that loops indefinitely. In each iteration of the loop, read in an integer N (declared as an int) that is entered by a user, display N/5 if N is non-negative and divisible by 5, or -1 otherwise. Use the ternary operator (?:) to accomplish this. (Hint: the modulus operator may be useful.)
My solution:
#include<iostream>
using namespace std;
int main(){
int x;
cin>>x;
while(1) {
cin>>x;
int result;
cout<<" "<<endl;
result = (x>0 & (x%5==0)) ? int(x/5) : -1;
cout<<result;
}
}
I am able to do the question
but the first run of the program does not gives output
Go through the program line by line. With cin>>x, you read a number into x. Line 6 is a while (1), 1 is true, so you go into the loop. The next cin>>x reads a number into x, overwriting the previous contents.
(x>0 && (x%5==0)) ? int(x/5) : -1;
^^
I think you intend to use Logical && operator and not the bitwise & operator.
Additionally, You are reading into x twice and overwriting the first read value.
Okay. First thing first. You should know C++ logical AND operator is "&&" and not "&" (the one you used). Have a look here: http://www.cplusplus.com/doc/tutorial/operators/.
Hint 1: Do you really need the singleton cin just above the while Loop?
Hint 2: Do you want to print the blank line with newline above the result?
Hint 3: Do you need to print the result without a newline?
Hint 4: Did you intend to use a bitwise & instead of logical &&.?
Optional
Hint 1: Do you need to case the division by 5 to int?