Lecture03 - Copy

Содержание

Слайд 2

Conditional Operators

Syntax:
exp1 ? exp2 : exp3
Where exp1,exp2 and exp3 are expressions
Working of

Conditional Operators Syntax: exp1 ? exp2 : exp3 Where exp1,exp2 and exp3
the ? Operator:
Exp1 is evaluated first, if it is nonzero(1/true) then the expression2 is evaluated and this becomes the value of the expression,
If exp1 is false(0/zero) exp3 is evaluated and its value becomes the value of the expression
Ex: m=2;
n=3
r=(m>n) ? m : n;

Слайд 3

Increment & Decrement Operators

C++ supports 2 useful operators namely
Increment ++
Decrement- -operators
The ++

Increment & Decrement Operators C++ supports 2 useful operators namely Increment ++
operator adds a value 1 to the operand
The -- operator subtracts 1 from the operand
++a or a++
--a or a--

Слайд 4

Rules for ++ & -- Operators

These require variables as their operands.
When postfix

Rules for ++ & -- Operators These require variables as their operands.
either ++ or -- is used with the variable in a given expression, the expression is evaluated first and then it is incremented or decremented by one.
When prefix either ++ or – is used with the variable in a given expression, it is incremented or decremented by .one first and then the expression is evaluated with the new value

Слайд 5

Examples for ++ and -- Operators

Let the value of a =5 and

Examples for ++ and -- Operators Let the value of a =5
b=++a then
a = b =6
Let the value of a = 5 and b=a++ then
a =6 but b=5
i.e.:
1. a prefix operator first adds 1 to the operand and then the result is assigned to the variable on the left
2. a postfix operator first assigns the value to the variable on left and then increments the operand.

Слайд 6

Shorthand Assignment Operators

Shorthand Assignment Operators

Слайд 7

Objectives

To use the selection structure to choose among the alternative actions

Objectives To use the selection structure to choose among the alternative actions

if selection statement
Double Selection (if else ) statements
Nested Selection statements

Слайд 8

Control structures

Control structure
A control statement and the statements whose execution it

Control structures Control structure A control statement and the statements whose execution
controls.
a control statement is any statement that alters the linear flow of control of a program. C++ examples include: if-else, while, for, break, continue and return statement
Sequential execution
Statements executed in order
Transfer of control
Next statement to be executed may be other than the next one in sequence.

Слайд 9

Control structures

Bohm and Jacopini’s control structures
Bohm and Jacopino’s work demonstrate that all

Control structures Bohm and Jacopini’s control structures Bohm and Jacopino’s work demonstrate
programs could be written in terms of only three control structures.
Sequence structures, selection structures and repetition structures.
Sequence structure
Built into C++. Programs executed sequentially by default.
Selection structures
C++ has three types - if, if/else, and switch
Repetition structures
C++ has three types – for, while and do while

Слайд 10

Control structures

if Selection Structure
Perform an action if condition is true.
.Skip

Control structures if Selection Structure Perform an action if condition is true.
the action if condition is false.
If/else Selection Structure
Perform an action if condition is true.
Performs a different action if the condition is false.

Слайд 11

We are going to discuss if and if/else selection structures and switch

We are going to discuss if and if/else selection structures and switch
first and will explain the repetition structures later. It was just an introduction to these structures.

Слайд 12

Decision making structure/ selection structure

Selection structure/decision structure
allows the program to make

Decision making structure/ selection structure Selection structure/decision structure allows the program to
a decision or comparison and then select one of two paths, depending on the result of the comparison.
Condition
condition is a logical expression that evaluates to true or false. It could be a relational or Boolean expression. In other words
Specifies the decision you are making
Must result in either a true or false answer
IF Structure
One statement or a block of statement enclosed in braces {} i.e. (compound statement), to be processed If condition met otherwise it is skipped.
Uses equality and relational operators

Слайд 13

Equality and Relational operators
Conditions in if structures can be formed by using

Equality and Relational operators Conditions in if structures can be formed by
the equality and relational operators
Equality operators
Same level of precedence
Associated left to right.
Relational operators
Same level of precedence.
Associated left to right.
Equality operators precedence is lower then precedence of relational operators.

Слайд 14

Equality and relational operators

Equality and relational operators

Слайд 15

Boolean Expressions

Boolean expressions are expressions that are either true or false
comparison operators

Boolean Expressions Boolean expressions are expressions that are either true or false
such as '>' (greater than) are used to compare variables and/or numbers
(grade >= 60) Including the parentheses, is the boolean expression from the grade example
A few of the comparison operators that use two symbols (No spaces allowed between the symbols!)
> greater than
!= not equal or inequality
== equal or equivalent
<= less than or equal to
etc

Слайд 16

If Selection Structure
The primary C++ selection structure statement used to perform a

