FP 201 Unit 2 - Part 3

48
FP 201 – Programming Fundamentals Operators & Expressions

Transcript of FP 201 Unit 2 - Part 3

Page 1: FP 201 Unit 2 - Part 3

FP 201 – Programming Fundamentals Operators & Expressions

Page 2: FP 201 Unit 2 - Part 3

Learning outcome

By the end of the course, students should be able to:

Define the following operators: a. Arithmetic operator b. Assignment operator c. Increment and decrement operator d. Relational operator e. Logical operatorExplain operators’ precedenceExplain type conversionWrite expression using operatorUse expression in program

Page 3: FP 201 Unit 2 - Part 3

Operators

Operator Action-+*/%--

++

subtraction (also unary minus)additionmultiplicationdivisionmodulus divisiondecrementincrement

&&||!

ANDORNOT

Page 4: FP 201 Unit 2 - Part 3

OperatorsIs a symbol that instructs compiler to

perform an operation or action.

Page 5: FP 201 Unit 2 - Part 3

Arithmetic OperatorsPerform four fundamental operations which

are addition, subtraction, multiplication and division.

Operator Description Example Result

* Multiplication 2 * 8 16

/ Division 8 / 2 4

+ Addition 2 + 8 10

- Subtraction 8 - 2 6

( ) Parentheses. For grouping (8+2) 10

% Modulus. Divides two number and returns just the remainder portion

4%3 1

Page 6: FP 201 Unit 2 - Part 3

Arithmetic Operatorsarithmetic expressions are evaluated with

some rule called operator precedence. multiplications (*) and divisions (/) are

evaluated firstadditions (+) and subtractions (-) are

performed last.

Page 7: FP 201 Unit 2 - Part 3

Activity 1

Write the resultant value of the following expressions.

Expression Result

14-4

14+4

14* 4

14/4

14%4

Page 8: FP 201 Unit 2 - Part 3

Calculate the total marks for the given five subjects. Declare appropriate variables, assign values as given below:

English = 85Maths = 100History = 75Geography = 70Art = 85

calculate the total marks calculate the average

ACTIVITY 2

Page 9: FP 201 Unit 2 - Part 3

#include<iostream>

using namespace std;int main(){

int english = 85, maths = 100, history = 75, geography = 70, art = 85;int sum=0;

sum=english+maths+history+geography+art;cout<<"Sum is: "<<sum<<endl;;

return 0;}

Page 10: FP 201 Unit 2 - Part 3

#include<iostream>

using namespace std;int main(){

int english = 85, maths = 100, history = 75, geography = 70, art = 85;int sum=0, average=0;

sum=english+maths+history+geography+art;average=sum/5;

cout<<"Sum is: "<<sum<<endl;cout<<"Average is:"<<average<<endl;

return 0;}

Page 11: FP 201 Unit 2 - Part 3

Assignment Operatorvariables are given a value through the use

of assignment operator (=) general form: variable = expression;

eg:int x, y; x = 2; y = 5*x; // y = 10 x = x + 4; // x = 6 y = y/2; // y = 5

Page 12: FP 201 Unit 2 - Part 3

Assignment OperatorThe value of an assignment can be used in

another assignment.

This is a chained assignment.Eg:

m = (n = 66) + 9; // n = 66 and m = 75x = y = 22; // x = 22 and y = 22

Page 13: FP 201 Unit 2 - Part 3

Compound Assignment Operators (+=), (-=), (*=), (/=), (%=)

allow us to use assignment and an arithmetic operator together.

general form is:variable operator= expression;

Page 14: FP 201 Unit 2 - Part 3

Compound Assignment Operators

Operator Description Example Equivalent to

+= add and assign x += 3 x = x + 3

-= subtract and assign x -= 5 x = x - 5

*= multiply and assign x *= 4 x = x * 4

/= divide and assign x /= 2 x = x / 2

%= find reminder and assign x %= 9 x = x % 9

Page 15: FP 201 Unit 2 - Part 3

In Class ExerciseGiven the following declaration and initial

assignment:

int i = 4, j = 21, k;float x = 94.55, y;char a = ‘z’, b = ‘t’, c =‘ ‘;

Determine the value for the following assignments: k = i * jy = x + iy = k = ja = b =c i += i

Page 16: FP 201 Unit 2 - Part 3

Increment & Decrement Operatorincrement operator (++) and decrement

