Chapter 2 (Part 3) - Week 3

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 38

Basic C++ Programming

Contents
 Arithmetic Operators
 Arithmetic Assignment Operators
 Increment and Decrement Operators
 Expressions
 Precedence and associativity
 Type Conversion
 Library Function Introduction
Objectives
 To understand the arithmetic operators and their precedencies

 To know what is expression

 To know what is type conversion

 To understand how to convert one data type to another type

 To understand Library Function


Learning Outcomes
 After completing this lecture, students will be able to:
 Use the arithmetic operators and expression.

 Define the precedencies of arithmetic operators.

 Understand about type conversion.

 Know how to convert one data type to another.


Arithmetic Operators

 are used to perform mathematical operations on variables and


values.
Table1. Basic arithmetic operators
Operator Meaning Example

+ addition ans = 7 + 3

- subtraction ans = 7 - 3

* multiplication ans = 7 * 3

/ division ans = 7 / 3

% modulus ans = 7 % 3

University of Computer Studies, FCS


Arithmetic Operators
(Example 1)
//example of division and modulus operator
#include<iostream>
using namespace std;
int main()
{
cout << 19 / 10 << endl; //1
cout << 19 % 10 << endl; //9
cout << 19.0 / 10 << endl; //1.9
cout << 19 / 10.0 << endl; //1.9
cout << 19.0 / 10.0 << endl; //1.9
cout << 2.5 % 2 << endl; //Error
cout << 2.5 % 2.0 << endl; //Error
cout << 5 % 2.5 << endl; //Error

}
Arithmetic Operators
(Example 2)
//display the use of arithmetic operators (addition and multiplication)
#include<iostream>
int main()
{
//calculate addition and multiplication of two numbers
int num1, num2;
cout << "Enter two numbers to be operated with arithmetic operators: ";
cin >> num1 >> num2;
cout << "Num1 + Num2 = " << num1 + num2 << endl;
cout << "Num1 * Num2 = " << num1 * num2 << endl;
}
Output
Enter two numbers to be operated
with arithmetic operators:
12 9

Num1 + Num2 = 21

Num1 * Num2 = 108


Arithmetic Assignment
Operators
 are used to assign values to variables.

Table2. A list of all assignment operators


Operator Example Same as

= x=5 x=5

+= x += 3 x=x+3

-= x -= 3 x=x-3

*= x *= 3 x=x*3

/= x /= 3 x=x/3

%= x %= 3 x=x%3
Arithmetic Assignment
Operator(Example)
//assign a single value to three variables and display the sum
#include<iostream>
using namespace std;
int main()
{
int num1, num2, num3;
int result;
num1 = num2 = num3 = 5;//assign the value 5 to variables num1, num2 and num3

result = num1 + num2 + num3; //calculate sum


cout << "The result is " << result <<endl;
Output
}
The result is 15
Increment and Decrement
Operators
Increment operators
 are used to increase the value of the variable by one.
++ //increment operator
Decrement operators
 are used to decrease the value of the variable by one.
-- //decrement operator
 Both increment and decrement operators are used on single operand or
variable, so it is also called as unary operator.
Example: x++, y--
Prefix and Postfix

 The increment/decrement operator can be used in two ways:


1. a prefix meaning that the operator precedes the variable.
 Prefix notation  ++var;
 The value of var is incremented by 1 then, it returns the value.

2. a postfix meaning that the operator follows the variable.


 Postfix notation  var++;
 The original value of var is returned first then, var is incremented by 1.
 The decrement (--)operator works like the ++operator except it decreases the value
by 1.
Prefix and Postfix (Example)

#include <iostream>
using namespace std;
int main() { var1 var2 Output
int var1 = 5, var2 = 5; 5 5 5
cout << var1++ << endl; 6 7
6
cout << ++var1 << endl; 6
7 5
cout << ++var2 << endl; 6
4
cout << var2 <<endl; 5
cout<< --var2 <<endl; 5
cout<< var2-- <<endl;
return 0;
}
Expression
 is a combination of variables, constants and operators that
represents a computation.
 consists of one or more operands, zero or more operators to
compute a value and produces some value.
 Example of C++ expression:
 (x/y) – z
 alpha +12
 (alpha – 37) * beta / 2