If Selection Structure The primary C++ selection structure statement used to perform
single-alternative selection.
Choose among alternative courses of action
If the condition is true
statement Print statement executed, program continues to next
If the condition is false
Print statement ignored, program continues

Слайд 17

Flow chart

Graphical representation of an algorithm or a portion of algorithm.
Drawn using

Flow chart Graphical representation of an algorithm or a portion of algorithm.
certain special-purpose symbols connected by arrows called flow lines.
Special purpose symbols.
Following are some symbols to draw a flow chart and there purpose.

Rectangles are action symbols to indicate any type of ACTION, including a calculation or an input output operation.

Diamonds are conditional or decision symbols. It indicates a decision to be made.

Ovals or rounded rectangles, indicate start or end of the program usually containing the word "Start, begin” or "End“.

Слайд 18

Flow chart

Parallelogram are the input/output symbols

Arrows, showing what's called "flow of control“.

Flow chart Parallelogram are the input/output symbols Arrows, showing what's called "flow
An arrow coming from one symbol and ending at another symbol represents that control passes to the symbol the arrow points to. Arrows are also called flow lines.

Слайд 19

If selection structure flow chart

If selection structure flow chart

Слайд 20

If selection structure

example:
Pseudocode
If student’s grade is greater than or

If selection structure example: Pseudocode If student’s grade is greater than or
equal to 60
Print “Passed”
C++ code
if ( grade >= 60 ) cout << "Passed";

Слайд 21

If selection structure

Flow chart for the pseudocode statement.

If selection structure Flow chart for the pseudocode statement.

Слайд 22

Example
Example is using the relational and equality operators.
Following example used six if

Example Example is using the relational and equality operators. Following example used
statements to compare two numbers input by the user.
If the condition in any of these if statements is satisfied, the output statement associated with if is executed.
If the condition with the if statement is false the output statement associated with that if statement is skipped.
Observe the different outputs for various inputs at the end of the program.

Слайд 24

Input is 35 and 30

Input is 25 and 25

Input is 10 and

Input is 35 and 30 Input is 25 and 25 Input is 10 and 20
20

Слайд 25

The if-else statement

The if statement by itself will execute a single statement,

The if-else statement The if statement by itself will execute a single
or a group of statements , when conditions following if is true.
It does nothing when the conditions is false.
Can we execute one group of statements if the condition is true and another group of statements if the condition is false?
Of course this is what is the purpose of else statement, which is demonstrated in the following example:

Слайд 26


Ques: In a company an employee is paid as under:
If his basic

Ques: In a company an employee is paid as under: If his
salary is less than $1500, then HRA = 10% of basic salary and DA=90% of basic. If his salary is either equal to or above $1500, then HRA = $500 and DA=98% of basic salary. If the employee’s salary is input through keyboard write a program to find his gross salary.

Слайд 27

If/else selection structure

Different actions if conditions true or false
Syntax
A single statement

If/else selection structure Different actions if conditions true or false Syntax A
for each alternative
if (Boolean_expression)
yes_statement;
else
no_statement;
A sequence statement for each alternative
if (Boolean_expression)
{ yes_statement1;
yes_statement2;
yes_statement last; }
else
{ no_statement1;
no_statement2;
no_statement last; }

Слайд 28

If/else selection structure flow chart

Action if true

true

false

If/else selection structure flow chart Action if true true false

Слайд 29

If/else selection structure

Example
Pseudocode
if student’s grade is greater than or equal to 60 print

If/else selection structure Example Pseudocode if student’s grade is greater than or
“Passed”
else
print “Failed”
C++ code
if ( grade >= 60 ) cout << "Passed"; else cout << "Failed";

Слайд 30

If/else selection structure

Flow chart for the pseudocode

If/else selection structure Flow chart for the pseudocode

Слайд 31

Compound Statement

Compound statement
Set of statements within a pair of braces also known

Compound Statement Compound statement Set of statements within a pair of braces
as BLOCK
if ( grade >= 60 ) cout << "Passed.\n"; else { cout << "Failed.\n"; cout << "You must take this course again.\n"; }
Without braces,
cout << "You must take this course again.\n";
always executed

Слайд 32

Another simple Example

//program to determine if user is ill
#include
using namespace

Another simple Example //program to determine if user is ill #include using
std;
int main()
{
const double NORM = 98.6; // degree Fahranheit;
double temperature;
cout<<"Enter your temperature\t";
cin>>temperature;
if (temperature>NORM) //if temperature is greater than NORM print following statement
cout<<"\n\nYou are sick\n"<<"take rest and drink lots of fluids";
else //if temperature is <= NORM print following statement
cout<<"\n\nYou are perfectly fine";
return 0;
}

Слайд 33

output

Input is 100
100 > NORM

Input is 98
98

