C++ Beginner Assignment Operators - c++

i'm a beginner in C++ and i'm doing this example code of assignment operators. I don't know what i'm doing wrong here.
#include <iostream>
using namespace std;
int main()
{
int x = 200; int y = 100;
x += y; cout << x << endl; //x += y; // x = x + y, x = 200 + 100, output 300.
x -= y; cout << x << endl; //x -= y; // x = x - y, x = 200 - 100, output 100.
x /= y; cout << x << endl; //x /= y; // x = x / y, x = 200 / 100, output 2.
x %= y; cout << x << endl; //x % y; // x = % y, x = 200 % 100, output 0.
return 0;
}
i'm getting the results for
x -= y = 200
x /= y = 2
x %= y = 2
when its suppose to be
x -= y = 100
x /= y = 2
x %= y = 0
its actually adding up the previous results. How do i stop the code from adding the result to the next line? Thanks!

As you mentioned in your comments in your code, the result of x += y is equivalent to x = x + y, which means the value of x will change. So it is no surprise that the new value of x, 300, is used in the next mathematical assignment.
If you want to avoid that, consider saving the result of x + y to another variable.
int x = 200;
int y = 100;
int x_addition = x + y;
std::cout << x_addition << std::endl;
Or, if its only usage is in displaying the result of the addition, do it all in one line.
int x = 200;
int y = 100;
std::cout << x + y << std::endl;

When x and y are variables and U is an operation x U= y is equivalent to:
x = x U y;
which means the original variable is being modified and assigned with the result.
You code is equivalent to:
x = x + y;
cout << x << endl; // x is now 300
x = x - y;
cout << x << endl; // x is now 200
x = x / y;
cout << x << endl; // x is now 2
x = x % y;
cout << x << endl; // x is now 2
If you want not to change x you want can save x in a temporary variable or just print the result:
int x = 200;
int y = 100;
cout << x - y << endl; // x unchanged
cout << x + y << endl; // x unchanged
cout << x / y << endl; // x unchanged
cout << x * y << endl; // x unchanged
Or:
int x = 200;
int x = 100;
int result = x + y;
cout << result << endl;
result = x - y;
cout << x << endl;
result = x / y;
cout << result << endl;
result = x % y;
cout << result << endl;
Note: since the = operator returns the value after the assignment cout << x += y << end can compile and print the assigned value.

Every time you are doing assignment like x += y;, it changing the value of x.
x += y;
is equivalent to
x = x + y;
Which means assignment. Value of x is changing. It's now 300. Same thing happening for latter assignments too.
Note: if you don't want to change the value of x and y, better do the assignments in other variable.
int x = 200, y = 100, t;
t = x + y; cout << t << endl;
t = x - y; cout << t << endl;
t = x * y; cout << t << endl;
t = (int) x / y; cout << t << endl;

