Program keeps spamming numbers? - c++

#include <iostream>
using namespace std;
int main(){
int a;
int b;
int dif;
cout<<"insert a: "<<endl;
cin>>a;
cout<<"insert b: "<<endl;
cin>>b;
if(a>b){
while(dif>=3){
dif=a-b;
cout<<dif;
}
}else{
while(dif>=3){
dif=b-a;
cout<<dif;
}
}
}
This is supposed to be a program that reads two numbers and keeps subtracting the smaller one from the bigger one until the difference is < 3 units. While it does this it should also output the difference at every iteration and for some reason it spams the difference or doesnt output anything. Help?

Two problems in your while loops:
while(dif>=3){
dif=a-b;
cout<<dif;
}
First, dif is used uninitialized and using it will cause undefined behavior. After you fix that the loop will still not do what you want.
dif=a-b; will assign to dif the same value in every iteration, hence the loop will run either never (condition is false before the loop), once (condition is false after the assignment), or forever (condition is still true after the assignment). I suppose this isn't the intended behavior.
...and keeps subtracting the smaller one from the bigger one until the difference is < 3 units.
You forgot to actually subtract one number from the other. That would be (in case a is the bigger):
while ( a-b >= 3) a -= b;
or with an additional variable (I don't think it helps, but rather adds complexity):
int diff = a-b;
while (diff >= 3) {
a -= b;
diff = a-b;
}

You need to initialize dif to be a number, e.g. int dif = 0;. C++ doesn't say what happens when you manipulate or use an uninitialized variable, so anything can happen and your program won't work consistently- this is probably why you've had it produce no output. This phenomenon is known as undefined behavior- see here for a full explanation.
Additionally, your loops also go infinite- if a is greater than b, dif >=3, and you set dif = a - b, dif is always the same, so the condition will always be true, and thus your code never stops running. You need to subtract and reassign the variable first so the values change, and then update dif:
a = a - b
dif = a - b
The second loop has the same problem.

There are two issue here ..
diff is not assigned any default value so it gets random value, if it will be greater or equal than 3 it will print infinity and if it is less than it will do nothing.
initiaalize the diff with diff=abs(b-a)
if by chance diff enter the loop then on every iteration diff is not changing as a and b remain same. So change the logic.
Instead of if else and two while loops just use diff=abs(b-a)
Good Luck

Related

Why is the "if" not executed within a loop?

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.

Multiply numbers which are divisible by 3 and less than 10 with a while loop in c++?

In C++, I should write a program where the app detects which numbers are divisible by 3 from 1 till 10 and then multiply all of them and print the result. That means that I should multiply 3,6,9 and print only the result, which is 162, but I should do it by using a "While" loop, not just multiplying the 3 numbers with each other. How should I write the code of this? I attached my attempt to code the problem below. Thanks
#include <iostream>
using namespace std;
int main() {
int x, r;
int l;
x = 1;
r = 0;
while (x < 10 && x%3==0) {
r = (3 * x) + 3;
cout << r;
}
cin >> l;
}
Firstly your checking the condition x%3 == 0 brings you out of your while - loop right in the first iteration where x is 1. You need to check the condition inside the loop.
Since you wish to store your answer in variable r you must initialize it to 1 since the product of anything with 0 would give you 0.
Another important thing is you need to increment the value of x at each iteration i.e. to check if each number in the range of 1 to 10 is divisible by 3 or not .
int main()
{
int x, r;
int l;
x = 1;
r = 1;
while (x < 10)
{
if(x%3 == 0)
r = r*x ;
x = x + 1; //incrementing the value of x
}
cout<<r;
}
Lastly I have no idea why you have written the last cin>>l statement . Omit it if not required.
Ok so here are a few hints that hopefully help you solving this:
Your approach with two variables (x and r) outside the loop is a good starting point for this.
Like I wrote in the comments you should use *= instead of your formula (I still don't understand how it is related to the problem)
Don't check if x is dividable by 3 inside the while-check because it would lead to an too early breaking of the loop
You can delete your l variable because it has no affect at the moment ;)
Your output should also happen outside the loop, else it is done everytime the loop runs (in your case this would be 10 times)
I hope I can help ;)
EDIT: Forget about No.4. I didn't saw your comment about the non-closing console.
int main()
{
int result = 1; // "result" is better than "r"
for (int x=1; x < 10; ++x)
{
if (x%3 == 0)
result = result * x;
}
cout << result;
}
or the loop in short with some additional knowledge:
for (int x=3; x < 10; x += 3) // i know that 3 is dividable
result *= x;
or, as it is c++, and for learning purposes, you could do:
vector<int> values; // a container holding integers that will get the multiples of 3
for (int x=1; x < 10; ++x) // as usual
if ( ! x%3 ) // same as x%3 == 0
values.push_back(x); // put the newly found number in the container
// now use a function that multiplies all numbers of the container (1 is start value)
result = std::accumulate(values.begin(), values.end(), 1, multiplies<int>());
// so much fun, also get the sum (0 is the start value, no function needed as add is standard)
int sum = std::accumulate(values.begin(), values.end(), 0);
It's important to remember the difference between = and ==. = sets something to a value while == compares something to a value. You're on the right track with incrementing x and using x as a condition to check your range of numbers. When writing code I usually try and write a "pseudocode" in English to organize my steps and get my logic down. It's also wise to consider using variables that tell you what they are as opposed to just random letters. Imagine if you were coding a game and you just had letters as variables; it would be impossible to remember what is what. When you are first learning to code this really helps a lot. So with that in mind:
/*
- While x is less than 10
- check value to see if it's mod 3
- if it's mod 3 add it to a sum
- if not's mod 3 bump a counter
- After my condition is met
- print to screen pause screen
*/
Now if we flesh out that pseudocode a little more we'll get a skeletal structure.
int main()
{
int x=1//value we'll use as a counter
int sum=0//value we'll use as a sum to print out at the end
while(x<10)//condition we'll check against
{
if (x mod 3 is zero)
{
sum=x*1;
increment x
}
else
{
increment x
}
}
//screen output the sum the sum
//system pause or cin.get() use whatever your teacher gave you.
I've given you a lot to work with here you should be able to figure out what you need from this. Computer Science and programming is hard and will require a lot of work. It's important to develop good coding habits and form now as it will help you in the future. Coding is a skill like welding; the more you do it the better you'll get. I often refer to it as the "Blue Collar Science" because it's really a skillset and not just raw knowledge. It's not like studying history or Biology (minus Biology labs) because those require you to learn things and loosely apply them whereas programming requires you to actually build something. It's like welding or plumbing in my opinion.
Additionally when you come to sites like these try and read up how things should be posted and try and seek the "logic" behind the answer and come up with it on your own as opposed to asking for the answer. People will be more inclined to help you if they think you're working for something instead of asking for a handout (not saying you are, just some advice). Additionally take the attitude these guys give you with a grain of salt, Computer Scientists aren't known to be the worlds most personable people. =) Good luck.

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;