Assignment Operators
Assignment operator (=) is used for assignment a value to a variable and for performing computations.
Assignment statement has the syntax:
variable = expression;
Expression is any combination of constants, variables, and function calls that can be evaluated to yield a result.
Example:
length = 25;
cMyCar = “Mercedes”;
sum = 3 + 7;
newtotal = 18.3*amount;
slope = (y2 – y1)/(x2 – x1);
The order of events when the computer executes an assignment statement is
- Evaluate the expression on the right hand side of the assignment operator.
- Store the resultant value of the expression in the variable on the left hand side of the assignment operator.
Note:
1. It’s important to note that the equal sign in C++ does not have the same meaning as an equal sign in mathematics.
2. Each time a new value is stored in a variable, the old one is overwritten.
Example
// This program calculates the volume of a cylinder,
// given its radius and height
#include <iostream.h>
int main()
{
float radius, height, volume;
radius = 2.5;
height = 16.0;
volume = 3.1416 * radius * radius * height;
cout << "The volume of the cylinder is " << volume << endl;
return 0;
}
The output of the above program:
The volume of the cylinder is 314.16
We can write multiple assignments, such as a = b = c = 25;. Because the assignment operator has a right-to-left associativity, the final evaluation proceeds in the sequence
c = 25;
b = 25;
c = 25;
Data Type Conversion across Assignment Operator
Note that data type conversion can take place across assignment operators, that is, the value of the expression on the right side of the assignment operator is converted to the data type of the variable to the left side of the assignment operator.
For example, if temp is an integer variable, the assignment temp = 25.89 causes the integer value 25 to be stored in the integer variable temp.
Assignment Variations
C++ also use a shorthand notation to perform an operation and an assignment at the same time. This is denoted by an operator followed by an equal sign. For example, to add 4 to the variable x and assign x to the result, you say: x += 4. Figure 1 illustrates assignment operator and all assignment variations.
Assignment statements such as sum += 10 or its equivalent, sum = sum + 10, are very common in C++ programming.
Increment and decrement operators
For the special case in which a variable is either increased or decreased by 1, C++ provides two unary operators: increment operator and decrement operator.
The increment (++) and decrement (--) unary operators can be used as prefix or postfix operators to increase or decrease value.
A prefix operator is placed before a variable and returns the value of the operand after the operation is performed.
A postfix operator is placed after a variable and returns the value of the operand before the operation is performed.
Prefix and postfix operators have different effects when used in a statement
b = ++a;
will first increase the value of a to 6, and then assign that new value to b. It is equivalent to
a = a +1;
b = a;
On the other hand, execution of the statement
b = a++;
will first assign the value of 5 to b, and then increase the value of a to 6. It is now equivalent to
b = a;
a = a + 1;
The decrement operators are used in a similar way.
Example
// Preincrementing and postincrementing
#include <iostream.h>
int main()
{
int c;
c = 5;
cout << c << endl; // print 5
cout << c++ << endl; // print 5 then postincrement
cout << c << endl << endl; // print 6
c = 5;
cout << c << endl; // print 5
cout << ++c << endl; // preincrement then print 6
cout << c << endl; // print 6
return 0; // successful termination
}
The output of the above program:
5
5
6
5
6
6
Formatting Number for Program Output
Besides displaying correct results, a program should present its results attractively with good formats.
Stream Manipulators
Stream manipulator functions are special stream functions that change certain characteristics of the input and output.
The main advantage of using manipulator functions is they facilitate the formatting of the input and output streams.
- setw(): The setw() stands for set width. This manipulator is used to specify the minimum number of the character positions on the output field a variable will consume.
- setprecision(): The setprecision() is used to control the number of digits of an output stream display of a floating point value. Setprecision(2) means 2 digits of precision to the right of the decimal point.
To carry out the operations of these manipulators in a user program, you must include the header file <iomanip.h>.
Example
#include <iostream.h>
#include <iomanip.h>
int main()
{
cout << setw(3) << 6 << endl
<< setw(3) << 18 << endl
<< setw(3) << 124 << endl
<< "---\n"
<< (6+18+124) << endl;
return 0;
}
The output of the above program:
Example:
cout << “|” << setw(10)
<< setioflags(ios::fixed)<< setprecision(3) << 25.67<<”|”;
causes the printout
- setiosflags: This manipulator is used to control different input and output settings.
setioflag(ios::fixed) means the output field will use conventional fixed-point decimal notation.
setiosflag(ios::showpoint) means the output field will show the decimal point for floating point number.
setiosflag(ios::scientific) means the output field will use exponential notation.
Note: In the absence of the ios::fixed flag, a floating point number is displayed with a default of 6 significant digits. If the integral part of the number requires more than 6 digits, the display will be in exponential notation.
Below are some other format flags for use with setiosflags().
Example
// This program will illustrate output conversions
#include <iostream.h>
#include <iomanip.h>
int main()
{
cout << "The decimal (base 10) value of 15 is " << 15 << endl
<< "The octal (base 8) value of 15 is "
<< setiosflags(ios::oct) << 15 << endl
<< "The hexadecimal (base 16) value of 15 is "
<< setiosflags(ios::hex) << 15 << endl;
return 0;
}
The output of the above program:
The decimal (base 10) value of 15 is 15
The octal (base 8) value of 15 is 17
The hexadecimal (base 16) value of 15 is f
To designate an octal integer constant, the number must have a leading 0. Hexadecimal number are denoted using a leading 0x.
Example
// Octal and hexadecimal integer constant
#include <iostream.h>
int main()
{
cout << "The decimal value of 025 is " << 025 << endl
<< "The decimal value of 0x37 is "<< 0x37 << endl;
return 0;
}
The output of the above program:
The decimal value of 025 is 21
The decimal value of 0x37 is 55
Using Mathematical Library Functions
Although addition, subtraction, multiplication and division are easily accomplished using C++’s arithmetic operators, no such operators exist for finding the square root of a number or determining trigonometric values. To facilitate such calculations, C++ provides standard library functions that can be included in a program.
Functions are normally called by writing the name of the function, followed by a left parenthesis, followed by the argument (or a comma-separated list of arguments) of the function, followed by a right parenthesis. For example, a programmer desiring to calculate and print the square root of 900.0 might write:
cout << sqrt(900.0);
When this statement is executed, the math library function sqrt is called to calculate the square root of the number contained in the parentheses (900.0). The number 900.0 is the argument of the sqrt function. The preceding statement would print 30. The sqrt function takes an argument of type double and returns a result of type double.
If your program uses mathematic function sqrt(), it should have the preprocessor command #include<math.h> in the beginning of the program. This makes a mathematical library accessible. Below are some commonly used mathematical functions provided in C++.
Except abs(a), the functions all take an argument of type double and return a value of type double.
Example
// this program calculates the area of a triangle
// given its three sides
#include <iostream.h>
#include <math.h>
int main()
{
double a,b,c, s;
a = 3;
b = 4;
c = 5;
s = (a+b+c)/2.0;
area = sqrt(s*(s-a)*(s-b)*(s-c));
cout << "The area of the triangle = " << area << endl;
return 0;
}
The output of the above program:
The area of the triangle = 6.0
Casts
We have already seen the conversion of an operand’s data type within mixed-mode expressions and across assignment operators. In addition to these implicit data type conversions that are automatically made within mixed-mode expressions and assignment, C++ also provides for explicit user-specified type conversion. This method of type conversion is called casting. The word cast is used in the sense of “casting into a mold.”
Casting or type casting, copies the value contained in a variable of one data type into a variable of another data type.
The C++ syntax for casting variables is
variable = new_type( old_variable);
where the new_type portion is the keyword representing the type to which you want to cast the variable.
Example:
int iNum = 100;
float fNum;
fNum = float (inum);
If you do not explicitly cast a variable of one data type to another data type, then C++ will try to automatically perform the cast for you.
Program Input Using the CIN Object
So far, our programs have been limited in the sense that all their data must be defined within the program source code.
We will now learn how to write programs which enable data to be entered via the keyboard, while the program is running.
Such programs can be made to operate upon different data every time they run, making them much more flexible and useful.
Standard Input Stream
The cin object reads in information from the keyboard via the standard input stream.
The extraction operator (>>) retrieves information from the input stream.
When the statement cin >> num1; is encountered, the computer stops program execution and accepts data from the keyboard. The user responds by typing an integer (or float) and then pressing the Enter key (sometimes called the Return key) to send the number to the computer. When a data item is typed, the cin object stores the integer (or float) into the variable listed after the >> operator.
The cin and cout stream objects facilitate interaction between the user and the computer. Because this interaction resembles a dialogue, it is often called conversational computing or interactive computing.
Example
#include <iostream.h>
int main()
{
int integer1, integer2, sum; // declaration
cout << "Enter first integer\n"; // prompt
cin >> integer1; // read an integer
cout << "Enter second integer\n"; // prompt
cin >> integer2; // read an integer
sum = integer1 + integer2;
cout << "Sum is " << sum << endl;
return 0; // indicate that program ended successfully
}
The output of the above program:
Enter the first integer
45
Enter the second integer
72
Sum is 117
Example
#include <iostream.h>
int main()
{
int integer1, integer2, sum; // declaration
cout << "Enter two integers\n"; // prompt
cin >> integer1 >> integer2; // read two integers
sum = integer1 + integer2;
cout << "Sum is " << sum << endl;
return 0;
}
The output of the above program:
Enter two integers
45 72
Sum is 117
Symbolic Constants
C++ introduces the concept of a named constant that is just like a variable, except that its value cannot be changed. The qualifier const tells the compiler that a name represents a constant. Any data type, built-in or user-defined, may be defined as const. If you define something as const and then attempt to modify it, the compiler will generate an error.
To define a constant in a program, we use const declaration qualifier.
Example:
const float PI = 3.1416;
const double SALESTAX = 0.05;
const int MAXNUM = 100;
Once declared, a constant can be used in any C++ statement in place of the number it represents.
Example
// this program calculates the circumference of a circle
// given its radius
#include <iostream.h>
int main()
{
const float PI = 3.1416
float radius, circumference;
radius = 2.0;
circumference = 2.0 * PI * radius;
cout << "The circumference of the circle is "
<< circumference << endl;
return 0;
}
The output of the above program:
The circumference of the circle is 12.5664
Focus on Problem Solving
In this section, we present a programming problem to further illustrate both the use of cin statements to accept user input data and the use of library functions for performing calculations.
Problem: Approximating the Exponential Function
The exponential function e^x, where e is known as Euler’s number (and has the value 2.718281828459045…) appears many times in descriptions of natural phenomena. The value of e^x can be approximated using the following series:
1 + x/1 + x^2/2 + x^3/6 + x^4/24 + x^5/120 + x^6/720 + …
Using this polynomial as a base, assume you are given the following assignment: Write a program that approximates e raised to a user input value of x using the first four terms of this series. For each approximation, display the value calculated by C++’s exponential function, exp(), the approximate value, and the absolute difference between the two. Make sure to verify your program using a hand calculation. Once the verification is complete, use the program to approximate e^4.
Using the top-down development procedure, we perform the following steps.
Step 1: Analyze the Problem
The statement of the problem specifies that four approximations are to be made using one, two, three, and four terms of the approximating polynomial, respectively. For each approximation, three output values are required: the value of produced by the exponential function, the approximate value, and the absolute difference between the two values. The structure of the required output display is as below (in symbolic form).
Realizing the each line in the display can only be produced by executing a cout statement, it should be clear that four such statements must be executed. Additionally, since each output line contains three computed values, each cout statement will have three items in its expression list.
The only input to the program consists of the value of x. This will, of course, require a single prompt and a cin statement to input the necessary value.
Step 2: Develop a Solution
Before any output items can be calculated, the program needs to prompt the user for a value of x and then accept the entered value. The output display consists of two title lines followed by four lines of calculated data. The title lines can be produced using two cout statements. Now let’s see how the data being displayed are produced.
The first item on the first data output line illustrated in Table 3.4 can be obtained using the exp() function. The second item on this line, the approximation to ex , can be obtained by using the first term in the polynomial that was given in the program specification. Finally, the third item on the line can be calculated by using the abs() function on the difference between the first two lines. When all of these items are calculated, a single cout statement can be used to display the three results on the same line.
The second output line illustrated in Table 3.4 displays the same type of items as the first line, except that the approximation to ex requires the two of two terms of the approximating polynomial. Notice also that the first item on the second line, the value obtained by the exp() function, is the same as the first item on the first line. This means that this item does not have to recalculated; the value calculated for the first line can simply be displayed a second line. Once the data for the second line have been calculated, a single cout statement can again be used to display the required values.
Finally, only the second and third items on the last two output lines shown in Figure 1 need to be recalculated because the first item on these lines is the same as previously calculated for the first line. Thus, for this problem, the complete algorithm described in pseudocode is:
Display a prompt for the input value of x.
Read the input value.
Display the heading lines.
Calculate the exponential value of x using the exp() function.
Calculate the first approximation.
Calculate the first difference.
Print the first output line.
Calculate the second approximation.
Calculate the second difference.
Print the second output line.
Calculate the third approximation.
Calculate the third difference.
Print the third output line.
Calculate the fourth approximation.
Calculate the fourth difference.
Print the fourth output line.
To ensure that we understand the processing used in the algorithm, we will do a hand calculation. The result of this calculation can then be used to verify the result produced by the program that we write. For test purposes, we use a value of 2 for x, which causes the following approximations:
Using the first term of the polynomial, the approximation is
e^2 = 1
Using the first two terms of the polynomial, the approximation is
e^2 = 1 + 2/1 = 3
Using the first three terms of the polynomial, the approximation is
e^2 = 3 + 2^2/2 = 5
Using the first four terms of the polynomial, the approximation is
e^2 = 5 + 2^3/6 = 6.3333
Notice that the first four terms of the polynomial, it was not necessary to recalculate the value of the first three terms; instead, we used the previously calculated value.
Step 3: Code the Algorithm
The following program represents a description of the selected algorithm in C++.
// This program approximates the function e raised to the x power
// using one, two, three, and four terms of an approximating polynomial.
#include <iostream.h>
#include <iomanip.h>
#include <math.h>
int main()
{
double x, funcValue, approx, difference;
cout << “\n Enter a value of x: “;
cin >> x;
// print two title lines
cout << “ e to the x Approximation Difference\n”
cout << “------------ --------------------- --------------\n”;
funcValue = exp(x);
// calculate the first approximation
approx = 1;
difference = abs(funcValue – approx);
cout << setw(10) << setiosflags(iso::showpoint) << funcValue
<< setw(18) << approx
<< setw(18) << difference << endl;
// calculate the first approximation
approx = 1;
difference = abs(funcValue – approx);
cout << setw(10) << setiosflags(iso::showpoint) << funcValue
<< setw(18) << approx
<< setw(18) << difference << endl;
// calculate the second approximation
approx = approx + x;
difference = abs(funcValue – approx);
cout << setw(10) << setiosflags(iso::showpoint) << funcValue
<< setw(18) << approx
<< setw(18) << difference << endl;
// calculate the third approximation
approx = approx + pow(x,2)/2.0;
difference = abs(funcValue – approx);
cout << setw(10) << setiosflags(iso::showpoint) << funcValue
<< setw(18) << approx
<< setw(18) << difference << endl;
// calculate the fourth approximation
approx = approx + pow(x,3)/6.0;
difference = abs(funcValue – approx);
cout << setw(10) << setiosflags(iso::showpoint) << funcValue
<< setw(18) << approx
<< setw(18) << difference << endl;
return 0;
}
In reviewing the program, notice that the input value of x is obtained first. The two title lines are then printed prior to any calculations being made. The value of ex is then computed using the exp() library function and assigned to the variable funcValue. This assignment permits this value to be used in the four difference calculations and displayed four times without the need for recalculation.
Since the approximation to the ex is “built up” using more and more terms of the approximating polynomial, only the new term for each approximation is calculated and added to the previous approximation. Finally, to permit the same variables to be reused, the values in them are immediately printed before the next approximation is made.
Step 4: Test and Correct the Program
The following is the sample run produced by the above program is:
The first two columns of output data produced by the sample run agree with our hand calculation. A hand check of the last column verifies that it also correctly contains the difference in values between the first two columns.