ZeePedia

C++: Examples of Expressions, Use of Operators

<< C language: Variables, Data Types, Arithmetic Operators, Precedence of Operators
Flow Charting, if/else structure, Logical Operators >>
img
CS201 ­ Introduction to Programming
Lecture Handout
Introduction to programming
Lecture No. 4
Reading Material
Deitel & Deitel ­ C++ How to Program
chapter 1
1.22
Summary
Sample Program
o
Examples of Expressions
o
Use of Operators
o
Tips
o
Sample Program
Problem statement:
Calculate the average age of a class of ten students. Prompt the user to enter the age of
each student.
Solution:
Lets first sort out the problem. In the problem we will take the ages of ten students from
the user. To store these ages we will use ten variables, one variable for each student's
age. We will take the ages of students in whole numbers (in years only, like 10, 12, 15
etc), so we will use the variables of data type int. The variables declaration statement in
our program will be as follow:
int age1, age2, age3, age4, age5, age6, age7, age8, age9, age10;
We have declared all the ten variables in a single line by using comma separator ( , ).
This is a short method to declare a number of variables of the same data type.
After this we will add all the ages to get the total age and store this total age in a variable.
Then we will get the average age of the ten students by dividing this total age by 10. For
Page 23
img
CS201 ­ Introduction to Programming
the storage of total and average ages we need variables. For this purpose we use variable
TotalAge for the total of ages and AverageAge for average of ages respectively.
int TotalAge, AverageAge;
We have declared AverageAge as int data type so it can store only whole numbers. The
average age of the class can be in real numbers with decimal point (for example if total
age is 173 then average age will be 17.3). But the division of integers will produce
integer result only and the decimal portion is truncated. If we need the actual result then
we should use real numbers (float or double) in our program.
Now we have declared variables for storing different values. In the next step we prompt
the user to enter the age of first student. We simply show a text line on the screen by
using the statement:
cout << "Please enter the age of first student : " ;
So on the screen the sentence "Please enter the age of first student:" will appear.
Whenever we are requesting user to enter some information we need to be very clear i.e.
write such sentences that are self explanatory and user understands them thoroughly and
correctly. Now with the above sentence everyone can understand that age would be
entered for the first student. As we are expecting only whole numbers i.e. age in years
only i.e. 10, 12 etc, our program is not to expect ages as 13.5 or 12.3 or 12 years and 3
months etc. We can refine our sentence such, that the user understands precisely that the
age would be entered in whole number only.
After this we allow the user to enter the age. To, get the age entered by the user into a
variable, we use the statement:
cin >> age1;
Lets have a look on the statement cin >> age1; cin is the counter part of the cout. Here
cin is the input stream that gets data from the user and assigns it to the variable on its
right side. We know that the sign >> indicates the direction of the flow of data. In our
statement it means that data comes from user and is assigned to the variable age1, where
age1 is a variable used for storing the age entered for student1. Similarly we get the ages
of all the ten students and store them into respective variables. That means the age of first
student in age1, the age of second student in age2 and so on up to 10 students. When cin
statement is reached in a program, the program stops execution and expects some input
from the user. So when cin >> age1; is executed, the program expects from the user to
type the age of the student1. After entering the age, the user has to press the 'enter key'.
Pressing 'enter key' conveys to the program that user has finished entering the input and
cin assigns the input value to the variable on the right hand side which is age1 in this
case. As we have seen earlier that in an assignment statement, we can have only one
variable on left hand side of the assignment operator and on right hand side we can have
an expression that evaluates to a single value. If we have an expression on the left hand
Page 24
img
CS201 ­ Introduction to Programming
side of assignment operator we get an error i.e. x = 2 + 4; is a correct statement but x + y
= 3+ 5; is an incorrect statement as we can not have an expression on the left hand side.
Similarly we can not have an expression after the >> sign with cin. So we can have one
and only one variable after >> sign i.e. cin >> x; is a correct statement and cin >> x + y;
is an incorrect statement.
Next, we add all these values and store the result to the variable TotalAge. We use
assignment operator for this purpose. On the right hand side of the assignment operator,
we write the expression to add the ages and store the result in the variable, TotalAge on
left hand side. For this purpose we write the statement as follow:
TotalAge = age1 + age2 + age3 + age4 + age5 + age6 + age7 + age8 +
age9 + age10 ;
The expression on the right hand side uses many addition operators ( + ). As these
operators have the same precedence, the expression is evaluated from left to right. Thus
first age1 is added to age2 and then the result of this is added to age3 and then this result
is added to age4 and so on.
Now we divide this TotalAge by 10 and get the average age. We store this average age in
the variable i.e. AverageAge by writing the statement:
AverageAge = TotalAge / 10;
And at the end we display this average age on the screen by using the following
statement:
cout << " The average age of the students is : " << AverageAge;
Here the string enclosed in the quotation marks, will be printed on the screen as it is and
the value of AverageAge will be printed on the screen.
The complete coding of the program is given below:
/* This program calculates the average age of a class of ten students after prompting the
user to enter the age of each student. */
#include <iostream.h>
main ()
{
// declaration of variables, the age will be in whole numbers
int age1, age2, age3, age4, age5, age6, age7, age8, age9, age10;
int TotalAge, AverageAge;
// take ages of the students from the user
cout << "Please enter the age of student 1: ";
cin >> age1;
Page 25
img
CS201 ­ Introduction to Programming
cout << "Please enter the age of student 2: ";
cin >> age2;
cout << "Please enter the age of student 3: ";
cin >> age3;
cout << "Please enter the age of student 4: ";
cin >> age4;
cout << "Please enter the age of student 5: ";
cin >> age5;
cout << "Please enter the age of student 6: ";
cin >> age6;
cout << "Please enter the age of student 7: ";
cin >> age7;
cout << "Please enter the age of student 8: ";
cin >> age8;
cout << "Please enter the age of student 9: ";
cin >> age9;
cout << "Please enter the age of student 10: ";
cin >> age10;
// calculate the total age and average age
TotalAge = age1 + age2 + age3 + age4 + age5 + age6 + age7 + age8 + age9 +
age10;
AverageAge = TotalAge / 10;
// Display the result ( average age )
cout << "Average age of class is: " << AverageAge;
}
A sample output of the above program is given below.
Please enter the age of student 1: 12
Please enter the age of student 2: 13
Please enter the age of student 3: 11
Please enter the age of student 4: 14
Please enter the age of student 5: 13
Please enter the age of student 6: 15
Please enter the age of student 7: 12
Please enter the age of student 8: 13
Please enter the age of student 9: 14
Please enter the age of student 10: 11
Average age of class is: 12
Page 26
img
CS201 ­ Introduction to Programming
In the above output the total age of the students is 123 and the actual average should be
12.3 but as we are using integer data types so the decimal part is truncated and the whole
number 12 is assigned to the variable AverageAge.
Examples of Expressions
We have already seen the precedence of arithmetic operators. We have expressions for
different calculations in algebraic form, and in our programs we write them in the form of
C statements. Let's discuss some more examples to get a better understanding.
We know about the quadratic equation in algebra, that is y = ax2 + bx + c. The quadratic
equation in C will be written as y = a * x * x + b * x + c. In C, it is not an equation but an
assignment statement. We can use parentheses in this statement, this will make the
expression statement easy to read and understand. Thus we can rewrite it as y = a * (x *
x) + (b * y) + c.
Note that we have no power operator in C, just use * to multiply the same value.
Here is another expression in algebra: x = ax + by + cz2. In C the above expression will
be as:
x=a*x+b*y+c*z*z
The * operator will be evaluated before the + operator. We can rewrite the above
statement with the use of parentheses. The same expressions can be written as:
x = (a * x) + (b * y) + c * ( z * z)
Lets have an other expression in algebra as x = a(x + b(y + cz2)). The parentheses in this
equation force the order of evaluation. This expression will be written in C as:
x = a * (x + b * (y + c * z * z))
While writing expressions in C we should keep in mind the precedence of the operators
and the order of evaluation of the expressions (expressions are evaluated from left to
right). Parentheses are used in complicated expressions. In algebra, there may be curly
brackets { } and square brackets [ ] in an expression but in C we have only parentheses
( ). Using parentheses, we can make a complex expression easy to read and understand
and can force the order of evaluation. We have to be very careful while using
parentheses, as parentheses at wrong place can cause an incorrect result. For example, a
statement x = 2 + 4 * 3 results x = 14. As * operator is of higher precedence, 4 * 3 is
evaluated first and then result 12 is added to 4 which gives the result 14. We can rewrite
this statement, with the use of parentheses to show it clearly, that multiplication is
Page 27
img
CS201 ­ Introduction to Programming
performed first. Thus we can write it as x = 2 + (4 * 3). But the same statement with
different parentheses like x = (2 + 4) * 3 will give the result 18, so we have to be careful
while using parenthesis and the evaluation order of the expression.
Similarly the equation (b2 ­ 4ac)/2a can be written as ( b * b ­ 4 * a * c) / ( 2 * a ). The
same statement without using parentheses will be as b * b ­ 4 * a * c / 2 * a. This is
wrong as it evaluates to b2 ­ 4ac/2a (i.e. 4ac is divided by 2a instead of (b2-4ac)).
Use of Operators
Here are sample programs which will further explain the use of operators in
programming.
Problem Statement:
Write a program that takes a four digits integer from user and shows the digits on the
screen separately i.e. if user enters 7531, it displays 7,5,3,1 separately.
Solution:
Let's first analyze the problem and find out the way how to program it.
Analysis:
First of all, we will sort the problem and find out how we can find digits of an integer.
We know that when we divide a number by 10, we get the last digit of the number as
remainder. For example when we divide 2415 by 10 we get 5 as remainder. Similarly
3476 divided by 10 gives the remainder 6. We will use this logic in our problem to get
the digits of the number. First of all, we declare two variables for storing number and the
digit. Let's say that we have a number 1234 to show its digits separately. In our program
we will use modulus operator ( % ) to get the remainder. So we get the first digit of the
number 1234 by taking its modulus with 10 (i.e. 1234 % 10). This will give us the digit 4.
We will show this digit on the screen by using cout statement. After this we have to find
the next digit. For this we will divide the number by 10 to remove its last digit. Here for
example the answer of 1234 divided by 10 is 123.4, we need only three digits and not the
decimal part. In C we know that the integer division truncates the decimal part to give the
result in whole number only. We will use integer division in our program and declare our
variable for storing the number as int data type. We will divide the number 1234 by 10
(i.e. 1234 / 10). Thus we will get the number with remaining three digits i.e. 123. Here is
a point to be noted that how can we deal with this new number (123)?
Page 28
img
CS201 ­ Introduction to Programming
There are two ways, one is that we declare a new variable of type int and assign the value
of this new number to it. In this way we have to declare more variables that mean more
memory will be used. The second way is to reuse the same variable (where number was
already stored). As we have seen earlier that we can reassign values to variables like in
the statement x = x + 1, which means, add 1 to the value of x and assign this resultant
value again to x. In this way we are reusing the variable x. We will do the same but use
the division operator instead of addition operator according to our need. For this purpose
we will write number = number / 10. After this statement we have value 123 in the
variable number.
Again we will get the remainder of this number with the use of modulus operator,
dividing the number by 10 (i.e. 123 % 10). Now we will get 3 and display it on the
screen. To get the new number with two digits, divide the number by 10. Once again, we
get the next digit of the number (i.e. 12) by using the modulus operator with 10, get the
digit 2 and display it on the screen. Again get the new number by dividing it by 10
(i.e. 1). We can show it directly, as it is the last digit, or take remainder by using modulus
operator with 10. In this way, we get all the digits of the number.
Now let's write the program in C by following the analysis we have made. The complete
C program for the above problem is given below. It is easy to understand as we are
already familiar with the statements used in it.
/* A program that takes a four digits integer from user and shows the digits on the screen
separately i.e. if user enters 7531, it displays 7,5,3,1 separately. */
#include <iostream.h>
main()
{
// declare variables
int number, digit;
// prompt the user for input
cout << "Please enter 4-digit number:";
cin >> number;
// get the first digit and display it on screen
digit = number % 10;
cout << "The digits are: ";
cout << digit << ", ";
// get the remaining three digits number
number = number / 10;
// get the next digit and display it
digit = number % 10;
Page 29
img
CS201 ­ Introduction to Programming
cout << digit << ", ";
// get the remaining two digits number
number = number / 10;
// get the next digit and display it
digit = number % 10;
cout << digit << ", ";
// get the remaining one digit number
number = number / 10;
// get the next digit and display it
digit = number % 10;
cout << digit;
}
A sample output of the above program is given below.
Please enter 4-digit number: 5678
The digits are: 8, 7, 6, 5
Problem Statement:
Write a program that takes radius of a circle from the user and calculates the diameter,
circumference and area of the circle and display the result.
Solution:
In this problem we take the input (radius of a circle) from the user. For that we can use
cin statement to prompt the user to enter the radius of a circle. We store this radius in a
variable. We also need other variables to store diameter, circumference and area of the
circle. To obtain the correct result, we declare these variables of type float, instead of int
data type, as we know that the int data type stores the whole numbers only. Here in our
problem the area or circumference of the circle can be in decimal values. After getting the
radius we use the formulae to find the diameter, circumference and area of the circle and
then display these results on the screen. The solution of this program in coding form is
given below.
Page 30
img
CS201 ­ Introduction to Programming
/* Following program takes the radius of a circle from the user and calculates the
diameter, circumference and area of the circle and displays the result. */
#include <iostream.h>
main ()
{
// declare variables
float radius, diameter, circumference, area;
// prompt the user for radius of a circle
cout << "Please enter the radius of the circle " ;
cin >> radius ;
// calculate the diameter, circumference and area of the circle
// implementing formula i.e. diameter = 2 r circumference = 2 ח r and area = ח r2
diameter = radius * 2 ;
circumference = 2 * 3.14 * radius ; // 3.14 is the value of ח (Pi)
area = 3.14 * radius * radius ;
// display the results
cout << "The diameter of the circle is : " << diameter ;
cout << "The circumference of the circle is : " << circumference ;
cout << "The area of the circle is : " << area ;
}
A sample output of the above program is given below.
Please enter the radius of the circle  5
The diameter of the circle is : 10
The circumference of the circle is : 31.4
The area of the circle is : 78.5
Tips
Use descriptive names for variables
o
Indent the code for better readability and understanding
o
Use parenthesis for clarity and to force the order of evaluation in an expression
o
Reuse the variables for better usage of memory
o
Take care of division by zero
o
Analyze the problem properly, and then start coding (i.e. first think and then write)
o
Page 31
Table of Contents:
  1. What is programming
  2. System Software, Application Software, C language
  3. C language: Variables, Data Types, Arithmetic Operators, Precedence of Operators
  4. C++: Examples of Expressions, Use of Operators
  5. Flow Charting, if/else structure, Logical Operators
  6. Repetition Structure (Loop), Overflow Condition, Infinite Loop, Properties of While loop, Flow Chart
  7. Do-While Statement, for Statement, Increment/decrement Operators
  8. Switch Statement, Break Statement, Continue Statement, Rules for structured Programming/Flow Charting
  9. Functions in C: Structure of a Function, Declaration and Definition of a Function
  10. Header Files, Scope of Identifiers, Functions, Call by Value, Call by Reference
  11. Arrays: Initialization of Arrays, Copying Arrays, Linear Search
  12. Character Arrays: Arrays Comparisonm, Sorting Arrays Searching arrays, Functions arrays, Multidimensional Arrays
  13. Array Manipulation, Real World Problem and Design Recipe
  14. Pointers: Declaration of Pointers, Bubble Sort Example, Pointers and Call By Reference
  15. Introduction, Relationship between Pointers and Arrays, Pointer Expressions and Arithmetic, Pointers Comparison, Pointer, String and Arrays
  16. Multi-dimensional Arrays, Pointers to Pointers, Command-line Arguments
  17. String Handling, String Manipulation Functions, Character Handling Functions, String Conversion Functions
  18. Files: Text File Handling, Output File Handling
  19. Sequential Access Files, Random Access Files, Setting the Position in a File, seekg() and tellg() Functions
  20. Structures, Declaration of a Structure, Initializing Structures, Functions and structures, Arrays of structures, sizeof operator
  21. Bit Manipulation Operators, AND Operator, OR Operator, Exclusive OR Operator, NOT Operator Bit Flags Masking Unsigned Integers
  22. Bitwise Manipulation and Assignment Operator, Programming Constructs
  23. Pre-processor, include directive, define directive, Other Preprocessor Directives, Macros
  24. Dynamic Memory Allocation, calloc, malloc, realloc Function, Dangling Pointers
  25. History of C/C++, Structured Programming, Default Function Arguments
  26. Classes and Objects, Structure of a class, Constructor
  27. Classes And Objects, Types of Constructors, Utility Functions, Destructors
  28. Memory Allocation in C++, Operator and Classes, Structures, Function in C++,
  29. Declaration of Friend Functions, Friend Classes
  30. Difference Between References and Pointers, Dangling References
  31. Operator Overloading, Non-member Operator Functions
  32. Overloading Minus Operator, Operators with Date Class, Unary Operators
  33. Assignment Operator, Self Assignmentm, Pointer, Conversions
  34. Dynamic Arrays of Objects, Overloading new and delete Operators
  35. Source and Destination of streams, Formatted Input and Output, Buffered Input/Output
  36. Stream Manipulations, Manipulators, Non Parameterized Manipulators, Formatting Manipulation
  37. Overloading Insertion and Extraction Operators
  38. User Defined Manipulator, Static keyword, Static Objects
  39. Pointers, References, Call by Value, Call by Reference, Dynamic Memory Allocation
  40. Advantages of Objects as Class Members, Structures as Class Members
  41. Overloading Template Functions, Template Functions and Objects
  42. Class Templates and Nontype Parameters, Templates and Static Members
  43. Matrices, Design Recipe, Problem Analysis, Design Issues and Class Interface
  44. Matrix Constructor, Matrix Class, Utility Functions of Matrix, Input, Transpose Function
  45. Operator Functions: Assignment, Addition, Plus-equal, Overloaded Plus, Minus, Multiplication, Insertion and Extraction