You are expecting the original value of x and y to be kept forever, but it isn't. Assignments like x += y; or x = x + y; change the value of the variables (in this case x, that is, the one on the left side of the equal sign). The previous value is overwritten and therefore lost.
If you don't want to change the original values, you have to either assign the result to other variables (for example, one called temp, that you can overwrite every time), or you don't assign it at all, and you simply send to cout the result of the calculation.
As an example with a temp variable:
int x = 200; int y = 100; int temp;
temp = x + y; cout << temp << endl; //temp = x + y, temp = 200 + 100, output 300.
temp = x - y; cout << temp << endl; //temp = x - y, temp = 200 - 100, output 100.
Or, doing away with variables entirely:
cout << x + y << endl; // 200 + 100, output 300
cout << x - y << endl; // 200 - 100, output 100
Another way to see that the variables are overwritten (well, in this case it's only x) is to declare them as const:
const int x = 200; const int y = 100;
The program won't compile, because it tries to change constant variables.

Try resetting x back to 200 after each assignment. Like this:
#include <iostream>
using namespace std;
int main()
{
int x = 200; int y = 100;
x += y; cout << x << endl;
x = 200;
x /= y; cout << x << endl;
x = 200;
x %= y; cout << x << endl;
return 0;
}

You are using the accumulation operators so you're changing the value of 'x'.
x += y; // x = 200 + 100 = 300
x -= y; // x = 300 - 100 = 200
x /= y; // x = 200 / 100 = 2
x %= y; // x = 2 % 100 = 2
Instead you could do:
int x = 200;
int y = 100;
cout << x + y << endl;
cout << x - y << endl;
cout << x / y << endl;
cout << x % y << endl;
Or:
int x = 200;
int y = 100;
int result;
result = x + y;
cout << result << endl;
result = x - y;
cout << result << endl;
result = x / y;
cout << result << endl;
result = x % y;
cout << result << endl;

You are not counting on Addition operations value
x=200,y=100;
x+=y;//x=200+100=300,x=300,y=100
x-=y;//x=300-100=200,x=200,y=100
Here you are forgetting that there is ADDITION OPERATION before subtraction

Related

How can I make lists print horizontally in C++?

I used a for loop to generate a list of strings, and I've been trying to make them print horizontally instead of vertically.
Currently:
the list is printed vertically, up to 10.
Goal: To have the list printed horizontally.
Code for reference:
#include <iostream>
using namespace std;
int main()
{
int x = 10;
int y, z = 0;
int result;
for (z = 1; z <= x; z++)
{
cout << '\n';
for (y = 1; y <= z; y++)
{
result = z * y;
cout << z << " * " << y << " = " << result << '\n';
}
cout << '\n';
}
}
For the first block of number (1x1 .. 5x5), here's something similar to your expected output.
for (int x = 1; x <=5 ; x++) {
for (int y = 1; y <= 5; y++) {
if (y < x) {
cout << " ";
}
else {
cout << setw(3) << y << " x " << setw(4) << x << " = " << setw(4) << x * y << " ";
}
}
cout << endl;
}
Prints out this:
1 x 1 = 1 2 x 1 = 2 3 x 1 = 3 4 x 1 = 4 5 x 1 = 5
2 x 2 = 4 3 x 2 = 6 4 x 2 = 8 5 x 2 = 10
3 x 3 = 9 4 x 3 = 12 5 x 3 = 15
4 x 4 = 16 5 x 4 = 20
5 x 5 = 25
I'll leave it as an exercise for extending this to another set of rows for the 6 through 10 times tables.

Why var x display incorrectly?

#include <iostream> // подключаем библиотеку ввода-вывода
#include <cmath> // подключаем библиотеку математических функций
using namespace std;
int main()
{
float a, x, y = 0; // объявление переменных
cout << "Enter a variable: ";
cin >> a; // запрос на ввод a
cout << "Enter x variable: ";
cin >> x; // запрос на ввод x
cout << "a = " << a << ", x = " << x; // вывод a и x
y = (pow(x, 3) + sqrt(1 + pow(x, 3))) / (a + exp(x)); // формула расчета
cout << y;
}
Enter a variable: 6
Enter x variable: 7
a = 6, x = 70.327894
I can't understand why x == 70, when it must be 7. Also I don't know why cout << y; doesn't work. If I delete y = ... and cout << y, x display correctly.
I think, that it's my fault, because I'm new in C++ and don't know syntax well.
You're simply printing everything on the same line, you can either:
Print it after your two first result:
cout << "a = " << a << ", x = " << x; // вывод a и x
y = (pow(x, 3) + sqrt(1 + pow(x, 3))) / (a + exp(x)); // формула расчета
cout << ", y = " << y;
Output:
Enter a variable: 6
Enter x variable: 7
a = 6, x = 7, y = 0.327894
Or print y on another line
cout << "a = " << a << ", x = " << x << "\n"; // returns to another line
y = (pow(x, 3) + sqrt(1 + pow(x, 3))) / (a + exp(x)); // формула расчета
cout << "y = " << y;
Output:
Enter a variable: 6
Enter x variable: 7
a = 6, x = 7
y = 0.327894
a = 6, x = 70.327894
this doesn't mean x =70.327894.
x is 7 and the result y is 0.327894
you need to carefully print to the terminal, use << endl; and add some more labels so you can easily recognize the output of the math calculation...
bottomline: your rocket formula is working fine and you need to take another coffee... :)

What's wrong with my C++ variable(scope related)?

#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
int x = 0, y = 1, k = 5;
{
int x = 1;
x = 10;
cout << "x is " << x << ", y is " << y << endl;
}
cout << "x is " << x << " and k is " << k << endl;
cout << endl;
cout << endl;
{
int x = 5;
int y = 6;
{
int y = 7;
x = 2;
}
cout << "(x, y) is : (" << x << ", " << y << ")" << endl;
}
cin.get();
return 0;
}
The output is:
x is 10, y is 1
x is 0 and k is 5
(x, y) is : (2, 6)
I think (x,y) should be (5,6). Because that's the coordinates x and y are in.
You're modifying x from the outer scope here:
{
int y = 7; // local variable
x = 2; // variable from outer scope
}
If you had said int x = 2; then you could expect to get (5,6). But you didn't.
You have assigned value 2 to x in last scope hence it's (2,6).
Not how it works, because the variable x from the outer scope was the one you changed in the inner scope, where there is no other x to hide it. Consider this example of why this is necessary:
static const size_t N = 10;
size_t i = 0;
int array[N];
while (i < 10) {
const int x = i*i;
array[i] = x;
++i;
} // We're out of the block where i was incremented. Should this be an infinite loop?
// Should array be uninitialized because this is the scope it was in and we updated it in a nested scope?

