Arithmetic-Assignment

Assignment and Arithmetic Operators

download the slides used in this presentation
PowerPoint pptx | Acrobat pdf

Objectives

While engaging with this module, you will...

  1. learn how to assign values to variables
  2. perform basic mathematical operations
  3. discover common pitfalls when using variable arithmetic

Overloads

Operators allow us to modify and manipulate information. They are symbols that represent a commonly used operation, such as addition. We will start now an investigation of many of the operators in C++.

The Assignment Operator

The symbol used for assignment of a value to a variable is “=”. (Note: henceforth, I will identify the operators by putting them between double quotes. These quotation marks are not to be taken as part of the operator.) This is an unfortunate choice for assignment. I’ll elucidate on this issue later. Here is a typical use:

tax = income * RATE; // you can see clearly that RATE is a constant!

The compiler goes through three steps to execute this statement.

  1. The value of the rhs (right hand side) is determined. In this case, memory locations for income and RATE have to be read, and then those values multiplied.
  2. The types of the rhs and lhs are determined. If the type of the lhs can be “converted” to the type of the rhs without losing information, then it is done. If information would be lost in doing so, a compiler warning is issue. As far as I am concerned, a warning is as bad as an error – it needs to be fixed.
  3. The value of the rhs is copied into the memory location of the lhs. Thus, the lhs MUST BE A MODIFIABLE MEMORY LOCATION. That is, lhs cannot be a constant. Thus,

    RATE = .05; // not allowed!
    4 = income + 64; // not allowed!

OK, what do I mean by when I say “converted without losing information”? Suppose the lhs is a floating point type (generically, I will refer to them as float) and the lhs is an integer type (int). For the compiler to make the assignment, it will have to chop off the fractional part of the float. Thus, information is lost.

Sometimes you desire this result and you want to suppress the warning that would normally be issued. this is accomplished with a “cast”. A cast is a way to tell the compiler that you know what you are doing. Here is the C++ syntax: static_cast<type>(the variable). static_cast is a reserved word.

int someValue;
double Num1, Num2;
someValue = Num1 + Num2; // warning issued
someValue = static_cast<int>(Num1 + Num2); // no warning – OK

If it is the case that the compiler can convert one type to another without losing information, then a type promotion is done. Assigning an int to a float, for example, is not a problem; the int is promoted to a float without loss of information (no fractional part thrown out).

Arithmetic Operators

The arithmetic operators are “+”, “-”, “*”, “/”, “%”(modular arithmetic). If you use any of these operators on two operands of the same type, the result is that type. Mixing the types causes automatic promotion. For example, a float + an int results in a float since the int is promoted to a float. Modulo arithmetic is only allowed with integer types.

There are two topics that warrant attention here. They are integer division and mod arithmetic.

Integer division:

When an int (int-type) is divided by another int, the result is an int. Simple you say? Yes, but that can trip you up and cause your program to give erroneous results. Let me show you in this example. Suppose you write a program to convert Fahrenheit to Celcius. (See the programin module 2.) It must contain an assignment statement along the lines of

celc = (5/9)*(fahr – 32);

Well, there’s a big problem here. Regardless of the value of fahr that is used, celc will be assigned 0. How is that? Both of the literal constants 5 and 9 are stored by the compiler as integers. Integer division will give you 0 (9 goes into 5 zero times), and 0 times anything is 0. In this case, it is an easy fix:

celc = (5.0/9)*(fahr – 32);

But suppose we have this situation:

average_age = total_of_ages / numPeople;

Clearly, total_of_ages and numPeople should be declared as integer types. It makes no sense that they be floats. However, we want average_age to have a fractional part – a float. But the result of the quotient on the lhs will be an int. To make this work the way you wish is:

average_age = static_cast<float>(total_of_ages) / numPeople;

We cast either the numerator or the denominator or both, but NOT the quotient. Now, a float divided by an int will give you a float as desired. Notice that you have not changed the nature of either total_of_ages or numPeople; they are both still ints after this line of code is executed.

Modular Arithmetic

The mod operator, %, works this way: a mod b is the remainder after a is divided by b. Thus,

  • 4%7 is 4 (since 4/7 is 0 with remainder 4)
  • 7%3 is 1 (since 7/3 is 2 with remainder 1)
  • 27%3 is 0 (since 27/3 is 9 with remainder 0)

You may not think mod arithmetic is so important, but it can be very useful. Here’s an example. Suppose you read in an integer from a user of your program. It is read in to a variable named x. Now, without loss of generalization, let’s assume x is 5 digits long, and let’s represent it as x=abcde. So, e is the “ones” digit, d is the “tens” digit, etc. Thus, we don’t know any of these digits at compile time. But suppose that we need to know, say, the tens digit, d, at run-time. How can we extract that from the value x, entered by the user at run-time? Well, x%100 is the integer de. This is because 100 goes into x abc times with a remainder of de. Now, de/10 is d. That is, 10 goes into de d times. So we have it:

