First Steps in (C) Programming, introduction - Basic Arithmetic Operations
(Page 7 of 8 )
In C, an arithmetic statement is of the following form:
Variable_Name = Arithmetic_Expression;
The arithmetic expression on the right of the=operator specifies a calculation using values stored in variables and/or explicit numbers that are combined using arithmetic operators such as addition (+), subtraction (-), multiplication (*), and division (/). There are also other operators, as you’ll see.
In the previous example, the arithmetic statement was
Total_Pets = Cats + Dogs + Ponies + Others;
The effect of this statement is to calculate the value of the arithmetic expression to the right of the=and store that value in the variable specified on the left.
In C, the=symbol defines an action. It doesn’t specify that the two sides are equal, as it does in mathematics. It specifies that the value resulting from the expression on the right is to be stored in the variable on the left. This means that you could have
Total_Pets = Total_Pets + 2;
This would be ridiculous as a mathematical equation, but in programming it’s fine. Let’s look at it in context. Imagine you’d rewritten the last part of the program to include the preceding statement. Here’s a fragment of the program as it would appear with the statement added:
Total_Pets = Cats + Dogs + Ponies + Others;
/* Value stored is 50 */
Total_Pets = Total_Pets + 2; /* Value stored is 52 */
printf("The total number of pets is: %d", Total_Pets);
After executing the first statement here,Total_Petscontains the value 50. Then, in the second line, you add 2 to that value and store the result back in the variableTotal_Pets. The final total that will be displayed is therefore 52.
NOTE In assignment operations, the expression on the right side of the=sign is evaluated first, and the result is then stored in the variable on the left. The new value replaces the value that was previously contained in the variable to the left of the assignment operator.
Any expression that results in a numeric value is described as an arithmetic expression. The following are all arithmetic expressions:
3
1+2
Total_Pets
Cats + Dogs - Ponies
Evaluating any of these expressions produces a single numeric value. In a moment, you’ll take a closer look at how an expression is made up, and you’ll look into the rules governing its evaluation. First, though, you’ll try some simple examples using the basic arithmetic operators that you have at your disposal. Table 2-1 shows these operators.
Table 2-1. Basic Arithmetic Operators
Operator + | Action Addition |
- | Subtraction |
* / % | Multiplication Division Modulus |
You may not have come across the modulus operator before. It just calculates the remainder after dividing the value of the expression on the left of the operator by the value of the expression on the right. For this reason it’s sometimes referred to as the remainder operator. The expression 12%5 would produce 2, because 12 divided by 5 leaves a remainder of 2. You’ll look at this in more detail shortly. All these operators work as you’d expect with the exception of division, which has a slight aberration from the norm when applied to integers, as you’ll see. Let’s try some more arithmetic operations.
..........................................................................................
Try It Out: Subtraction and Multiplication
Let’s look at a food-based program that demonstrates subtraction and multiplication:
/* Program 2.5 Calculations with cookies */ #include <stdio.h>
void main()
{
int cookies = 5;
int cookie_calories = 125; /* Calories per cookie */
int total_eaten = 0; /* Total cookies eaten */
int eaten = 2; /* Number to be eaten */
cookies = cookies - eaten; /* Subtract number eaten from cookies */
total_eaten = total_eaten + eaten;
printf("\nI have eaten %d cookies. There are %d cookies left",
eaten, cookies);
eaten = 3; /* New value for cookies to be eaten */
cookies = cookies - eaten; /* Subtract number eaten from cookies */
total_eaten = total_eaten + eaten;
printf("\nI have eaten %d more. Now there are %d cookies left\n",
eaten, cookies);
printf("\nTotal energy consumed is %d calories.\n",
total_eaten*cookie_calories);
}
This program produces the following output:
--------------------------------------------
I have eaten 2 cookies. There are 3 cookies left
I have eaten three more. Now there are 0 cookies left
Total energy consumed is 625 calories.
--------------------------------------------
HOW IT WORKS
You first declare and initialize three variables of typeint:
int cookies = 5;
int cookie_calories = 125; /* Calories per cookie */
int total_eaten = 0; /* Total cookies eaten */
You’ll use thetotal_eatenvariable to accumulate the total number of cookies eaten as execution of the program progresses, so you initialize it to 0.
The next variable that you declare and initialize holds the number of cookies to be eaten next:
int eaten = 2; /* Number to be eaten */
You use the subtraction operator to subtracteatenfrom the value ofcookies:
cookies = cookies - eaten; /* Subtract number eaten from cookies */
The result of the subtraction is stored back in the variablecookies, so the value of cookies will now be 5 – 2, which is 3.
Because you’ve eaten some cookies, you increment the count of the total eaten by the value ofeaten:
total_eaten = total_eaten + eaten;
You add the current value ofeaten, which is 2, to the current value oftotal_eaten, which is 0. The result, 2, is stored back in the variabletotal_eaten.
Theprintf()statement displays the number of cookies that are left:
printf("\nI have eaten %d cookies. There are %d cookies left",
eaten, cookies);
I couldn’t fit the statement in the space available, so after the comma following the first argument toprintf(), I put the rest of the statement on a new line. You can spread statements out like this to make them easier to read or fit within a given width on the screen.
Note that you could not split the string that is the first argument in this way. An explicit newline character isn’t allowed in the middle of a string. When you need to split a string over two or more lines, each segment of the string on a line must have its own pair of double quotes delimiting it. For example, you could write the previous statement as follows:
printf("\nI have eaten %d cookies. "
" There are %d cookies left",
eaten, cookies);
Where there are two or more strings immediately following one another like this, the compiler will join them together to form a single string.
You display the values stored ineaten andcookies using the conversion specifier,%d, for integer values. The value ofeatenwill replace the first%din the output string, and the value ofcookieswill replace the second. The string will be displayed starting on a new line because of the\nat the beginning.
The next statement sets the variableeatento a new value:
eaten = 3; /* New value for cookies to be eaten */
The new value, 3, replaces the previous value stored ineaten, which was 2. You then go through the same sequence of operations as you did before:
cookies = cookies - eaten; /* Subtract number eaten from cookies */
total_eaten = total_eaten + eaten;
printf("\nI have eaten %d more. Now there are %d cookies left\n",
eaten, cookies);
Finally, you calculate and output the number of calories corresponding to the number of cookies eaten:
printf("\nTotal energy consumed is %d calories.\n",
total_eaten*cookie_calories);
Here the second argument to theprintf()function is an arithmetic expression rather than just a variable. The compiler will arrange for the result of the expressiontotal_eaten*cookie_caloriesto be stored in a temporary variable, and that value will be passed as the second argument to theprintf()function. You can always use an expression for an argument to a function as long as it evaluates to a result of the required type.
Easy, isn’t it? Let’s take a look at division and the modulus operator.
..........................................................................................
..........................................................................................
Next: Try It Out: Division and the Modulus Operator >>
More C++ Articles
More By Apress Publishing
|
This article is excerpted from chapter two of the book Beginning C, written by Ivor Horton (Apress, 2004; ISBN: 1590592530). Check it out today at your favorite bookstore. Buy this book now.
|
|