operator (--) increase or reduce by one the value stored in a variable.

the following are equivalent in functionality. x++; x += 1; x = x + 1;

characteristic of this operator: can be used both as a prefix and as a postfix. eg: a++ or ++a the results is different

Page 17: FP 201 Unit 2 - Part 3

Prefix

When a prefix expression (++x or --x) is used as part of an expression, the value returned is the value calculated after the prefix operator is applied

int x = 0; int y = 0; y = ++x; // result: y=1, x=1 x is incremented by 1 and the result is assigned to y

Page 18: FP 201 Unit 2 - Part 3

PostfixWhen a postfix expression (x++ or x--) is

used as part of an expression, the value returned is the value calculated before the postfix operator is applied

int x = 0; int y = 0; y = x++; // result: y=0, x=1 original value of x is stored, x is incremented, original value of x is assigned to y

Page 19: FP 201 Unit 2 - Part 3

Increment & Decrement Operatoreg:a = 5; // a = 5 b = a++; // b = a = 5, then a = 5+1 = 6 c = ++a; // a = 6+1 = 7, then c = a = 7

Page 20: FP 201 Unit 2 - Part 3

Operator Description Example Value

< less than x < y 6 < 9 1

<= less than or equal to x <= y 12 <= 13 1

> greater than x > y 7 > 10 0

>=greater than or equal

tox >= y 9 >= 5 1

== equal to x == y 7 ==5 0

!= not equal to x != y 6 != 5 1

Relational Operator Control statements use relation operators in order to

compare two objects, which results in a value that is either true (1) or false (0).

There are six relational operators as follows:

Page 21: FP 201 Unit 2 - Part 3

Logical Operator

Operator Description Example

&&logical AND, conjunction.Both sides must be true for the result to be true

x > 2 && y == 3

||logical OR, disjunction.The result is true if either side or both sides are true.

x > 2 || x <= 9

! logical NOT, negation !(x>0)

Page 22: FP 201 Unit 2 - Part 3

Condition1 Condition2 && ||

true true true true

true false false true

false true false true

false false false false

Page 23: FP 201 Unit 2 - Part 3

Logical Operatorusing these operators, we can form a

Boolean Expression that can be either true or false.

Boolean expressions evaluate to integer values.

The value 0 means 'false' and all non-zero value means 'true'.

There are also two literal constants used with bool variables: true and false.

Page 24: FP 201 Unit 2 - Part 3

In Class ExerciseWhat is the difference between x = 3 and x

== 3? Given a = 2, b = 5, c = 7 determine the

value for the following expressions either TRUE or FALSE: :

1. a < 2 && b > 52. c >= a3. a < b || b > c4. c != 105. a == 25

Page 25: FP 201 Unit 2 - Part 3

Operator PrecedenceDetermines the order in which

mathematical computations and operations are performed in an expression.

Page 26: FP 201 Unit 2 - Part 3

Operator Precedence

Page 27: FP 201 Unit 2 - Part 3

Operator Precedence

Given a=b = 5, c = 2; solve the following expression

a + b * 2 / c – 5 = 5 + 5 * 2 / 2 – 5 = 5 + 10 / 2 – 5= 5 + 5 – 5= 10 – 5= 5

Page 28: FP 201 Unit 2 - Part 3

In Class ExerciseGiven x = 10, y = 7, z = 2; solve the

following expressionx + 2y – zx / z – x * x + yx * y % z5 ( x + y + z ) – x / z++x*y – y*z

Page 29: FP 201 Unit 2 - Part 3

Type conversion/Type CastingIs the conversion of a value of one data

type into another data type.Typecasting consist of two types:

Implicit conversion

Explicit conversion

Page 30: FP 201 Unit 2 - Part 3

Implicit conversionA value of data type with lower range is

assigned to a variable of data type with higher range

Lower range to higher range

Page 31: FP 201 Unit 2 - Part 3

Example#include<iostream>using namespace std;void main(){

double x; // Size is 8 bytesint y=2; //Size is 4 bytesfloat z=2.2555f; x=y+z; //Implicit conversioncout<<"Result: "<<x;

}

OUTPUTResult: 4.2555

Page 32: FP 201 Unit 2 - Part 3

Explicit conversionA value of data type with higher range is

assigned to a variable of data type with lower range

Higher range to lower range

Explicit conversion leads to data loss.