int tens_digit;
tens_digit = (x%100)/10; //assigns tens digit of x to variable tens_digit

Thus, you can now “tear down” a number if need be.

The Increment and Decrement Operators

At times, you will need to increment (or decrement) an integer variable’s value. That is, you want to do

val = val + 1; // retrieve val, add one, replace val’s value

This is common in looping structures (repeated operations). C++ provides a speedy version of this:

val++; //increment
++val;
val--; //decrement
--val;

These are complete C++ statements and, by themselves, are equivalent to val = val + 1; but are much faster. If this operation is repeated millions of times, the time savings is significant. If the operation is only used once or a few times, it is better to use val = val + 1; for clarity of code.

Beware! The two versions of increment (or decrement) are NOT the same. val++ is a post-increment while ++val is a pre-increment. It is when these statements are inserted into bigger statements that the difference becomes apparent. Suppose we have

int val = 6, num;
num = ++val;
// num is now 7, val is now 7

int val = 6, num;
num = val++;
// num is now 6, val is now 7

In any C++ statement, a pre-increment is executed before anything else, while a post-increment is executed last.

Other Fast Operators

C++ also has these operators:

x+=y; // equivalent to x = x + y;
x*=y; // equivalent to x = x * y;
x/=y;
x-=y;
x%=y;

These are simply faster versions of the expanded computations and assignments.

Chapter 5. Assignment and Data Statements

Assignment statements assign values to variables and array elements. Data statements and implied lists in data statements are used to initialize variables and array elements.

The following are the different types of Fortran assignment statements:

This chapter explains how to use each of these statements.

Arithmetic Assignment Statements

An arithmetic assignment statement assigns the value of an arithmetic expression to a variable or array element of type , , , , or . The form of an arithmetic statement is the following:

where v is the name of an , , , , or type variable or array element and e is an arithmetic expression.

When an arithmetic assignment statement is executed, the expression e is evaluated and the value obtained replaces the value of the entity to the left of the equal sign.

The values v and e need not be of the same type; the value of the expression is converted to the type of the variable or array element specified. Table 5-1 lists the type conversion rules.

Table 5-1. Type Conversion Rules

Declaration

Function Equivalent

INTEGER

INT(e)

REAL

REAL(e)

DOUBLE PRECISION

DBLE(e)

COMPLEX

CMPLX(e)

DOUBLE COMPLEX

DCMPLX(e)

The following are examples of arithmetic assignment statements:

Assign the value 4 to.

Assign the value 7 to .

Assign the value 29 to .

The following table gives the detailed conversion rules for arithmetic assignment statements. The functions in the table's second column are intrinsic functions described in Chapter 10, “Statement Functions and Subprograms” and Appendix A, “Intrinsic Functions”.

Table 5-2. Conversion rules for assignment statements

Variable or Array Element ()

or Expression ()

Expression ()

Expression ()

or

Assign to

: Truncate to integer and assign to

: Truncate to integer and assign to

: Truncate to integer and assign to

: Truncate real part of to integer and assign to

: Truncate real part of to integer and assign to

Append fraction () to and assign to

: Assign to

: Assign high-order portion of to ; low-order portion of is rounded

: Assign high-order part of to ; low-order part is rounded

: Assign real part of to ; imaginary part of not used

: Assign high-order part of real part of to ; low-order portion of real part is rounded

Append fraction () to and assign to

: Assign to high-order portion of ; low-order portion of is 0

: Assign to

: Assign high-order part of to ; low-order part is rounded

: Assign to high-order portion of ; low-order portion of is 0

: Assign real part of to

Append fraction () to and assign to

: Assign to high-order portion of ; low-order portion of is 0

: Assign to

: Assign high-order part of to ; low-order part is rounded

: Assign to high-order portion of ; low-order portion of is 0

: Assign real part of to

Append fraction to and assign to real part of ; imaginary part of is 0.0

: Assign to real part of ; imaginary part of is 0.0

: Assign high-order portion of to real part of ; low-order portion of is rounded; imaginary part of is 0.0

: Assign high-order portion of to real part of ; low-order part is rounded; imaginary part of is 0.0

: Assign to

: High-order parts of real and imaginary components of are assigned to ; low-order parts are rounded

Append fraction to and assign to ; imaginary part of is 0.0

: Assign to high-order portion of real part of ; imaginary part of is 0.0

: Assign to real part of ; imaginary part is 0.0

