Up to now, you have worked with variables where you stored a value that you later used. After the initial assignment, the value of the variable did not change. Now you are ready to go to the next step, which is to study a case when a variable’s value changes during the program run, in other words, when a new value is determined from the old one.
Ten More, Revisited
First you will return to the task of adding ten to a number, which you studied in Chapter 8. The program’s goal is to present a value that is greater by ten than the number entered by the user (see Figure 13-1).
Figure 13-1 Displaying the user’s number plus ten
Task
You will now solve this task in a new way; specifically, you will store the calculation result in the same variable where you originally stored the entered number.
This is not necessarily a better solution, but you will learn how to build upon it further in later sections.
Solution
Here is the code:
static void Main(string[] args)
{
// Input
Console.Write("Enter a number: ");
string input = Console.ReadLine();
int number = Convert.ToInt32(input);
// Calculation
number = number + 10;
// Result output
Console.WriteLine("Number ten more greater is: " + number);
// Waiting for Enter
Console.ReadLine();
}
Discussion
The core statement of the solution is as follows: number = number + 10;. This statement is unusual in the sense that the same thing—the variable number—appears on both sides of the equal sign!
The computer executes the statement like this: “Take the present value of the variable number, add ten to it, and store the result as the new value of the variable number.” Thus, the net result of the statement is augmenting number’s value by ten.
Compound Assignment
There is a nice shortcut for doing the same thing, which is called compound assignment. You will study this now.
Task
You will solve the previous exercise using the more concise compound assignment.
Solution
Here is the code:
static void Main(string[] args)
{
// Input
Console.Write("Enter a number: ");
string input = Console.ReadLine();
int number = Convert.ToInt32(input);
// Calculation using compound assignment
number += 10; // same as number = number + 10;
// Result output
Console.WriteLine("Number ten more greater is: " + number);
// Waiting for Enter
Console.ReadLine();
}
Note
In this code, you use the compound assignment operator (+=), which is a shortcut that does the same thing as the previous solution. You will see compound assignments in all C-family programming languages.
Further Compound Assignments
Did you like compound assignment? There are even more similar assignments to use when working with other arithmetic operations.
Task
I will show you a program that illustrates compound assignment in connection with subtraction, multiplication, and division (see Figure 13-2).
Figure 13-2 Compound assignment
Solution
Here is the code:
static void Main(string[] args)
{
// Input
Console.Write("Enter a number: ");
string input = Console.ReadLine();
int number = Convert.ToInt32(input);
Console.WriteLine();
// With subtraction
number -= 5; // same as number = number - 5;
Console.WriteLine("After decrease by 5: " + number);
// With multiplication
number *= 10; // same as number = number * 10;
Console.WriteLine("Ten times greater: " + number);
// With division
number /= 2; // same as number = number / 2;
Console.WriteLine("Decreased to one half: " + number);
// Waiting for Enter
Console.ReadLine();
}
Note
The program works with the same variable every time!
The division here is integer division since both number and 2 are ints.
Incrementing and Decrementing
By far the most frequent change for a variable is a change by 1. That is why there are special super-concise ways for how to make such calculations.
Task
You’ll now get acquainted with the increment operator (++) and the decrement operator (--), as shown in Figure 13-3.
Figure 13-3 Increment and decrement operators
Solution
Here is the code:
static void Main(string[] args)
{
// Input
Console.Write("Enter a number: ");
string input = Console.ReadLine();
int number = Convert.ToInt32(input);
// Increasing by 1 using INCREMENT OPERATOR
number++; // same as number = number + 1;
Console.WriteLine("Increased by 1: " + number);
// Decreasing by 1 using DECREMENT OPERATOR
number--; // same as number = number - 1;
Console.WriteLine("Back again: " + number);
// Waiting for Enter
Console.ReadLine();
}
Compound Assignment and Text
Since the + operator can be used with text, you can use the compound assignment operator (+=) with text, too. You will probably use this frequently.
Task
This task will get you familiar with text concatenations using compound assignment (see Figure 13-4).
Figure 13-4 Text concatenations using compound assignment
Solution
Here is the code:
static void Main(string[] args)
{
// Initial value (empty text)
string books = "";
// Appending
books += "Homage to Catalonia" + Environment.NewLine;
books += "Silent Spring" + Environment.NewLine;
books += "The beat of a different drum" + Environment.NewLine;
// Output
Console.WriteLine("Valuable books");
Console.WriteLine("--------------");
Console.WriteLine(books);
// Waiting for Enter
Console.ReadLine();
}
Progressive Summation
Progressive summation is an important principle of summing a large number of values. It means summing them not all at once in a single statement but summing them one by one, progressively accumulating intermediate results in a special variable.
Task
You will write a program that progressively sums three entered numbers. Sure, summing three numbers would be more conveniently done at once in a single line. However, I want to illustrate the important principle of progressive summation on a simple example and get you used to the idea before covering a more complex topic, namely, loops (see Figure 13-5).
Figure 13-5 Progressively summing three entered numbers
Solution
Here is the code:
static void Main(string[] args)
{
// Preparation - variable to accumulate intemediate result
int sum = 0;
// Input - 1. number
Console.Write("Enter first number: ");
string input = Console.ReadLine();
int number = Convert.ToInt32(input);
// Adding first number to intermediate result
sum += number;
// Input - 2. number
Console.Write("Enter second number: ");
input = Console.ReadLine();
number = Convert.ToInt32(input);
// Adding second number to intermediate result
sum += number;
// Input - 3. number
Console.Write("Enter third number: ");
input = Console.ReadLine();
number = Convert.ToInt32(input);
// Adding third number to intermediate result
sum += number;
// Output
Console.WriteLine();
Console.WriteLine("Sum of entered numbers: " + sum);
// Waiting for Enter
Console.ReadLine();
}
Multiple Text Join
Again, since the + operator can be used with text, too, you can extend the principle of progressive summation to text. In this context, it may rather be called progressive accumulation.
Task
You will write a program that progressively accumulates names entered by the user. It will be interesting to make two accumulations; the first one is in the original order, and the second one is in the reverse order.
For simplicity, you will work with three values only (see Figure 13-6).
Figure 13-6 Progressively accumulating names
Solution
Here is the code:
static void Main(string[] args)
{
// Preparation - variables to accumulate intermediate results
string inOriginalOrder = "";
string inReversedOrder = "";
// Input of the first person
Console.Write("Enter first person: ");
string person = Console.ReadLine();
// Appending the first person to intermediate result
inOriginalOrder += person + Environment.NewLine;
inReversedOrder = person + Environment.NewLine + inReversedOrder;
// Input of the second person
Console.Write("Enter second person: ");
person = Console.ReadLine();
// Appending the second person to intermediate result
inOriginalOrder += person + Environment.NewLine;
inReversedOrder = person + Environment.NewLine + inReversedOrder;
// Input of the third person
Console.Write("Enter third person: ");
person = Console.ReadLine();
// Appending the third person to intermediate result
inOriginalOrder += person + Environment.NewLine;
inReversedOrder = person + Environment.NewLine + inReversedOrder;
// Output
Console.WriteLine();
Console.WriteLine("Entered persons");
Console.WriteLine("---------------");
Console.WriteLine(inOriginalOrder);
Console.WriteLine("In reversed order");
Console.WriteLine("-----------------");
Console.WriteLine(inReversedOrder);
// Waiting for Enter
Console.ReadLine();
}
Note
It is interesting to note that when joining the people’s names in reverse order, the compound assignment is of no help.
Summary
The central topic of this chapter has been the accumulation of values in the same variable. Contrary to the programs so far, the programs here were repeatedly changing the value of a variable, usually using its original value, and modifying it somehow. Specifically, you studied the following:
Statements such as variable = variable + change; that take the present value of variable, add change to it, and store the result as a new value of variable
Compound assignments such as variable += change;, which are short equivalents of previous statements
Compound assignments with other arithmetic operations: -=, *=, /=
Compound assignments with text (only +=)
Incrementing (adding 1) and decrementing (subtracting 1) variables using the super-short notation of variable++; and variable--;
At the end of the chapter, you got acquainted with the principle of progressive summation (and progressive accumulation), which means summing numbers one by one while storing intermediate results in a special variable. This principle is mostly used when summing a large number of values, and you will appreciate its extreme importance when studying loops later in this book.