output Input is 100 100 > NORM Input is 98 98

Слайд 34

Example of if and if/else selection structure drawn in flow chart form

If

Example of if and if/else selection structure drawn in flow chart form
selection structure(program 1)

If/else selection structure(program2)

Слайд 35

c++ code for the flow chart of if selection structure (program 1).

//program

c++ code for the flow chart of if selection structure (program 1).
1
//program to find the part prices for the given part number.
#include
using namespace std;
int main()
{
int part_number, ;
float price;
cout<<"enter part number"< cin>>part_number;
cout<<"enter price"< cin>>price;
if(part_number==203)
price = price*1.1;
cout<<"price is "< return 0;
}

Слайд 36

Output of program 1

Part_number is equal to 203

Part_number is not equal to

Output of program 1 Part_number is equal to 203 Part_number is not equal to 203
203

Слайд 37

c++ code for the flow chart of if/else selection structure (program 2).
//program

c++ code for the flow chart of if/else selection structure (program 2).
to calculate the sales commission
#include
using namespace std;
int main()
{
float sales, commission;
cout<<"enter the sales"< cin>>sales;
if (sales>1500)
commission = sales*0.2;
else
commission = sales*0.1;
cout<<"commission is"<return 0;
}

Слайд 38

Output of program 2

Sales is 1500

Sales is greater than 1500

Output of program 2 Sales is 1500 Sales is greater than 1500

Слайд 39

Example of if/else
Write a program to calculate the gross pay of an

Example of if/else Write a program to calculate the gross pay of
employee.
The employee is paid at his basic hourly rate for the first 40 hours worked during a week. Any hours worked beyond 40 is considered overtime.
overtime is paid at the 1.5 times the hourly rate.

Pseudocode
If total number of hours >40
Gross pay = rate*40 + rate*1.5(hours – 40)
Else
Gross pay = rate * hours

Слайд 40

C++ code

#include
using namespace std;
int main()
{
int hour; //declaration
double gross_pay, rate;
cout<<"enter

C++ code #include using namespace std; int main() { int hour; //declaration
the hourly rate of pay\t"< cin>>rate; //reading data
cout<<"enter the number of hours worked \t"< cin>>hour; //readin data
if(hour>40) //condition if working hours is greater than 40
gross_pay = rate*40 + 1.5*rate*(hour - 40); //gross pay including extra hour
else //if working hour is <=40 then use this formula to get gross pay
gross_pay = rate*hour;
cout<<" Gross pay is \t"<return 0;
}

Слайд 41

output

Hour<40

Hour>40

output Hour Hour>40

Слайд 42

Nested if/else structure
if structure that rests entirely within another if structure, within

Nested if/else structure if structure that rests entirely within another if structure,
either the if or the else clause
One inside another, test for multiple cases
Once condition met, other statements skipped

Слайд 43

Simple example to understand the nested if/else

Consider an example of a

Simple example to understand the nested if/else Consider an example of a
program segment that accepts a gender code and print gender according to that code.
Pseudocode
if the gender code is F
print female
else
if the gender code is M
print male
else
print invalid code

Слайд 44

Simple example to understand the nested if/else

Flow chart

Simple example to understand the nested if/else Flow chart

Слайд 45

Simple example to understand the nested if/else

C++ code

//F and M are correct

Simple example to understand the nested if/else C++ code //F and M
codes
//f and m are invalid codes

Слайд 46

Nested if/else structure

following pseudocode is example of nested if/else
if student’s grade is

Nested if/else structure following pseudocode is example of nested if/else if student’s
greater than or equal to 90 Print “A”
else if student’s grade is greater than or equal to 80 Print “B” else if student’s grade is greater than or equal to 70 Print “C” else if student’s grade is greater than or equal to 60 Print “D” else
Print “F”

Слайд 47

Nested if/else structure

C++ code
if ( grade >= 90 ) // 90 and

Nested if/else structure C++ code if ( grade >= 90 ) //
above cout << "A"; else
if ( grade >= 80 ) // 80-89 cout << "B"; else
if ( grade >= 70 ) // 70-79 cout << "C"; else
if ( grade >= 60 ) // 60-69 cout << "D"; else // less than 60 cout << "F";
if grade>=90, first four conditions will be true. But only the cout statement after the first test will be executed. After that cout is executed, the else part of the outer if/else statement is skipped.

Слайд 48

Avoiding Common Pitfalls with if Statements
Forgetting that C++ is case sensitive
Assuming that

Avoiding Common Pitfalls with if Statements Forgetting that C++ is case sensitive
indentation has a logical purpose
Adding an unwanted semicolon
Forgetting curly braces
Using = instead of == (explained with example on next slide)
Making unnecessary comparisons
Имя файла: Lecture03---Copy.pptx
Количество просмотров: 33
Количество скачиваний: 0