: Assign high-order portion of to real part of ; low-order part is rounded; imaginary part of is 0.0

: Assign to high-order parts of ; low-order parts of are 0

: Assign to

Append fraction to and assign to ; imaginary part of is 0.0

: Assign to high-order portion of real part of ; imaginary part of is 0.0

: Assign to real part of ; imaginary part is 0.0

: Assign high-order portion of to real part of ; low-order part is rounded; imaginary part of is 0.0

: Assign to high-order parts of ; low-order parts of are 0

: Assign to


Logical Assignment Statements

The logical assignment statement assigns the value of a logical expression to a logical variable or array element. It takes the form

where v is the name of a logical variable or logical array element and e is a logical expression.

When a logical assignment statement is executed, the value of the logical expression e is evaluated and replaces the value of the logical entity to the left of the equal sign. The value of the logical expression is either true or false.

Character Assignment

The character assignment statement assigns the value of a character expression to a character variable, array element, or substring. The form of a character assignment statement is

where v is the name of a character variable, array element, or substring and e is a character expression.

During the execution of a character string assignment statement, the character expression is evaluated and the resultant value replaces the value of the character entity to the left of the equal sign. None of the character positions being defined in v can be referenced in the evaluation of the expression e.

The entity v and character expression e can have different lengths. If the length of v is greater than the length of e, then the value of e is extended on the right with blank characters to the length of v. If the length of e is greater than the length of v, then the value of e is truncated on the right to the length of v.

The following is an example of character assignment:

CHARACTER U*5, V*5, W*7 U = 'HELLO' V = 'THERE' W(6:7) = V(4:5)

If an assignment is made to a character substring, only the specified character positions are defined. The definition status of character positions not specified by the substring remain unchanged.

Aggregate Assignment

An aggregate assignment statement assigns the value of each field of one aggregate to the corresponding field of another aggregate. The aggregates must be declared with the same structure. The form of an aggregate assignment statement is

where v and e are aggregate references declared with the same structure.

See Chapter 2, “Constants and Data Structures”, for more information.

The statement assigns a statement label to an integer variable and is used in conjunction with an assigned statement or an I/O statement. The form of a statement label assignment statement is

where s is a statement label of an executable statement or a statement that appears in the same program unit as the statement and e is an integer variable name.

A statement label assignment by the statement is the only way of defining a variable with a statement label value. A variable defined with a statement label value may be used only in an assigned statement or as a format identifier in an I/O statement. The variable thus defined must not be referenced in any other way until it has been reassigned with an arithmetic value.

An integer variable that has been assigned a statement label value can be redefined with the same statement label, a different statement label, or an arithmetic integer variable.

Examples using the statement are shown below:

Example 5-1. with

ASSIGN 100 TO kbranch . . . GO TO kbranch


Example 5-2. with I/O

ASSIGN 999 TO ifmt 999 FORMAT(f10.5) . . . READ (*, ifmt) x . . . WRITE (*, fmt = ifmt) z


Data Initialization

Variables, arrays, array elements, and substrings can be initially defined using the statement or an implied list in a statement. The subprogram is a means of initializing variables and arrays in named common blocks and is discussed in Chapter 4, “Specification Statements”.

Entities not initially defined or associated with an initialized entity are undefined at the beginning of the execution of a program. Uninitialized entities must be defined before they can be referenced in the program.

Implied Lists

The implied list initializes or assigns initial values to elements of an array.

Syntax

(dlist, i = e1, e2 [,e3] )

The following arguments are available with this statement:

dlist

a list of array element names and implied lists.

i

an integer variable name, referred to as the implied DO variable. It is used as a control variable for the iteration count.

e1

an integer constant expression specifying an initial value.

e2

an integer constant expression specifying a limit value.

e3

aan integer constant expression specifying an increment value.

e1, e2, and e3 are as defined in statements.

Method of Operation

An iteration count and the values of the implied variable are established from e1, e2, and e3 exactly as for a loop, except that the iteration count must be positive.

When an implied list appears in a statement, the dlist items are specified once for each iteration of the implied list with the appropriate substitution of values for any occurrence of the implied variable. The appearance of an implied variable in an implied has no effect on the definition status of that variable name elsewhere in the program unit. For an example of an implied list, see “DATA” in Chapter 4.

The range of an implied list is dlist.

Rules

  • The integer constant expressions used for e1, e2, and e3 can contain implied variables of other implied lists.

  • Any subscript expression in the list dlist must be an integer constant expression. The integer constant expression can contain implied variables of implied lists that have the subscript expression within their range.

Categories: 1

0 Replies to “Arithmetic-Assignment”

Leave a comment

L'indirizzo email non verrà pubblicato. I campi obbligatori sono contrassegnati *