0% found this document useful (0 votes)
5 views

L3 - Increment and Decrement Operations, Conditional and Logical Operations

Uploaded by

vevele3809
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

L3 - Increment and Decrement Operations, Conditional and Logical Operations

Uploaded by

vevele3809
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 48

CE 204: Computer Programming Sessional

Increment & Decrement Operations


Conditional and Logical Operations 1
Ahmed Farhan Ahnaf Siddique

Assistant Professor,
Department of Civil Engineering,
BUET

2
Program to Find Average Speed
/* Program that finds the average speed of three
vehicles */
#include <iostream>
using namespace std;
int main()
{
double num1, num2, num3, average;
cout<<"Program to find the average speed of
three vehicles"<<endl;
cout<<"The first number ="<<endl;
cin>>num1;
cout<<"The second number ="<<endl;
cin>>num2; 3
Program to Find Average Speed
cout<<"The third number ="<<endl;
cin>>num3;
average = (num1 + num2 + num3)/3;
cout<< "Trial program"<<endl;
cout<<"Average =" <<average<<endl; //Prints the
value stored in variable average
return 0;
}

4
Increment and Decrement Operators

• The values of integral objects can be incremented and


decremented with the ++ and -- operators,
respectively.

• Each of these operators has two versions: a “pre”


version and a “post” version.

• The “pre” version performs the operation (either


adding 1 or subtracting 1) on the object before the
resulting value is used in its surrounding context.

5
Increment and Decrement Operators

• The “post” version performs the operation after the


object’s current value has been used.

++variable or --variable  prefix form

variable++ or variable--  postfix form

• If prefix form exists in an expression, then they are


executed first and then the expression.

• If postfix form exists in an expression, then the


expression is executed first and then they are
executed.
6
Increment and Decrement Operators
#include <iostream>
using namespace std;
int main()
{ // shows the difference between m++ and ++m:
int m,n;
m = 44;
n = ++m; // the pre-increment operator is applied to m
cout << "m = " << m << ", n = " << n << endl;
m = 44;
n = m++; // the post-increment operator is applied to m
cout << "m = " << m << ", n = " << n << endl;
}
7
Increment and Decrement Operators
Output: m = 45, n = 45

m = 45, n = 44

// n = ++m; the pre-increment operator is applied to m

• This line increments m to 45 and then assigns that


value to n

// n = m++; the post-increment operator is applied to m

• This line increments m to 45 only after it has assigned


the value of m to n
8
Type Conversions
• C++ converts integral types into floating point types
when they are expected

int n = 22;

float x = 3.14159;

x += n; // the value 22 is automatically


converted to 22.0

cout << x - 2 << endl; // value 2 is

automatically converted to 2.0

• Converting from integer to float like this is what one


would expect and is usually taken for granted. 9
Type Conversions
• But converting from a floating point type to an integer
type is not automatic. high to low => not automatic, as data lose
may occur, type casting
• In general, if T is one type and v is a value of another
type, then the expression:

T(v) converts v to type T

• This is called type casting.

• For example, if expr is a floating-point expression and


n is a variable of type int, then,

n = int(expr); converts the value of expr to type int


and assigns it to n
10
Type Conversions

• The effect is to remove the real number’s fractional


part, leaving only its whole number part to be
assigned to n.

• For example, 2.71828 would be converted to 2.


• Note that this is truncating, not rounding.

• When one type is to be converted to a “higher” type,


the type cast operator is not needed.

• This is called type promotion.


low to high, no data lost, needs no casting ritual, type promotion

11
Type Casting
int a=10,b=3;
#include <iostream> double c=double(a)/double(b); //type casting
cout<<c<<endl;
double e=a,f=b; //type promotion
using namespace std; c=e/f;
cout<<c<<endl;
int g=c; //high to low te ashlam but casting lage nai :)
cout<<g;
int main()