Error in displaying the largest and smallest number

I was attempting to write a program for exercise 2.19 in How to Program, but I ran into some difficulties.
The program is supposed to have the user enter three integers and then display the sum, average, and product of those integers.
The only problem I am having is with displaying the largest and smallest. When I ran the program and entered three integers (8, 9, and 10), the output read Smallest is 8 AND Smallest is 9.
I was hoping you could tell me why.
#include <iostream>
using namespace std;
int main ()
{ int x, y, z, sum, ave, prod;
cout << "Input three different integers ";
cin >> x >> y >> z;
sum = x + y + z;
cout << "\nThe sum is " << sum;
ave = (x + y + z) / 3;
cout << "\nThe average is " << ave;
prod = x * y * z;
cout << "\nThe product is " << prod;
if (x < y, x < z)
{cout << "\nSmallest is " << x;}
if (y < x, y < z)
{cout << "\nSmallest is " << y;}
if (z < x, z < y)
{cout << "\nSmallest is " << z;}
if (x > y, x > z)
{cout << "\nLargest is " << x << endl;}
if (y > x, y > z)
{cout << "\nLargest is " << y << endl;}
if (z > x, z > y)
{cout << "\nLargest is " << z << endl;}
return 0;
}
P.S. I am doing this to study, this is not homework.
You need to rewrite this if condition
if (x < y, x < z)
to be
if (x < y && x < z)
and do the same for all of the remaining if conditions you have.
Edit:
All experssions seperated by comma will be evaluated so if you have something like that
x = 5, y = 6; it will evaluate both of them and set x to 5 and y to 6
but
z = (x=5, y=6); this will cause z to be set to 6 just like y as y=6 was the last term in the list of comma separated terms.
int main() {
std::cout << "Enter three numbers: ";
int sum = 0;
double avg = 0.;
int product = 0;
int smallest = std::numeric_limits<int>::max();
int largest = std::numeric_limits<int>::min(); // the initializers here might not be correct, but the gist is in place...
for (int i = 0; i < 3; ++i) {
int val = 0;
std::cin >> val;
sum += val;
avg += val;
product *= val;
if (val < smallest) smallest = val;
if (val > largest) largest = val;
}
avg /= 3.; // This can also be done in the for loop, I just forget how.
std::cout << "Sum: " << sum;
// etc... The calculations are all done.
}
Replace your commas, with && for an AND operator, meaning both of the conditions have to be true, or || which is an OR operator, if you want any or both conditions to be satisfied.
from C++ docs:
The comma operator (,) is used to separate two or more expressions that are included
where only one expression is expected. When the set of expressions has to be evaluated
for a value, only the rightmost expression is considered.
Instead of comma, you want &&
i.e.
if (x < y , x < z)
{cout << "\nSmallest is " << x;}
should be
if (x < y && x < z)
{cout << "\nSmallest is " << x;}
Use && in place of , inside your if conditions.
By now you realize that && is for AND and that you should use this operator instead of the comma, ,. But did you know you can also use they keyword and in place of its symbol equivalent?:
if ( x < y and x < z ) {
}

Operator Precedence Puzzle

I have variables with their initial value defined as: x = 10, y = 4, z = 1 and what's those variable values in y>>=x&0x2&&z ?
I would do:
y >>= ((Fun1) && z)
Fun1 = x&0x2, that is the bit operation of 1010 & 0010 = 0010, or 2 in decimal;
Fun1 && z returns 1, or 0001 in binary
Then my question is what is the operation of
y >>= 0001
gives me?
#include <iostream>
using namespace std;
int main()
{
int x = 10, y = 4, z = 1;
y >>= x&0x2&&z;
cout << "x: " << x << endl;
cout << "y: " << y << endl;
cout << "z: " << z << endl;
return 0;
}
When in doubt use braces
When in doubt use braces
When in doubt use braces
y >>= 1
is the same as
y = y >> 1
So it should effectively integer-divide y by 2.