SlideShare ist ein Scribd-Unternehmen logo
1 von 47
Downloaden Sie, um offline zu lesen
CSC 103
Lecture 7 & 8
Introduction to Computers and Programming
The Decision Control
2
 We need to alter our actions in the face of changing
circumstances
 If the weather is fine then I will go for a walk
 If the highway is busy I would take a diversion
 If the pitch takes spin, we would win the match
 If I am feeling well then I will watch a movie
 You can notice that all these decisions depend on
some condition being met
 C language too must be able to perform different sets
of actions depending on the circumstances
3
 Decision control instruction can be implemented in C
using:
(a) The if statement
(b)The if-else statement
(c)The conditional operators
The if Statement
4
 C uses the keyword if to implement the decision
control instruction
 Syntax is :
if ( expression )
execute this statement ;
 The keyword if tells the compiler that what follows is a
decision control instruction
 The expression following the keyword if is always
enclosed within a pair of parentheses
 if the expression is true then the statement is
executed otherwise not
5
 In general, the condition is expressed using C’s ‘Relational
Operator’
 Following are different relational operators:
 != is inequality or not equals to operator
 == is used for comparison of two quantities
 = is an assignment operator
Example
6
/* Demonstration of if statement */
main( )
{
int num ;
printf ( "Enter a number less than 10 " ) ;
scanf ( "%d", &num ) ;
if ( num <= 10 )
printf ( “The number is less than 10!" ) ;
}
7
 The general form of if statement is:
if (expression)
statement;
 Here the expression can be any valid expression including a
relational expression
 We can use arithmetic expressions in the if statement
e.g.
if (3+5-2)
printf(“ This works”);
if (a=10)
printf(“ Even this works”);
if(-5)
printf (“And even this works”);
if-else Statement
8
 Statements are executed when if condition is true
 We also want to execute statements when condition is
false
if ( condition )
do this ;
else
do this ;
if block
else block
Some if-else rules in C
9
 else block should come immediately after if block
 When if and else blocks contain only one statement
 then we can drop pair of braces i.e. { }
 Example:
 Take two values from user and determine which one is
smaller and which one is greater.
 Solution:
 First we draw a flow chart
Making decisions in C
 Sometimes your programs need to make logical
choices.
 Example:
IF score is higher than 50
THEN grade is "pass"
ELSE grade is "fail"
10
Making decisions in C
 Example:
IF score is higher than 50
THEN grade is PASS
ELSE grade is FAIL
 In C, this corresponds to one statement with 3 parts:
if (score > 50) {
grade = PASS;
}
else {
grade = FAIL;
}
11
Making decisions in C
 Part 1 : the condition
An expression that evaluates to TRUE or FALSE
if (score > 50)
{
grade = PASS;
}
else
{
grade = FAIL;
}
12
Making decisions in C
 Part 2 : the TRUE part
A block of statements that are executed if the condition
has evaluated to TRUE
if (score > 50)
{
grade = PASS;
}
else
{
grade = FAIL;
}
True part
13
Making decisions in C
 Part 3 : the FALSE part
A block of statements that are executed if the condition
has evaluated to FALSE
if (score > 50)
{
grade = PASS;
}
else
{
grade = FAIL;
}
if the condition
evaluates to FALSE,
the true part is skipped.
False part
14
Making decisions in C
 If the true part (or false part) consists of only one
statement, then the curly braces may be omitted.
 Example: these two statements are equivalent:
if (score > 50)
{
grade = PASS;
}
else
{
grade = FAIL;
}
if (score > 50)
grade = PASS;
else
grade = FAIL;
15
Making decisions in C
 Sometimes there are more than two parts. In those cases you
may use cascading (a.k.a. nested) if/else statements:
if (score > 90)
lettergrade = 'A';
else if (score > 75)
lettergrade = 'B';
else if (score > 60)
lettergrade = 'C';
else if (score > 50)
lettergrade = 'D';
else
lettergrade = 'F';
16
Making decisions in C
 if(condition)
statement;
 if (condition) {
statements;
statements; …
}
 if (condition) {
statements;
statements;…
}
else {
statements;
statements;...
}
3 forms of if statements;
(note indenting)
Note condition is
always in parentheses,
All TRUE parts and
all FALSE parts are
a single statement
or a single block
of statements
{}17
Some Valid if Statements in C
18
if ( 3 + 2 % 5 )
printf ( "This works" ) ;
if ( a = 10 )
printf ( "Even this works" ) ;
if ( -5 )
printf ( "Surprisingly even this works" ) ;
“Condition is false only if expression evaluates to 0”
Multiple Statements within if (Flowchart)
19
Multiple Statements within if (C Language)
20
/* Calculation of bonus */
main( )
{
int bonus, cy, yoj, yr_of_ser ;
printf ( "Enter current year and year of joining " ) ;
scanf ( "%d %d", &cy, &yoj ) ;
yr_of_ser = cy - yoj ;
if ( yr_of_ser > 3 )
{
bonus = 2500 ;
printf ( "Bonus = Rs. %d", bonus ) ;
}
}
21
#include<stdio.h>
#include<conio.h>
main()
{
int a,b;
printf("Enter 1st Number: ");
scanf("%d", &a);
printf("Enter 2nd Number: ");
scanf("%d", &b);
if( a > b )
printf("%d is greater than %d", a, b);
else
printf("%d is greater than %d", b, a);
getch();
}
Some tests
22
Test
No.
Output Remarks
01
Enter 1st Number: 15
Enter 2nd Number: 25
25 is greater than 15
2nd number is greater than 1st number
02
Enter 1st Number: 35
Enter 2nd Number: 20
35 is greater than 20
1st number is greater than 2nd number
03
Enter 1st Number: 300
Enter 2nd Number: 300
300 is greater than 300
Both numbers are equal…..Logical Error!
nested if-else
23
if ( condition )
do this ;
else
{
if ( condition )
do this ;
else
do this ;
}
“Modify our flow chart to solve logical error”
24
#include<stdio.h>
#include<conio.h>
main()
{
int a,b;
printf("Enter 1st Number: ");
scanf("%d", &a);
printf("Enter 2nd Number: ");
scanf("%d", &b);
if( a > b )
printf("%d is greater than %d", a, b);
else {
if( a == b )
printf("%d is equal to %d", a, b);
else
printf("%d is greater than %d", b, a);
}
getch();
}
else if Statement
25
 Every else is associated with its previous if
 The last else goes to work only if all the conditions fail
 In else if the last else is optional
 The else if clause is nothing different, it’s just a way of
rearranging the else with the if that follows it
 e.g.
Use of Logical Operators
26
 C allows usage of three logical operators
 &&, ||, !
 These are to be read as AND, OR, NOT respectively
 && and || are composed of double symbols
 Don’t use the single symbols & , |
 These single symbols also have meaning. These are
bitwise operators
 The && and || allow two or more conditions to be
combined in an if statement
27
Write a program to calculate the division obtained
by a student. The marks obtained by the student
in 5 different subjects are input through the
keyboard
 There are two ways to solve this problem
28
/* Method – I */
main( )
{
int m1, m2, m3, m4, m5, per ;
printf ( "Enter marks in five subjects " ) ;
scanf ( "%d %d %d %d %d", &m1, &m2, &m3, &m4, &m5 ) ;
per = ( m1 + m2 + m3 + m4 + m5 ) / 5 ;
if ( per >= 60 )
printf ( "First division n") ;
else
{
if ( per >= 50 )
printf ( "Second divisionn" ) ;
else
{
if ( per >= 40 )
printf ( "Third divisionn" ) ;
else
printf ( "Failn" ) ;
}
}
}
29
 This program uses nested if-else
 Three disadvantages of this method
 As the number of conditions go on increasing the level of
indentation also goes on increasing. As a result the
whole program creeps to the right.
 Care needs to be exercised to match the corresponding
ifs and elses.
 Care needs to be exercised to match the corresponding
pair of braces.
 All these three problems can be eliminated by usage
of ‘Logical operators’
30
/* Method – II */
main( )
{
int m1, m2, m3, m4, m5, per ;
printf ( "Enter marks in five subjects " ) ;
scanf ( "%d %d %d %d %d", &m1, &m2, &m3, &m4, &m5 ) ;
per = ( m1 + m2 + m3 + m4 + m5 ) / 5 ;
if ( per >= 60 )
printf ( "First divisionn" ) ;
if ( ( per >= 50 ) && ( per < 60 ) )
printf ( "Second divisionn" ) ;
if ( ( per >= 40 ) && ( per < 50 ) )
printf ( "Third divisionn" ) ;
if ( per < 40 )
printf ( "Failn" ) ;
}
31
 In the second if statement, the && operator is used to
combine two conditions
 ‘Second division’ gets printed if both conditions are
true
 Two advantages of this method
 The matching of the ifs with their corresponding elses
gets avoided
 In spite of using several conditions, the program doesn’t
expand to the right
Solution Using else if
32
/* Use of else if */
main( )
{
int m1, m2, m3, m4, m5, per ;
printf ( "Enter marks in five subjects " ) ;
scanf ( "%d %d %d %d %d", &m1, &m2, &m3, &m4, &m5 ) ;
per = ( m1+ m2 + m3 + m4+ m5 ) / 5 ;
if ( per >= 60 )
printf ( "First divisionn" ) ;
else if ( per >= 50 )
printf ( "Second divisionn" ) ;
else if ( per >= 40 )
printf ( "Third divisionn" ) ;
else
printf ( "failn" ) ;
}
Problem!
33
 Find smallest and greatest number among three input
numbers?
The ! (NOT) Operator
34
 The third logical operator is ! (NOT operator)
 This operator reverse the result of an expression
 If the result of an expression is TRUE, the ! operator will
make it FALSE and vice versa
 e.g.
 !(y<10) it means that “not y less than 10”
 if y is less than 10, the expression will be FALSE
 the same condition can be written as (y>=10)
 The NOT operator is often used to reverse the logical
value of a single variable
 if (!flag) is same as if(flag==0)
Hierarchy of Operators Revisited
35
 Since we have added the logical operators, so it’s time to
review the priorities of these operators
 The higher the position of an operator in the table, the
higher is its priority
Summary of Logical Operators
36
 Following figure summarizes the working of logical
operators
X 1
Logical Operators (Exercise)
37
 A company insures its drivers in the following cases:
 If the driver is married.
 If the driver is unmarried, male & above 30 years of age.
 If the driver is unmarried, female & above 25 years of
age.
 In all other cases the driver is not insured. If the
marital status, sex and age of the driver are the inputs,
write a program to determine whether the driver is to
be insured or not.
38
// One way to solve the problem
main( )
{
char sex, ms ;
int age ;
printf ( "Enter age, sex, marital status " ) ;
scanf ( "%d %c %c", &age, &sex, &ms ) ;
if ( ms == 'M' )
printf ( "Driver is insured" ) ;
else
{
if ( sex == 'M' )
{
if ( age > 30 )
printf ( "Driver is insured" ) ;
else
printf ( "Driver is not insured" ) ;
}
else
{
if ( age > 25 )
printf ( "Driver is insured" ) ;
else
printf ( "Driver is not insured" ) ;
}
}
}
Solution by using Logical Operators
39
main( )
{
char sex, ms ;
int age ;
printf ( "Enter age, sex, marital status " ) ;
scanf ( "%d %c %c“, &age, &sex, &ms ) ;
if ( ( ms == 'M') || ( ms == 'U' && sex == 'M' && age > 30 ) ||
( ms == 'U' && sex == 'F' && age > 25 ) )
printf ( "Driver is insured" ) ;
else
printf ( "Driver is not insured" ) ;
}
The Conditional Operators
40
 The conditional operators are ? and :
 Sometimes called Ternary Operators since they take three
arguments
 The general form is:
expression 1 ? expression 2 :
expression 3
 It means that if expression 1 is TRUE then the value
returned will be expression 2 otherwise the value
returned will be expression 3
 e.g.
int x,y;
scanf (“%d”, &x);
y=(x>5 ? 3 : 4)
 This statement will store 3 in y if x is greater than 5
otherwise it will store 4 in y
41
 Another example
int x,y;
scanf("%d", &x);
y = (x >= 10 && x <= 50 ? 1 : 0);
 Here if x>=10 && x<=50 evaluates to TRUE then y=1
otherwise y=0
The following points may be noted about conditional operators
42
 It’s not necessary that the conditional operators should be used only in
arithmetic statements
int i ;
scanf ( "%d", &i ) ;
i == 1 ? printf ("You have entered 1" ) : printf (
"Entered value is other than 1" ) ;
 The conditional operators can be nested as shown below:
int big, a, b, c ;
big = ( a > b ? ( a > c ? 3: 4 ) : ( b > c ? 6: 8 ) ) ;
43
 Check out the following conditional expression:
a > b ? g = a : g = b ;
 This will give you an error ‘Lvalue Required’. To remove the error
just enclose the statement in : part within a pair of parenthesis
a > b ? g = a : ( g = b ) ;
 In absence of parentheses the compiler believes that b is
being assigned to the result of the expression to the left
of second =.
 The limitation of the conditional operators is that after
the ? or after the : only one C statement can occur
What is the Output?
44
#include<stdio.h>
#include<conio.h>
main()
{
int a, b, g;
a=10;b=5;
a > b ? g = a : (g = b) ;
g == 10 ? printf ( "true" ) : printf ( "false" );
getch();
}
Some Rules
45
 The default scope of the if statement is only the next
statement.
 So, to execute more than one statement they must be written
in a pair of braces.
 An if block need not always be associated with an else
block.
 However, an else block is always associated with an if
statement.
 && and || are binary operators, whereas, ! is a unary
operator
 In C every test expression is evaluated in terms of zero and
non-zero values.
 A zero value is considered to be false and a non-zero value is
considered to be true.
 Assignment statements used with conditional operators
must be enclosed within a pair of parenthesis.
Output of program!
46
main( )
{
int a = 300, b, c ;
if ( a >= 400 )
b = 300 ;
c = 200 ;
printf ( "n%d %d", b, c ) ;
}
main( )
{
int x = 10, y = 20 ;
if ( x == y ) ;
printf ( "n%d %d", x, y ) ;
}
47
main( )
{
int i = 4, j = -1, k = 0, y, z ;
y = i + 5 && j + 1 || k + 2 ;
z = i + 5 || j + 1 && k + 2 ;
printf ( "ny = %d z = %d", y, z ) ;
}

Weitere ähnliche Inhalte

Was ist angesagt?

The Three Basic Selection Structures in C++ Programming Concepts
The Three Basic Selection Structures in C++ Programming ConceptsThe Three Basic Selection Structures in C++ Programming Concepts
The Three Basic Selection Structures in C++ Programming ConceptsTech
 
Decision making statements in C
Decision making statements in CDecision making statements in C
Decision making statements in CRabin BK
 
Decision making and branching in c programming
Decision making and branching in c programmingDecision making and branching in c programming
Decision making and branching in c programmingPriyansh Thakar
 
C programming decision making
C programming decision makingC programming decision making
C programming decision makingSENA
 
Selection Statements in C Programming
Selection Statements in C ProgrammingSelection Statements in C Programming
Selection Statements in C ProgrammingKamal Acharya
 
COM1407: Program Control Structures – Decision Making & Branching
COM1407: Program Control Structures – Decision Making & BranchingCOM1407: Program Control Structures – Decision Making & Branching
COM1407: Program Control Structures – Decision Making & BranchingHemantha Kulathilake
 
Control Structures
Control StructuresControl Structures
Control StructuresGhaffar Khan
 
[ITP - Lecture 08] Decision Control Structures (If Statement)
[ITP - Lecture 08] Decision Control Structures (If Statement)[ITP - Lecture 08] Decision Control Structures (If Statement)
[ITP - Lecture 08] Decision Control Structures (If Statement)Muhammad Hammad Waseem
 
Control structure C++
Control structure C++Control structure C++
Control structure C++Anil Kumar
 
FLOW OF CONTROL-INTRO PYTHON
FLOW OF CONTROL-INTRO PYTHONFLOW OF CONTROL-INTRO PYTHON
FLOW OF CONTROL-INTRO PYTHONvikram mahendra
 
3. control statements
3. control statements3. control statements
3. control statementsamar kakde
 
control statements of clangauge (ii unit)
control statements of clangauge (ii unit)control statements of clangauge (ii unit)
control statements of clangauge (ii unit)Prashant Sharma
 
04 control structures 1
04 control structures 104 control structures 1
04 control structures 1Jomel Penalba
 

Was ist angesagt? (20)

The Three Basic Selection Structures in C++ Programming Concepts
The Three Basic Selection Structures in C++ Programming ConceptsThe Three Basic Selection Structures in C++ Programming Concepts
The Three Basic Selection Structures in C++ Programming Concepts
 
Control structures in c
Control structures in cControl structures in c
Control structures in c
 
Decision making statements in C
Decision making statements in CDecision making statements in C
Decision making statements in C
 
Decision Making and Branching
Decision Making and BranchingDecision Making and Branching
Decision Making and Branching
 
Decision making and branching in c programming
Decision making and branching in c programmingDecision making and branching in c programming
Decision making and branching in c programming
 
C programming decision making
C programming decision makingC programming decision making
C programming decision making
 
Selection Statements in C Programming
Selection Statements in C ProgrammingSelection Statements in C Programming
Selection Statements in C Programming
 
Control structure in c
Control structure in cControl structure in c
Control structure in c
 
COM1407: Program Control Structures – Decision Making & Branching
COM1407: Program Control Structures – Decision Making & BranchingCOM1407: Program Control Structures – Decision Making & Branching
COM1407: Program Control Structures – Decision Making & Branching
 
Control Structures
Control StructuresControl Structures
Control Structures
 
Control All
Control AllControl All
Control All
 
[ITP - Lecture 08] Decision Control Structures (If Statement)
[ITP - Lecture 08] Decision Control Structures (If Statement)[ITP - Lecture 08] Decision Control Structures (If Statement)
[ITP - Lecture 08] Decision Control Structures (If Statement)
 
Control structure C++
Control structure C++Control structure C++
Control structure C++
 
FLOW OF CONTROL-INTRO PYTHON
FLOW OF CONTROL-INTRO PYTHONFLOW OF CONTROL-INTRO PYTHON
FLOW OF CONTROL-INTRO PYTHON
 
3. control statements
3. control statements3. control statements
3. control statements
 
Control Structures: Part 1
Control Structures: Part 1Control Structures: Part 1
Control Structures: Part 1
 
control statements of clangauge (ii unit)
control statements of clangauge (ii unit)control statements of clangauge (ii unit)
control statements of clangauge (ii unit)
 
Control statements in c
Control statements in cControl statements in c
Control statements in c
 
04 control structures 1
04 control structures 104 control structures 1
04 control structures 1
 
Lecture 3
Lecture 3Lecture 3
Lecture 3
 

Ähnlich wie ICP - Lecture 7 and 8

CONTROLSTRUCTURES.ppt
CONTROLSTRUCTURES.pptCONTROLSTRUCTURES.ppt
CONTROLSTRUCTURES.pptSanjjaayyy
 
Dti2143 chap 4 control structures aka_selection
Dti2143 chap 4 control structures aka_selectionDti2143 chap 4 control structures aka_selection
Dti2143 chap 4 control structures aka_selectionalish sha
 
Dti2143 chap 4 control structures aka_selection
Dti2143 chap 4 control structures aka_selectionDti2143 chap 4 control structures aka_selection
Dti2143 chap 4 control structures aka_selectionalish sha
 
Visula C# Programming Lecture 3
Visula C# Programming Lecture 3Visula C# Programming Lecture 3
Visula C# Programming Lecture 3Abou Bakr Ashraf
 
Control statements-Computer programming
Control statements-Computer programmingControl statements-Computer programming
Control statements-Computer programmingnmahi96
 
Control Structures in C
Control Structures in CControl Structures in C
Control Structures in Csana shaikh
 
C Programming: Control Structure
C Programming: Control StructureC Programming: Control Structure
C Programming: Control StructureSokngim Sa
 
Decisions in C or If condition
Decisions in C or If conditionDecisions in C or If condition
Decisions in C or If conditionyarkhosh
 
[C++][a] tutorial 2
[C++][a] tutorial 2[C++][a] tutorial 2
[C++][a] tutorial 2yasir_cesc
 
Loops and conditional statements
Loops and conditional statementsLoops and conditional statements
Loops and conditional statementsSaad Sheikh
 
Fundamental of Information Technology - UNIT 8
Fundamental of Information Technology - UNIT 8Fundamental of Information Technology - UNIT 8
Fundamental of Information Technology - UNIT 8Shipra Swati
 
Chapter 4 flow control structures and arrays
Chapter 4 flow control structures and arraysChapter 4 flow control structures and arrays
Chapter 4 flow control structures and arrayssshhzap
 

Ähnlich wie ICP - Lecture 7 and 8 (20)

CONTROLSTRUCTURES.ppt
CONTROLSTRUCTURES.pptCONTROLSTRUCTURES.ppt
CONTROLSTRUCTURES.ppt
 
Dti2143 chap 4 control structures aka_selection
Dti2143 chap 4 control structures aka_selectionDti2143 chap 4 control structures aka_selection
Dti2143 chap 4 control structures aka_selection
 
Dti2143 chap 4 control structures aka_selection
Dti2143 chap 4 control structures aka_selectionDti2143 chap 4 control structures aka_selection
Dti2143 chap 4 control structures aka_selection
 
Visula C# Programming Lecture 3
Visula C# Programming Lecture 3Visula C# Programming Lecture 3
Visula C# Programming Lecture 3
 
Control statements-Computer programming
Control statements-Computer programmingControl statements-Computer programming
Control statements-Computer programming
 
control statement
control statement control statement
control statement
 
CH-4 (1).pptx
CH-4 (1).pptxCH-4 (1).pptx
CH-4 (1).pptx
 
What is c
What is cWhat is c
What is c
 
Control Structures in C
Control Structures in CControl Structures in C
Control Structures in C
 
C Programming: Control Structure
C Programming: Control StructureC Programming: Control Structure
C Programming: Control Structure
 
Decisions in C or If condition
Decisions in C or If conditionDecisions in C or If condition
Decisions in C or If condition
 
Java Programmin: Selections
Java Programmin: SelectionsJava Programmin: Selections
Java Programmin: Selections
 
[C++][a] tutorial 2
[C++][a] tutorial 2[C++][a] tutorial 2
[C++][a] tutorial 2
 
Loops and conditional statements
Loops and conditional statementsLoops and conditional statements
Loops and conditional statements
 
Programming for Problem Solving
Programming for Problem SolvingProgramming for Problem Solving
Programming for Problem Solving
 
Fundamental of Information Technology - UNIT 8
Fundamental of Information Technology - UNIT 8Fundamental of Information Technology - UNIT 8
Fundamental of Information Technology - UNIT 8
 
Conditional Statements
Conditional StatementsConditional Statements
Conditional Statements
 
Chapter 4 flow control structures and arrays
Chapter 4 flow control structures and arraysChapter 4 flow control structures and arrays
Chapter 4 flow control structures and arrays
 
C Programming Unit-2
C Programming Unit-2C Programming Unit-2
C Programming Unit-2
 
Ch4
Ch4Ch4
Ch4
 

Mehr von Hassaan Rahman

Lecture#12 preservation of hadees
Lecture#12 preservation of hadeesLecture#12 preservation of hadees
Lecture#12 preservation of hadeesHassaan Rahman
 
Isl. lecture#11 ahadees
Isl. lecture#11 ahadeesIsl. lecture#11 ahadees
Isl. lecture#11 ahadeesHassaan Rahman
 
Isl. lecture#10 the miracle of the holy qura'n
Isl. lecture#10 the miracle of the holy qura'nIsl. lecture#10 the miracle of the holy qura'n
Isl. lecture#10 the miracle of the holy qura'nHassaan Rahman
 
Isl. lecture#9 compilation in the time of hazrat usman (r.a.)
Isl. lecture#9 compilation in the time of hazrat usman (r.a.)Isl. lecture#9 compilation in the time of hazrat usman (r.a.)
Isl. lecture#9 compilation in the time of hazrat usman (r.a.)Hassaan Rahman
 
Isl. lecture#8 the holy qura'n
Isl. lecture#8 the holy qura'nIsl. lecture#8 the holy qura'n
Isl. lecture#8 the holy qura'nHassaan Rahman
 
Isl. lecture#7 risalat
Isl. lecture#7 risalatIsl. lecture#7 risalat
Isl. lecture#7 risalatHassaan Rahman
 
ECA - Source Transformation
ECA - Source TransformationECA - Source Transformation
ECA - Source TransformationHassaan Rahman
 
Isl. lecture#6 effect of tawheed
Isl. lecture#6 effect of tawheedIsl. lecture#6 effect of tawheed
Isl. lecture#6 effect of tawheedHassaan Rahman
 
Isl. lecture#5 tawheed
Isl. lecture#5 tawheedIsl. lecture#5 tawheed
Isl. lecture#5 tawheedHassaan Rahman
 
Electric Circuit - Lecture 04
Electric Circuit - Lecture 04Electric Circuit - Lecture 04
Electric Circuit - Lecture 04Hassaan Rahman
 
Isl. lecture#3 need of islam
Isl. lecture#3 need of islamIsl. lecture#3 need of islam
Isl. lecture#3 need of islamHassaan Rahman
 
Lab 02 Resistor color coding and ohms law
Lab 02   Resistor color coding and ohms lawLab 02   Resistor color coding and ohms law
Lab 02 Resistor color coding and ohms lawHassaan Rahman
 

Mehr von Hassaan Rahman (20)

Step natural
Step naturalStep natural
Step natural
 
Lecture#12 preservation of hadees
Lecture#12 preservation of hadeesLecture#12 preservation of hadees
Lecture#12 preservation of hadees
 
Isl. lecture#11 ahadees
Isl. lecture#11 ahadeesIsl. lecture#11 ahadees
Isl. lecture#11 ahadees
 
Isl. lecture#10 the miracle of the holy qura'n
Isl. lecture#10 the miracle of the holy qura'nIsl. lecture#10 the miracle of the holy qura'n
Isl. lecture#10 the miracle of the holy qura'n
 
Isl. lecture#9 compilation in the time of hazrat usman (r.a.)
Isl. lecture#9 compilation in the time of hazrat usman (r.a.)Isl. lecture#9 compilation in the time of hazrat usman (r.a.)
Isl. lecture#9 compilation in the time of hazrat usman (r.a.)
 
Circuits
CircuitsCircuits
Circuits
 
Isl. lecture#8 the holy qura'n
Isl. lecture#8 the holy qura'nIsl. lecture#8 the holy qura'n
Isl. lecture#8 the holy qura'n
 
Isl. lecture#7 risalat
Isl. lecture#7 risalatIsl. lecture#7 risalat
Isl. lecture#7 risalat
 
Thev norton eq
Thev norton eqThev norton eq
Thev norton eq
 
ECA - Source Transformation
ECA - Source TransformationECA - Source Transformation
ECA - Source Transformation
 
Isl. lecture#6 effect of tawheed
Isl. lecture#6 effect of tawheedIsl. lecture#6 effect of tawheed
Isl. lecture#6 effect of tawheed
 
Isl. lecture#5 tawheed
Isl. lecture#5 tawheedIsl. lecture#5 tawheed
Isl. lecture#5 tawheed
 
Circuits5
Circuits5Circuits5
Circuits5
 
Electric Circuit - Lecture 04
Electric Circuit - Lecture 04Electric Circuit - Lecture 04
Electric Circuit - Lecture 04
 
ECA - Lecture 03
ECA - Lecture 03ECA - Lecture 03
ECA - Lecture 03
 
Isl. lecture#4 islam
Isl. lecture#4 islamIsl. lecture#4 islam
Isl. lecture#4 islam
 
Isl. lecture#3 need of islam
Isl. lecture#3 need of islamIsl. lecture#3 need of islam
Isl. lecture#3 need of islam
 
ICP - Lecture 6
ICP - Lecture 6ICP - Lecture 6
ICP - Lecture 6
 
ICP - Lecture 5
ICP - Lecture 5ICP - Lecture 5
ICP - Lecture 5
 
Lab 02 Resistor color coding and ohms law
Lab 02   Resistor color coding and ohms lawLab 02   Resistor color coding and ohms law
Lab 02 Resistor color coding and ohms law
 

Kürzlich hochgeladen

Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGSujit Pal
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 

Kürzlich hochgeladen (20)

Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAG
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 

ICP - Lecture 7 and 8

  • 1. CSC 103 Lecture 7 & 8 Introduction to Computers and Programming
  • 2. The Decision Control 2  We need to alter our actions in the face of changing circumstances  If the weather is fine then I will go for a walk  If the highway is busy I would take a diversion  If the pitch takes spin, we would win the match  If I am feeling well then I will watch a movie  You can notice that all these decisions depend on some condition being met  C language too must be able to perform different sets of actions depending on the circumstances
  • 3. 3  Decision control instruction can be implemented in C using: (a) The if statement (b)The if-else statement (c)The conditional operators
  • 4. The if Statement 4  C uses the keyword if to implement the decision control instruction  Syntax is : if ( expression ) execute this statement ;  The keyword if tells the compiler that what follows is a decision control instruction  The expression following the keyword if is always enclosed within a pair of parentheses  if the expression is true then the statement is executed otherwise not
  • 5. 5  In general, the condition is expressed using C’s ‘Relational Operator’  Following are different relational operators:  != is inequality or not equals to operator  == is used for comparison of two quantities  = is an assignment operator
  • 6. Example 6 /* Demonstration of if statement */ main( ) { int num ; printf ( "Enter a number less than 10 " ) ; scanf ( "%d", &num ) ; if ( num <= 10 ) printf ( “The number is less than 10!" ) ; }
  • 7. 7  The general form of if statement is: if (expression) statement;  Here the expression can be any valid expression including a relational expression  We can use arithmetic expressions in the if statement e.g. if (3+5-2) printf(“ This works”); if (a=10) printf(“ Even this works”); if(-5) printf (“And even this works”);
  • 8. if-else Statement 8  Statements are executed when if condition is true  We also want to execute statements when condition is false if ( condition ) do this ; else do this ; if block else block
  • 9. Some if-else rules in C 9  else block should come immediately after if block  When if and else blocks contain only one statement  then we can drop pair of braces i.e. { }  Example:  Take two values from user and determine which one is smaller and which one is greater.  Solution:  First we draw a flow chart
  • 10. Making decisions in C  Sometimes your programs need to make logical choices.  Example: IF score is higher than 50 THEN grade is "pass" ELSE grade is "fail" 10
  • 11. Making decisions in C  Example: IF score is higher than 50 THEN grade is PASS ELSE grade is FAIL  In C, this corresponds to one statement with 3 parts: if (score > 50) { grade = PASS; } else { grade = FAIL; } 11
  • 12. Making decisions in C  Part 1 : the condition An expression that evaluates to TRUE or FALSE if (score > 50) { grade = PASS; } else { grade = FAIL; } 12
  • 13. Making decisions in C  Part 2 : the TRUE part A block of statements that are executed if the condition has evaluated to TRUE if (score > 50) { grade = PASS; } else { grade = FAIL; } True part 13
  • 14. Making decisions in C  Part 3 : the FALSE part A block of statements that are executed if the condition has evaluated to FALSE if (score > 50) { grade = PASS; } else { grade = FAIL; } if the condition evaluates to FALSE, the true part is skipped. False part 14
  • 15. Making decisions in C  If the true part (or false part) consists of only one statement, then the curly braces may be omitted.  Example: these two statements are equivalent: if (score > 50) { grade = PASS; } else { grade = FAIL; } if (score > 50) grade = PASS; else grade = FAIL; 15
  • 16. Making decisions in C  Sometimes there are more than two parts. In those cases you may use cascading (a.k.a. nested) if/else statements: if (score > 90) lettergrade = 'A'; else if (score > 75) lettergrade = 'B'; else if (score > 60) lettergrade = 'C'; else if (score > 50) lettergrade = 'D'; else lettergrade = 'F'; 16
  • 17. Making decisions in C  if(condition) statement;  if (condition) { statements; statements; … }  if (condition) { statements; statements;… } else { statements; statements;... } 3 forms of if statements; (note indenting) Note condition is always in parentheses, All TRUE parts and all FALSE parts are a single statement or a single block of statements {}17
  • 18. Some Valid if Statements in C 18 if ( 3 + 2 % 5 ) printf ( "This works" ) ; if ( a = 10 ) printf ( "Even this works" ) ; if ( -5 ) printf ( "Surprisingly even this works" ) ; “Condition is false only if expression evaluates to 0”
  • 19. Multiple Statements within if (Flowchart) 19
  • 20. Multiple Statements within if (C Language) 20 /* Calculation of bonus */ main( ) { int bonus, cy, yoj, yr_of_ser ; printf ( "Enter current year and year of joining " ) ; scanf ( "%d %d", &cy, &yoj ) ; yr_of_ser = cy - yoj ; if ( yr_of_ser > 3 ) { bonus = 2500 ; printf ( "Bonus = Rs. %d", bonus ) ; } }
  • 21. 21 #include<stdio.h> #include<conio.h> main() { int a,b; printf("Enter 1st Number: "); scanf("%d", &a); printf("Enter 2nd Number: "); scanf("%d", &b); if( a > b ) printf("%d is greater than %d", a, b); else printf("%d is greater than %d", b, a); getch(); }
  • 22. Some tests 22 Test No. Output Remarks 01 Enter 1st Number: 15 Enter 2nd Number: 25 25 is greater than 15 2nd number is greater than 1st number 02 Enter 1st Number: 35 Enter 2nd Number: 20 35 is greater than 20 1st number is greater than 2nd number 03 Enter 1st Number: 300 Enter 2nd Number: 300 300 is greater than 300 Both numbers are equal…..Logical Error!
  • 23. nested if-else 23 if ( condition ) do this ; else { if ( condition ) do this ; else do this ; } “Modify our flow chart to solve logical error”
  • 24. 24 #include<stdio.h> #include<conio.h> main() { int a,b; printf("Enter 1st Number: "); scanf("%d", &a); printf("Enter 2nd Number: "); scanf("%d", &b); if( a > b ) printf("%d is greater than %d", a, b); else { if( a == b ) printf("%d is equal to %d", a, b); else printf("%d is greater than %d", b, a); } getch(); }
  • 25. else if Statement 25  Every else is associated with its previous if  The last else goes to work only if all the conditions fail  In else if the last else is optional  The else if clause is nothing different, it’s just a way of rearranging the else with the if that follows it  e.g.
  • 26. Use of Logical Operators 26  C allows usage of three logical operators  &&, ||, !  These are to be read as AND, OR, NOT respectively  && and || are composed of double symbols  Don’t use the single symbols & , |  These single symbols also have meaning. These are bitwise operators  The && and || allow two or more conditions to be combined in an if statement
  • 27. 27 Write a program to calculate the division obtained by a student. The marks obtained by the student in 5 different subjects are input through the keyboard  There are two ways to solve this problem
  • 28. 28 /* Method – I */ main( ) { int m1, m2, m3, m4, m5, per ; printf ( "Enter marks in five subjects " ) ; scanf ( "%d %d %d %d %d", &m1, &m2, &m3, &m4, &m5 ) ; per = ( m1 + m2 + m3 + m4 + m5 ) / 5 ; if ( per >= 60 ) printf ( "First division n") ; else { if ( per >= 50 ) printf ( "Second divisionn" ) ; else { if ( per >= 40 ) printf ( "Third divisionn" ) ; else printf ( "Failn" ) ; } } }
  • 29. 29  This program uses nested if-else  Three disadvantages of this method  As the number of conditions go on increasing the level of indentation also goes on increasing. As a result the whole program creeps to the right.  Care needs to be exercised to match the corresponding ifs and elses.  Care needs to be exercised to match the corresponding pair of braces.  All these three problems can be eliminated by usage of ‘Logical operators’
  • 30. 30 /* Method – II */ main( ) { int m1, m2, m3, m4, m5, per ; printf ( "Enter marks in five subjects " ) ; scanf ( "%d %d %d %d %d", &m1, &m2, &m3, &m4, &m5 ) ; per = ( m1 + m2 + m3 + m4 + m5 ) / 5 ; if ( per >= 60 ) printf ( "First divisionn" ) ; if ( ( per >= 50 ) && ( per < 60 ) ) printf ( "Second divisionn" ) ; if ( ( per >= 40 ) && ( per < 50 ) ) printf ( "Third divisionn" ) ; if ( per < 40 ) printf ( "Failn" ) ; }
  • 31. 31  In the second if statement, the && operator is used to combine two conditions  ‘Second division’ gets printed if both conditions are true  Two advantages of this method  The matching of the ifs with their corresponding elses gets avoided  In spite of using several conditions, the program doesn’t expand to the right
  • 32. Solution Using else if 32 /* Use of else if */ main( ) { int m1, m2, m3, m4, m5, per ; printf ( "Enter marks in five subjects " ) ; scanf ( "%d %d %d %d %d", &m1, &m2, &m3, &m4, &m5 ) ; per = ( m1+ m2 + m3 + m4+ m5 ) / 5 ; if ( per >= 60 ) printf ( "First divisionn" ) ; else if ( per >= 50 ) printf ( "Second divisionn" ) ; else if ( per >= 40 ) printf ( "Third divisionn" ) ; else printf ( "failn" ) ; }
  • 33. Problem! 33  Find smallest and greatest number among three input numbers?
  • 34. The ! (NOT) Operator 34  The third logical operator is ! (NOT operator)  This operator reverse the result of an expression  If the result of an expression is TRUE, the ! operator will make it FALSE and vice versa  e.g.  !(y<10) it means that “not y less than 10”  if y is less than 10, the expression will be FALSE  the same condition can be written as (y>=10)  The NOT operator is often used to reverse the logical value of a single variable  if (!flag) is same as if(flag==0)
  • 35. Hierarchy of Operators Revisited 35  Since we have added the logical operators, so it’s time to review the priorities of these operators  The higher the position of an operator in the table, the higher is its priority
  • 36. Summary of Logical Operators 36  Following figure summarizes the working of logical operators X 1
  • 37. Logical Operators (Exercise) 37  A company insures its drivers in the following cases:  If the driver is married.  If the driver is unmarried, male & above 30 years of age.  If the driver is unmarried, female & above 25 years of age.  In all other cases the driver is not insured. If the marital status, sex and age of the driver are the inputs, write a program to determine whether the driver is to be insured or not.
  • 38. 38 // One way to solve the problem main( ) { char sex, ms ; int age ; printf ( "Enter age, sex, marital status " ) ; scanf ( "%d %c %c", &age, &sex, &ms ) ; if ( ms == 'M' ) printf ( "Driver is insured" ) ; else { if ( sex == 'M' ) { if ( age > 30 ) printf ( "Driver is insured" ) ; else printf ( "Driver is not insured" ) ; } else { if ( age > 25 ) printf ( "Driver is insured" ) ; else printf ( "Driver is not insured" ) ; } } }
  • 39. Solution by using Logical Operators 39 main( ) { char sex, ms ; int age ; printf ( "Enter age, sex, marital status " ) ; scanf ( "%d %c %c“, &age, &sex, &ms ) ; if ( ( ms == 'M') || ( ms == 'U' && sex == 'M' && age > 30 ) || ( ms == 'U' && sex == 'F' && age > 25 ) ) printf ( "Driver is insured" ) ; else printf ( "Driver is not insured" ) ; }
  • 40. The Conditional Operators 40  The conditional operators are ? and :  Sometimes called Ternary Operators since they take three arguments  The general form is: expression 1 ? expression 2 : expression 3  It means that if expression 1 is TRUE then the value returned will be expression 2 otherwise the value returned will be expression 3  e.g. int x,y; scanf (“%d”, &x); y=(x>5 ? 3 : 4)  This statement will store 3 in y if x is greater than 5 otherwise it will store 4 in y
  • 41. 41  Another example int x,y; scanf("%d", &x); y = (x >= 10 && x <= 50 ? 1 : 0);  Here if x>=10 && x<=50 evaluates to TRUE then y=1 otherwise y=0
  • 42. The following points may be noted about conditional operators 42  It’s not necessary that the conditional operators should be used only in arithmetic statements int i ; scanf ( "%d", &i ) ; i == 1 ? printf ("You have entered 1" ) : printf ( "Entered value is other than 1" ) ;  The conditional operators can be nested as shown below: int big, a, b, c ; big = ( a > b ? ( a > c ? 3: 4 ) : ( b > c ? 6: 8 ) ) ;
  • 43. 43  Check out the following conditional expression: a > b ? g = a : g = b ;  This will give you an error ‘Lvalue Required’. To remove the error just enclose the statement in : part within a pair of parenthesis a > b ? g = a : ( g = b ) ;  In absence of parentheses the compiler believes that b is being assigned to the result of the expression to the left of second =.  The limitation of the conditional operators is that after the ? or after the : only one C statement can occur
  • 44. What is the Output? 44 #include<stdio.h> #include<conio.h> main() { int a, b, g; a=10;b=5; a > b ? g = a : (g = b) ; g == 10 ? printf ( "true" ) : printf ( "false" ); getch(); }
  • 45. Some Rules 45  The default scope of the if statement is only the next statement.  So, to execute more than one statement they must be written in a pair of braces.  An if block need not always be associated with an else block.  However, an else block is always associated with an if statement.  && and || are binary operators, whereas, ! is a unary operator  In C every test expression is evaluated in terms of zero and non-zero values.  A zero value is considered to be false and a non-zero value is considered to be true.  Assignment statements used with conditional operators must be enclosed within a pair of parenthesis.
  • 46. Output of program! 46 main( ) { int a = 300, b, c ; if ( a >= 400 ) b = 300 ; c = 200 ; printf ( "n%d %d", b, c ) ; } main( ) { int x = 10, y = 20 ; if ( x == y ) ; printf ( "n%d %d", x, y ) ; }
  • 47. 47 main( ) { int i = 4, j = -1, k = 0, y, z ; y = i + 5 && j + 1 || k + 2 ; z = i + 5 || j + 1 && k + 2 ; printf ( "ny = %d z = %d", y, z ) ; }