Page 33: FP 201 Unit 2 - Part 3

Example #include<iostream>

using namespace std;void main(){

int total_value; double book1 = 300.46;

total_value=(int)book1; // Explicit conversioncout<<"The total value is:"<<total_value;

}

OUTPUTThe total value is:300

Page 34: FP 201 Unit 2 - Part 3

ExerciseWrite a program to declare a variable d of

type double. Assign the value 102.5789 to d. Declare a float variable fl. Assign the value of d to fl by performing an explicit conversion and print the value on the screen.

Page 35: FP 201 Unit 2 - Part 3

Answer #include<iostream>using namespace std;void main(){

double d=102.5789; float fl;

fl=(float)d; // Explicit conversion cout<<"Value of the float variable fl = "<<fl;

}

OUTPUTValue of the float variable fl = 102.579

Page 36: FP 201 Unit 2 - Part 3

Summary In this presentation, you learnt the following:Operator is a symbol that instructs

compiler to perform an operation or action.Typecasting is the conversion of data type

of the value of a variable into another.There are two types of casting: implicit

conversion and explicit conversion.

Page 37: FP 201 Unit 2 - Part 3

FP 201 – Programming Fundamentals with C++ Input Output Statements

Page 38: FP 201 Unit 2 - Part 3

Learning outcome

By the end of the course, students should be able to:

Identify the syntax use for input and outputWrite program that use the input and output

statements

Page 39: FP 201 Unit 2 - Part 3

Input/Output Statements The standard C++ library includes the

header file iostream, where the standard input and output stream objects are declared.

cout to output data to the screen and

cin to input data from the keyboard.

Page 40: FP 201 Unit 2 - Part 3

Standard Outputstandard output:

need to use cout, followed by the insertion operator (<<)

eg:cout << "Hello World!"; // Outputs "Hello World!"

on the screen

cout << 1299; // Outputs the number 1299 on the screen

cout << x; // Outputs the content of x on the screen

insertion operator (<<) may be used more than once in a single statement: cout << "Hi, " << "this is " << "a simple C++ statement";

Page 41: FP 201 Unit 2 - Part 3

Standard OutputNote that, cout does not add a line break. For example: cout << "Computer Programming ";

cout << "is important for engineers.";

will be output as:

Computer Programming is important for engineers.

Page 42: FP 201 Unit 2 - Part 3

Standard OutputA line break can be added by inserting a '\

n' character or a using a endl manipulator.

cout << "Computer Programming \n";

cout << "is important for engineers.";

cout << "Computer Programming " << endl;

cout << "is important for engineers.";

These two produce the following (same) output: Computer Programming is important for engineers.

Page 43: FP 201 Unit 2 - Part 3

Standard InputHandling the standard input is done by applying

the overloaded operator of extraction (>>) on the cin stream

Value can be input from the keyboard and assigned to a variable x as follows: cin >> x;

and two variables can assigned as any of the follows: cin >> x;

cin >> y;

cin >> x >> y;

Page 44: FP 201 Unit 2 - Part 3

Code Example// Calculates the sum of two integers #include <iostream> using namespace std;

int main() { int a, b, total; cout << "Enter two integers to be added: "; cin >> a >> b; total = a + b; cout << "The sum is " << total << endl; return 0; }

Page 45: FP 201 Unit 2 - Part 3

Code Example// Calculates the area of a triangle // given an input of the triangle base and height. #include <iostream>

int main() { float base, height, area; std::cout << "Enter the base and height of the triangle: "; std::cin >> base >> height; area = 0.5*base*height; std::cout << "The area of the triangle is " << area << std::endl;

}

Page 46: FP 201 Unit 2 - Part 3

Q&ADevelop a program that can calculate the

total and average of four numbers that is input by user.

Page 47: FP 201 Unit 2 - Part 3

#include <iostream>

using namespace std;

int main()

{

int a, b, c, d, total, average;

cout << "Enter four integers to be added: ";

cin >> a >> b>>c>>d;

total = a + b + c + d;

average = total/4;

cout << "The sum is " << total << endl;

cout<< "The average is "<< average << endl;

return 0;

}

Page 48: FP 201 Unit 2 - Part 3

Summary In this presentation, you learnt the following:

cout to output data to the screen cin to input data from the keyboard. cout use insertion operator (<<)cin use overloaded operator of extraction

(>>)