{ // casts a double value as an int:

double v = 1234.56789;

int n = int(v);

cout << "v = " << v << ", n = " << n << endl;

Output: v = 1234.57,n = 1234


12
Promotion of Types
#include <iostream>
using namespace std;
int main()
{ // prints promoted values of 65 from char to double:
char c='A'; cout << " char c = " << c << endl;
short k=c; cout << " short k = " << k << endl;
int m=k; cout << " int m = " << m << endl;
long n=m; cout << " long n = " << n << endl;
float x=m; cout << " float x = " << x << endl;
double y=x; cout << "double y = " << y << endl;
} 13
Promotion of Types

14
Numeric Overflow
• On most computers the long int type allows
4,294,967,296 different values

• That’s a lot of values, but it’s still finite

• Computers are finite, so the range of any type must


also be finite but in mathematics there are infinitely
many integers

• Consequently, computers are manifestly prone to error


when their numeric values become too large

• That kind of error is called numeric overflow


15
Numeric Overflow
#include <iostream>
using namespace std;
int main()
{// prints n until it overflows:
int n=1000;
cout << "n = " << n << endl;
n *= 1000; // multiplies n by 1000
cout << "n = " << n << endl;
n *= 1000; // multiplies n by 1000
cout << "n = " << n << endl;
n *= 1000; // multiplies n by 1000
cout << "n = " << n << endl;
} 16
Numeric Overflow

17
Round-off Error
• Round-off error is another kind of error that often
occurs when computers do arithmetic on rational
numbers.

• For example, the number 1/3 might be stored as


0.333333, which is not exactly equal to 1/3.

• The difference is called round-off error.

• In some cases, these errors can cause serious problems.

18
The if Statement
• The if statement allows conditional execution.

• Its syntax is if (condition) statement;


• Where condition is an integral expression and
statement is any executable statement.

• The statement will be executed only if the value of


the integral expression is nonzero.

• In C++, whenever an integral expression is used as


a condition, the value 0 means “false” and all other
values mean “true”.

• The parentheses around condition is required. 19


The if Statement

20
The if Statement

21
The if Statement
#include <iostream>
using namespace std;
int main()
{
int n,d;
cout << "Enter two positive integers: ";
cin >> n >> d;
if (n%d) cout << n << " is not divisible by " << d <<
endl;
}
• Note: This program is inadequate because it
provides no affirmative information when n is
divisible by d. 22
The if … else Statement
• The if … else statement causes one of two
alternative statements to execute depending upon
whether the condition is true, its syntax is

₋ if (condition) statement1;
₋ else statement2;
• condition is an integral expression and statement1
and statement2 are executable statements.

• If the value of the condition is nonzero then


statement1 will execute; otherwise statement2 will
execute. 23
The if … else Statement

24
The if … else Statement
#include <iostream>
using namespace std;
int main()
{
int n,d;
cout << "Enter two positive integers: ";
cin >> n >> d;
if (n%d) cout << n << " is not divisible by " << d <<
endl;
else cout << n << " is divisible by " << d << endl;
}

• Note that the if … else is only one statement, even


though it requires two semicolons. 25
Comparison/Relational Operators
• The six comparison operators are:

₋ x < y // x is less than y

₋ x > y // x is greater than y

₋ x <= y // x is less than or equal to y

₋ x >= y // x is greater than or equal to y

₋ x == y // x is equal to y

₋ x != y // x is not equal to y

• These can be used to compare the values of


expressions of any ordinal type.
26
Comparison/Relational Operators

• The resulting integral expression is interpreted as a


condition that is either false or true according to
whether the value of the expression is zero.

• For example, the expression 7*8 < 6*9 evaluates to


zero, which means that the condition is false.

• Note that in C++ the single equal sign “=” is the


assignment operator, and the double equal sign
“==” is the equality operator.

27
Comparison/Relational Operators
#include <iostream>
using namespace std;
int main()
{
int m,n;
cout << "Enter two integers: ";
cin >> m >> n;
if (m < n) cout << m << " is the minimum." << endl;
else cout << n << " is the minimum." << endl;
}
28
Comparison/Relational Operators
#include <iostream>
using namespace std;
int main()
{
int n;
cout << "Enter an integer: ";
cin >> n;
if (n = 22) cout << n << " = 22" << endl; // LOGICAL
ERROR!
else cout << n << " != 22" << endl;
} 29
Compound Conditions
• Conditions such as n % d and x >= y can be
combined to form compound conditions.

• This is done using the logical operators && (and),


|| (or), and ! (not).

• p && q evaluates to true if and only if both p and q


evaluate to true.

• p || q evaluates to false if and only if both p and q


evaluate to false.

• !p evaluates to true if and only if p evaluates to false.


30
Compound Conditions
• For example, (n % d || x >= y) will be false if and
only if n % d is zero and x is less than y.

• The definitions of the three logical operators are


usually given by the truth tables below

p q p && q p q p || q p !p

T T T T T T T F
T F F T F T F T
F T F F T T
F F F F F F 31
Compound Conditions
#include <iostream>
using namespace std;
int main()
{
char ans;
cout << "Are you enrolled (y/n): ";
cin >> ans;
If (ans == 'Y' || ans == 'y') cout << "You are
enrolled.\n";
else cout << "You are not enrolled.\n";
}

32
Short-Circuiting
• Compound conditions that use && and || will not
evaluate the second operand of the condition unless
necessary, this is called short-circuiting.

• As the truth tables show, the condition p && q will


be false if p is false.

• In that case there is no need to evaluate q.

• Similarly if p is true then there is no need to


evaluate q to determine that p || q is true.

• In both cases the value of the condition is known as


soon as the first operand is evaluated.
33
Short-Circuiting
#include <iostream>
using namespace std;
int main()
{
int n,d;
cout << "Enter two positive integers: ";
cin >> n >> d;
if (d != 0 && n%d == 0) cout << d << " divides " <<
n << endl;
else cout << d << " does not divide " << n << endl;
}
• This short-circuiting prevents the program from
crashing. Because, when d is zero, the expression
n % d cannot be evaluated. 34
Nested Selection Statements
• Like compound statements, selection statements
can be used wherever any other statement can be
used.

• So a selection statement can be used within another


selection statement.

• This is called nesting statements.

• When if … else statements are nested, the compiler


uses the following rule to parse the compound
statement:

Match each else with the last unmatched if 35


Nested Selection Statements
#include <iostream>
using namespace std;
int main()
{
int n,d;
cout << "Enter two positive integers: ";
cin >> n >> d;
if (d != 0)
if (n%d == 0) cout << d << " divides " << n
<< endl;
else cout << d << " does not divide " << n
<< endl;
else cout << d << " does not divide " << n << endl;
36
}
The else … if Construct

• Nested if ... else statements are often used to test a


sequence of parallel alternatives, where only the else
clauses contain further nesting.

• In that case, the resulting compound statement is


usually formatted by lining up the else if phrases to
emphasize the parallel nature of the logic.

37
The else … if Construct

38
The else … if Construct
#include <iostream>
using namespace std;
int main()
{
int score;
cout << "Enter your test score: ";
cin >> score;
if (score > 100) cout <<"Error: that score is out of range.";
else if (score >= 90) cout << "Your grade is an A." << endl;
else if (score >= 80) cout << "Your grade is a B." << endl;
else if (score >= 70) cout << "Your grade is a C." << endl;
else if (score >= 60) cout << "Your grade is a D." << endl;
else if (score >= 0) cout << "Your grade is an F." << endl;
else cout << "Error: that score is out of range.";
} 39
The switch Statement
• The switch statement can be used instead of the else
if construct to implement a sequence of parallel
alternatives. Its syntax is:
switch (expression)
{ case constant1: statementList1;
case constant2: statementList2;
case constant3: statementList3;
:
:
case constantN: statementListN;
default: statementList0;
} 40
The switch Statement
• This evaluates the expression and then looks for its
value among the case constants.

• If the value is found among the constants listed,


then the statements in the corresponding
statementList are executed.

• Otherwise, if there is a default (which is optional),


then the program branches to its statementList.

• The expression must evaluate to an integral type


and the constants must be integral constants.
41
The switch Statement
#include <iostream>
using namespace std;
int main()
{
int score;
cout << "Enter your test score: "; cin >> score;
switch (score/10)
{ case 10:
case 9: cout << "Your grade is an A." << endl; break;
case 8: cout << "Your grade is a B." << endl; break;
case 7: cout << "Your grade is a C." << endl; break;
case 6: cout << "Your grade is a D." << endl; break;
case 5: 42
The switch Statement
case 4:
case 3:
case 2:
case 1:
case 0: cout << "Your grade is an F." << endl; break;
default: cout << "Error: score is out of range.\n";
}
cout << "Goodbye." << endl;
}

• But with no break statements, the program execution


falls through all the case statements it encounters.

43
The break Statement
• It is normal to put a break statement at the end of
each case clause in a switch statement.

• Without it, the program execution will not branch


directly out of the switch block after it finishes
executing its case statement sequence.

• Instead, it will continue within the switch block,


executing the statements in the next case sequence.

• This (usually) unintended consequence is called a


fall through.

44
Conditional Expression Operator
• C++ provides a special operator that often can be
used in place of the if ... else statement.

• It is called the conditional expression operator.

• It uses the ? and the : symbols in this syntax:


condition ? expression1 : expression2

• It is a ternary operator; i.e., it combines three


operands to produce a value.

• That resulting value is either the value of expression1


if ( condition ) {
or the value of expression2. statement1;
}
else {
statement2; 45
}
Conditional Expression Operator
• For example, the assignment

min = ( x<y ? x : y );

would assign the minimum of x and y to min.


Because, if the condition x<y is true, the expression
(x<y ? x : y) evaluates to x; otherwise it evaluates to y.

• Conditional expression statements should be used


sparingly; only when the condition and both
expressions are very simple.

46
Conditional Expression Operator
#include <iostream>
using namespace std;
int main() if ( condition ) {
statement1;
}
{ else {
statement2;
}
int m, n;
cout << "Enter two integers: ";
cin >> m >> n;
cout << ( m<n ? m : n ) << " is the minimum." <<
endl;
} 47
Thank You!
48

You might also like