Precedencies
 Operator precedence specifies the order of operations in expressions that contain
more than one operator.
Table 3: Arithmetic operator precedence
Precedence Operator Description Example Associativity
1 () Grouping (a + b) / 4 Left to right
operator
2 ++ Increment ++a Right to left
-- Decrement - -a
3 * Multiplication int i = 2 * 4
/ Division float f = 10 / 3 Left to right
% Modulus int rem = 4 % 3
4 + Addition int i = 2 + 3 Left to right
- Subtraction int i = 5 - 1
5 = assignment int i = 5 Right to left

 In this expression (a – 32) * 5 / 9 , which is calculated first?


Expression (Example 1)
 Expression = (a – 32) * 5 / 9  Expression = a – 32 * 5 / 9
 Given a = 40  Given a = 40
(a – 32) * 5 / 9 a – 32 * 5 / 9
= (40 – 32) * 5 / 9 = 40 – 32 * 5 / 9
=8*5/9 = 40 – 160 / 9
= 40 / 9 = 40 – 17
=4 = 23
Expression (Example 2)
 Expression = 40 + 32 * 10 / 3 + 7 – 5 % 3
= 40 + 320 / 3 + 7 – 5 % 3
= 40 + 106 + 7 – 5 % 3
= 40 + 106 + 7 – 2
= 146 + 7 – 2
= 153 – 2
= 151
Type Conversion

 A type cast is basically a conversion from one type to another.


 Implicit Type Conversion or Automatic Type Conversion
 Explicit Type Conversion
 Implicit conversion is used when an expression contains variables of more than
one type.
 All the data types present in the expression are converted to data type of the
variable with the largest data type.
 Explicit conversion also called type casting is user defined and the user can type
cast the result to make it of a particular data type.
Syntax: (type) expression
Automatic Type Conversion
(Example)
//Example of implicit conversion
#include <iostream>
using namespace std;
int main()
{
int x = 10; // integer x
char y = 'a'; // character c
x = x + y; // y implicitly converted to int. ASCII, the value of 'a' is 97
float z = x + 1.0; // x is implicitly converted to float Output
cout << "x = " << x << endl; x = 107
cout << "y = " << y << endl;
cout << "z = " << z << endl; y=a

z = 108
return 0;
}
Type Conversion

Consider the program


void main()
{
int count=7;
float avgweight = 7.7;
double totalweight;
totalweight = count * avgweight;
cout << “Total weight = “ << totalweight<< endl;
}

count (type int) is multiplied by avgweight (type float) to


yield a result totalweight (type double). This program
compiles without error.
Automatic Conversions
When two operands of different types are encountered
in the same expression, the lower-type variable is
converted to the type of the higher-type variable .
These conversions take place invisibly, and C++
automatically does what you want.
Conversion using Cast Operator

 A cast operator is an unary operator which forces one data type to be


converted into another data type.
 C++ supports four types of casting:
 Static Cast
 Dynamic Cast
 Const Cast
 Reinterpret Cast
Conversion using Static Cast Operator
(Example)

//explicit conversion from float to integer


#include <iostream>
using namespace std;
int main()
{
float f = 3.5;
Output
int b;
b=3
// using cast operator
b = static_cast<int>(f);
cout << "b = "<< b;
}
Example – about variable float
Write a program that prompts the user to type in a floating-point number
representing the radius of a circle. Then calculates and displays the circle’s
area.
#include <iostream.h>
int main()
{
float radius;
float area;
cout << “Enter radius :”;
cin >> radius;
area = 3.1415 * radius * radius;
cout << “Area is “ << area ;
return 0;
}
Constant Defined
In the previous example, the PI value 3.14 is never changed. Thus, defined PI
value as a constant.
The keyword const (for constant) precedes the data type of a variable.
Any attempt to alter the value of a variable defined with this qualifier will elicit
an error message from the compiler.
Constant variable is defined using all capital letter.
Syntax :
const float PI = 3.1415; // PI is capital letter
Library Function
Many activities in C++ are carried out by library
functions. These functions perform file access,
mathematical computations, and data conversion,
among other things.

Example,
clrscr();
getch()
Example
Write a program that input a number and then display square root value of that
input number.
Procedure
Input – a number
Process - square root value
Output - output the square root result

