We know how to perform common arithmetic operations. But there is also an operation that is common in programs, and does not have a specific mathematical symbol: incrementing the value of a variable in one unit:
a = a + 1;
In C# there is a more compact notation for this operation, and also for the opposite operation (decrement):
a++; is the same as a = a+1;
a--; is the same as a = a-1;
But there is more to discover about increment (and decrement): we can distinguish between "pre-increment" and "post-increment." We can make assignments like this one:
b = a++;
In this example, if "a" is 2, this instruction assigns to "b" the value of "a" and then increments that value of "a". Therefore, in the end we have b=2 and a=3 (post-increment: "a" is incremented after its value is assigned).
But if we write
b = ++a;
which first increments "a" and then assigns it to "b" (pre-increment), so a=3 y b=3.
Of course, we can also distinguish post-decrement (a--) and pre-decrement (--a).
Suggested exercises:
Ø Create a program that uses three variables x, y, z. Their initial values must be 15, -10, 2,147,483,647. It will increase the value of these variables. What results do you expect to get? Compare it with the results obtained by the program.
Ø What would be the result of the following operations? a=5; b=++a; c=a++; b=b*5; a=a*2;
Also, in C# we can make multiple assignments:
a = b = c = 1;
No comments:
Post a Comment