The library function sqrt() can be used to calculate the square root of a number.
Example
int main()
{
double number, answer;

cout << “Enter a number: “;


cin >> number; //get the numberinput

answer = sqrt(number); //find square root

cout << “Square root is “ << answer << endl; //display it


return 0;
}
Quiz- You need to input header file? How can you know which
header file need to use?
How can we know which header file to use?

Place the cursor under the library function and press Ctrl+F1.
The new window shows the header file name on top right corner and Type the
preprocessor directive #include with the header file.
Summary
 Arithmetic Operators
 Arithmetic Assignment Operators
 Increment and Decrement Operators
 Expressions
 Precedence and associativity
 Type Conversion
 Library Function Introduction
Reading Assignments

1. Chapter(2) - C++ Programming Basics (page.30-71)


Reference book : “Object-Oriented Programming in C++” by Robert Lafore, 4th Edition
Download link : https://docs.google.com/file/d/0B21HoBq6u9TsUHhqS3JIUmFuamc/view
References

1. Object-Oriented Programming in C++ (Fourth Edition) by Robert Lafore

2. Programming Logic and Design Comprehensive (Sixth Edition) by Joyce Farrell

3. Data Structures using C++ by Varsah H. Patil

4. C++ Language Tutorial (e-book)

5. C Programming for Engineering & Computer Science by H.H. Tan and T.B. D’Orazio
Exercise
3. Write a program that generates the following output:
10
20
19
Use an integer constant for the 10, an arithmetic assignment operator to
generate the 20, and a decrement operator to generate the 19.
Exercise

No. 1, 6, 7, 9 Page- 71-72


Exercise
• What will be the output of the following:
ans1 = 10 + 20 / 3;
ans2 = 4 * 12 + 10 /2
result = 2 + 3 * 5;
answer = 7 * (5 – 2);
2 * 3 / 4 - 5;
Exercise
Write a program that asks the user for a temperature
in degrees Fahrenheit, converts it to Celsius, and displays
the result. It uses integer variables.
(Hint: Tc = 5/9 (Tf-32) )

Think how to write the program?


What is the output, if you input Fahrenheit temperature is 212?
Exercise
10. In the heyday of the British empire, Great Britain used a monetary system based
on pounds, shillings, and pence. There were 20 shillings to a pound, and 12 pence
to a shilling. The notation for this old system used the pound sign, £, and two
decimal points, so that, for example, £5.2.8 meant 5 pounds, 2 shillings, and 8
pence. (Pence is the plural of penny.) The new monetary system, introduced in the
1950s, consists of only pounds and pence, with 100 pence to a pound (like U.S.
dollars and cents). We’ll call this new system decimal pounds. Thus £5.2.8 in the
old notation is £5.13 in decimal pounds (actually £5.1333333). Write a program to
convert the old pounds-shillings-pence format to decimal pounds.
An example of the user’s interaction with the program would be
Enter pounds: 7 old system = 7.17.9 1pound = 20 shilli/1 shilli = 12 pence
Enter shillings: 17
Enter pence: 9
Decimal pounds = £7.89
In most compilers you can use the decimal number 156 (hex character constant ‘\
x9c’) to represent the pound sign (£).
Exercise
12. Write the inverse of Exercise 10, so that the user enters an amount in Great Britain’s new decimal-
pounds notation (pounds and pence), and the program converts it to the old pounds-shillings-pence
notation. An example of interaction with the program might be
Enter decimal pounds: 3.51 // pounds.shillings.pence
Equivalent in old notation = £3.10.2.

Make use of the fact that if you assign a floating-point value (say 12.34) to an integer variable, the
decimal fraction (0.34) is lost; the integer value is simply 12. Use a cast to avoid a compiler warning.
You can use statements like
float decpounds; // input from user (new-style pounds)
int pounds; // old-style (integer) pounds
float decfrac; // decimal fraction (smaller than 1.0)

pounds = (int)decpounds ; // remove decimal fraction


decfrac = decpounds - pounds; // regain decimal fraction
You can then multiply decfrac by 20 to find shillings. A similar operation obtains pence.
Exercise
No. 5 page 72
A library function, islower(char), takes a single character (a letter) as an
argument and returns a nonzero integer if the letter is lowercase, or zero
if it is uppercase.

You might also like