SlideShare a Scribd company logo
1 of 32
Programming Methodology &
Abstractions
1
Lecture 8
Decision and Control Statements:
if
CS106
Programming Methodology
& Abstractions
FALL 2005
Balochistan University
of I.T & M.S
Faculty of System Sciences
Sadique Ahmed Bugti
Programming Methodology &
Abstractions
2
Conditional Expressions
 As we have seen, the following logical,
relational and equality operators exist in C:
 These operators are used in conjunction with
decision and control statements.
Programming Methodology &
Abstractions
3
Conditional Expressions
 For example:
heart_rate > 75
performs the necessary comparison and
evaluates to 1 (true) when heart_rate
is over 75; and evaluates to 0 (false)
when heart_rate is not greater than
75.
Programming Methodology &
Abstractions
4
Conditional Expressions
 For example:
marks is in the range 40 to 100, (40  marks 
b) inclusive
(marks >= 40) && (marks <= 100)
performs the necessary comparison and
evaluates to 1 (true) when marks is greater than
or equal to 40 AND marks is less than or equal to
100; and evaluates to 0 (false) when the either
expression is false.
Programming Methodology &
Abstractions
5
Decision and Control Statements
 Decision or control-flow statements specify the
order in which computations are performed.
• they are branching statements
 There are two principle control statements:
•if-else
•switch
Programming Methodology &
Abstractions
6
if-else statement
• The if-else statement is used to carry out
a logical test and then take one of two
possible actions, depending on whether the
outcome of the test is true or false.
• The else portion of the statement is
optional.
Programming Methodology &
Abstractions
7
if statement
if structure (Single Selection)
F
T
Programming Methodology &
Abstractions
8
if statement
 The simplest possible if-else statement takes the
form:
if(expression)
statement;
 The expression is evaluated:
• If expression has a nonzero value (i.e., if
expression if true), statement is executed.
• If expression has a value of zero (i.e., if
expression is false) then the statement will be
ignored.
 The expression must be placed in
parenthesis, as shown.
Programming Methodology &
Abstractions
9
if statement
 For example:
if (heart_rate > 75)
printf(“Heart rate is
normaln”);
if (y != 0.0)
x = x / y;
Programming Methodology &
Abstractions
10
if statement
 Be careful! What happens here?
a = -12;
if (a > 0)
printf(“a is positiven”);
b = sqrt(a);
Programming Methodology &
Abstractions
11
if statement
 Where appropriate, compound statements can
be used to group a series of statements under
the control of a single if expression.
• For example:
if (j < k) if (j < k) {
min = j; min = j;
if (j < k) max =
k;
max = k; }
Programming Methodology &
Abstractions
12
Compound if statement
 Computes the growth rate of a population from
time t1 to time t2.
if (pop_t2 > pop_t1)
{
growth = pop_t2 – pop_t1;
growth_pct = (growth/pop_t1) *
100;
printf(“The growth % is %.2fn”,
growth_pct);
}
Programming Methodology &
Abstractions
13
if-else statement
 The if-else statement is an extension of if used in
situations where there are two alternatives:
if(expression)
statement1;
else
statement2;
 The expression is evaluated:
• If expression has a nonzero value (i.e., if expression
is true), statement1 is executed.
• If the expression has a value of zero (i.e., if
expression is false) and there is an else part,
statement2 is executed.
Programming Methodology &
Abstractions
14
if-else statement
if else structure
(double selection)
TF
Programming Methodology &
Abstractions
15
if-else statement
 For example:
if (marks >=40)
printf(“Pass);
else
printf(“Fail”);
 If marks >= y is true, then “Pass” will be
printed; if it is false, “Fail” will be printed.
Programming Methodology &
Abstractions
16
if-else statement
 For example:
if (ch >= ‘a’ && ch <= ‘z’)
++lower_char;
else
++other_char;
 If ch >= ‘a’ && ch <= ‘z’ (c is a
lowercase character) is true, the variable
lower_char is incremented; if it is false,
other_char is incremented.
Programming Methodology &
Abstractions
17
Example: Finding the Minimum Value
/* Find the minimum of two values */
#include <stdio.h>
void main(void)
{
int x, y, min;
printf(“Input two integers: “);
scanf(“%d%d”, &x, &y);
if (x < y)
min = x;
else
min = y;
printf(“The minimum value is %dn”, min);
}
Programming Methodology &
Abstractions
18
if-else statement
 An example of a syntax error:
if (a != b){
a = a + 1;
b = b + 1;
};
else
c = a + b;
 The syntax error occurs because the semicolon
following the right brace creates an empty
statement, and consequently the else has
nowhere to attach.
Programming Methodology &
Abstractions
19
The “dangling-else” Problem
 There is an ambiguity when an else is
omitted from a nested if statement:
“dangling else” problem
if (marks>= 40)
if (marks > 90)
printf(“Excellent”);
else
printf(“Failed”);
 This is resolved by associating the else with
the closest previous else-less if.
Programming Methodology &
Abstractions
20
The “dangling-else” Problem
 If that’s not what you want, use braces to
force the proper association.
if (marks>=40{
if (marks >90)
printf(“Excellent”);
}
else
printf(“Fail”);
 Use braces where there are nested ifs.
Programming Methodology &
Abstractions
21
Nested if statement
 Sometimes the if-else statement is
used for a multi-way decision.
 The expressions are evaluated in order;
if any expression is true, the statement
associated with it is executed, and this
terminates the whole chain.
 The last else can be used to handle the
default case where none of the other
conditions is satisfied.
Programming Methodology &
Abstractions
22
Nested if statement
if (expression1)
statement1;
else if (expression2)
statement2;
:
:
else if (expressionN)
statementN;
else
default_statement;
Programming Methodology &
Abstractions
23
Nested if statement
 For example
if (marks >= 80)
printf(“Grade A”);
else if (marks >=70)
printf(“Grade B”);
else if(marks>=50)
printf(“Grade C”)
else /* marks less than 50 */
printf(“Fail”);
Programming Methodology &
Abstractions
24
Example: Quadratic Equation
 A simple C program that calculates the
real roots of a quadratic equation;
ax+bx+c=0
using the quadratic formula.
Programming Methodology &
Abstractions
25
Example: Quadratic Equation (quadratic.c)
#include <stdio.h>
#include <math.h>
void main()
{
double a, b, c, d, x1, x2;
/* Read input data */
printf("na = ");
scanf("%lf", &a);
printf("b = ");
scanf("%lf", &b);
printf("c = ");
scanf("%lf", &c);
/* Perform calculation */
d = sqrt(b * b - 4. * a * c);
x1 = (-b + d) / (2 * a);
x2 = (-b - d) / (2 * a);
/* Display output */
printf("nx1 = %12.3e n x2 = %12.3en", x1, x2);
}
Programming Methodology &
Abstractions
26
Example: Quadratic Equation
 The program quadratic.c, listed
previously, is incapable of dealing
correctly with cases where the
 roots are complex (i.e., b2< 4ac),
 or cases where a = 0.
Programming Methodology &
Abstractions
27
Example: Quadratic Equation
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
void main()
{
double a, b, c, d, e, x1, x2;
/* Read input data */
printf("na = ");
scanf("%lf", &a);
printf("b = ");
scanf("%lf", &b);
printf("c = ");
scanf("%lf", &c);
Programming Methodology &
Abstractions
28
Example: Quadratic Equation
/* Test for complex roots */
e = b * b - 4. * a * c;
if (e < 0.)
{
printf("nError: roots are complexn");
exit(1);
}
/* Test for a = 0. */
if (a == 0.)
{
printf("nError: a = 0.n");
exit(1);
}
/* Perform calculation */
d = sqrt(e);
x1 = (-b + d) / (2. * a);
x2 = (-b - d) / (2. * a);
/* Display output */
printf("nx1 = %12.3e x2 = %12.3en", x1, x2);
}
Programming Methodology &
Abstractions
29
Example: Quadratic Equation
 The standard library function call exit(1)
(header file: stdlib.h) causes the program
to abort with an error status.
 Execution of the above program for the case
of complex roots yields the following output:
a = 4
b = 2
c = 6
Error: roots are complex %
Programming Methodology &
Abstractions
30
Example: Quadratic Equation
/* Perform calculation */
e = b * b - 4. * a * c;
if (e > 0.) // Test for real roots
{
/* Case of real roots */
d = sqrt(e);
x1 = (-b + d) / (2. * a);
x2 = (-b - d) / (2. * a);
printf("nx1 = %12.3e x2 = %12.3en", x1, x2);
}
else
{
/* Case of complex roots */
d = sqrt(-e);
x1 = -b / (2 * a);
x2 = d / (2 * a);
printf("nx1 = (%12.3e, %12.3e) nx2 = (%12.3e, %12.3e)n",
x1, x2, x1, -x2);
}
Programming Methodology &
Abstractions
31
Example: Quadratic Equation
 The output from the above program for
the case of complex roots looks like:
a = 9
b = 2
c = 2
x1 = ( -1.111e-01, 4.581e-01)
x2 = ( -1.111e-01, -4.581e-01)
Programming Methodology &
Abstractions
32
The End

More Related Content

What's hot

Chapter 4 : Balagurusamy Programming ANSI in C
Chapter 4 : Balagurusamy Programming ANSI in CChapter 4 : Balagurusamy Programming ANSI in C
Chapter 4 : Balagurusamy Programming ANSI in CBUBT
 
Conditional statements
Conditional statementsConditional statements
Conditional statementsNabishaAK
 
Cs291 assignment solution
Cs291 assignment solutionCs291 assignment solution
Cs291 assignment solutionKuntal Bhowmick
 
programs of c www.eakanchha.com
 programs of c www.eakanchha.com programs of c www.eakanchha.com
programs of c www.eakanchha.comAkanchha Agrawal
 
The solution manual of c by robin
The solution manual of c by robinThe solution manual of c by robin
The solution manual of c by robinAbdullah Al Naser
 
Core programming in c
Core programming in cCore programming in c
Core programming in cRahul Pandit
 
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
 
Operators and expressions in c language
Operators and expressions in c languageOperators and expressions in c language
Operators and expressions in c languagetanmaymodi4
 
COM1407: Program Control Structures – Repetition and Loops
COM1407: Program Control Structures – Repetition and Loops COM1407: Program Control Structures – Repetition and Loops
COM1407: Program Control Structures – Repetition and Loops Hemantha Kulathilake
 
Conditional Control in MATLAB Scripts
Conditional Control in MATLAB ScriptsConditional Control in MATLAB Scripts
Conditional Control in MATLAB ScriptsShameer Ahmed Koya
 
TMPA-2015: Implementing the MetaVCG Approach in the C-light System
TMPA-2015: Implementing the MetaVCG Approach in the C-light SystemTMPA-2015: Implementing the MetaVCG Approach in the C-light System
TMPA-2015: Implementing the MetaVCG Approach in the C-light SystemIosif Itkin
 

What's hot (20)

Chapter 4 : Balagurusamy Programming ANSI in C
Chapter 4 : Balagurusamy Programming ANSI in CChapter 4 : Balagurusamy Programming ANSI in C
Chapter 4 : Balagurusamy Programming ANSI in C
 
Conditional statements
Conditional statementsConditional statements
Conditional statements
 
Decision Making and Branching
Decision Making and BranchingDecision Making and Branching
Decision Making and Branching
 
Cs291 assignment solution
Cs291 assignment solutionCs291 assignment solution
Cs291 assignment solution
 
ICP - Lecture 7 and 8
ICP - Lecture 7 and 8ICP - Lecture 7 and 8
ICP - Lecture 7 and 8
 
programs of c www.eakanchha.com
 programs of c www.eakanchha.com programs of c www.eakanchha.com
programs of c www.eakanchha.com
 
Unit 2
Unit 2Unit 2
Unit 2
 
Control statments in c
Control statments in cControl statments in c
Control statments in c
 
Ansi c
Ansi cAnsi c
Ansi c
 
175035 cse lab-03
175035 cse lab-03175035 cse lab-03
175035 cse lab-03
 
The solution manual of c by robin
The solution manual of c by robinThe solution manual of c by robin
The solution manual of c by robin
 
Core programming in c
Core programming in cCore programming in c
Core programming 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
 
Operators and expressions in c language
Operators and expressions in c languageOperators and expressions in c language
Operators and expressions in c language
 
COM1407: Program Control Structures – Repetition and Loops
COM1407: Program Control Structures – Repetition and Loops COM1407: Program Control Structures – Repetition and Loops
COM1407: Program Control Structures – Repetition and Loops
 
6 operators-in-c
6 operators-in-c6 operators-in-c
6 operators-in-c
 
Conditional Control in MATLAB Scripts
Conditional Control in MATLAB ScriptsConditional Control in MATLAB Scripts
Conditional Control in MATLAB Scripts
 
Chap 5 c++
Chap 5 c++Chap 5 c++
Chap 5 c++
 
Chap 4 c++
Chap 4 c++Chap 4 c++
Chap 4 c++
 
TMPA-2015: Implementing the MetaVCG Approach in the C-light System
TMPA-2015: Implementing the MetaVCG Approach in the C-light SystemTMPA-2015: Implementing the MetaVCG Approach in the C-light System
TMPA-2015: Implementing the MetaVCG Approach in the C-light System
 

Similar to Programming Methodology if Statements

Programming Fundamentals Decisions
Programming Fundamentals  Decisions Programming Fundamentals  Decisions
Programming Fundamentals Decisions imtiazalijoono
 
Control Structures in C
Control Structures in CControl Structures in C
Control Structures in Csana shaikh
 
Control structure of c
Control structure of cControl structure of c
Control structure of cKomal Kotak
 
C Programming: Control Structure
C Programming: Control StructureC Programming: Control Structure
C Programming: Control StructureSokngim Sa
 
CONTROL FLOW in C.pptx
CONTROL FLOW in C.pptxCONTROL FLOW in C.pptx
CONTROL FLOW in C.pptxSmitaAparadh
 
Unit ii chapter 2 Decision making and Branching in C
Unit ii chapter 2 Decision making and Branching in CUnit ii chapter 2 Decision making and Branching in C
Unit ii chapter 2 Decision making and Branching in CSowmya Jyothi
 
Fundamental of Information Technology - UNIT 8
Fundamental of Information Technology - UNIT 8Fundamental of Information Technology - UNIT 8
Fundamental of Information Technology - UNIT 8Shipra Swati
 
Control structuresin c
Control structuresin cControl structuresin c
Control structuresin cVikash Dhal
 
C programming
C programmingC programming
C programmingXad Kuain
 
C decision making and looping.
C decision making and looping.C decision making and looping.
C decision making and looping.Haard Shah
 
Cs1123 5 selection_if
Cs1123 5 selection_ifCs1123 5 selection_if
Cs1123 5 selection_ifTAlha MAlik
 
Scala as a Declarative Language
Scala as a Declarative LanguageScala as a Declarative Language
Scala as a Declarative Languagevsssuresh
 
CONTROLSTRUCTURES.ppt
CONTROLSTRUCTURES.pptCONTROLSTRUCTURES.ppt
CONTROLSTRUCTURES.pptSanjjaayyy
 
Programming for Problem Solving
Programming for Problem SolvingProgramming for Problem Solving
Programming for Problem SolvingSreedhar Chowdam
 
Programming fundamental 02
Programming fundamental 02Programming fundamental 02
Programming fundamental 02Suhail Akraam
 
Understand more about C
Understand more about CUnderstand more about C
Understand more about CYi-Hsiu Hsu
 
Operators in c language
Operators in c languageOperators in c language
Operators in c languageAmit Singh
 

Similar to Programming Methodology if Statements (20)

Programming Fundamentals Decisions
Programming Fundamentals  Decisions Programming Fundamentals  Decisions
Programming Fundamentals Decisions
 
Control Structures in C
Control Structures in CControl Structures in C
Control Structures in C
 
Control structure of c
Control structure of cControl structure of c
Control structure of c
 
C Programming: Control Structure
C Programming: Control StructureC Programming: Control Structure
C Programming: Control Structure
 
CONTROL FLOW in C.pptx
CONTROL FLOW in C.pptxCONTROL FLOW in C.pptx
CONTROL FLOW in C.pptx
 
Unit ii chapter 2 Decision making and Branching in C
Unit ii chapter 2 Decision making and Branching in CUnit ii chapter 2 Decision making and Branching in C
Unit ii chapter 2 Decision making and Branching in C
 
Fundamental of Information Technology - UNIT 8
Fundamental of Information Technology - UNIT 8Fundamental of Information Technology - UNIT 8
Fundamental of Information Technology - UNIT 8
 
Control structuresin c
Control structuresin cControl structuresin c
Control structuresin c
 
What is c
What is cWhat is c
What is c
 
C programming
C programmingC programming
C programming
 
control statement
control statement control statement
control statement
 
C decision making and looping.
C decision making and looping.C decision making and looping.
C decision making and looping.
 
Cs1123 5 selection_if
Cs1123 5 selection_ifCs1123 5 selection_if
Cs1123 5 selection_if
 
Scala as a Declarative Language
Scala as a Declarative LanguageScala as a Declarative Language
Scala as a Declarative Language
 
CONTROLSTRUCTURES.ppt
CONTROLSTRUCTURES.pptCONTROLSTRUCTURES.ppt
CONTROLSTRUCTURES.ppt
 
Programming for Problem Solving
Programming for Problem SolvingProgramming for Problem Solving
Programming for Problem Solving
 
Programming fundamental 02
Programming fundamental 02Programming fundamental 02
Programming fundamental 02
 
Understand more about C
Understand more about CUnderstand more about C
Understand more about C
 
C tutorial
C tutorialC tutorial
C tutorial
 
Operators in c language
Operators in c languageOperators in c language
Operators in c language
 

More from yarkhosh

Arithmetic Operator in C
Arithmetic Operator in CArithmetic Operator in C
Arithmetic Operator in Cyarkhosh
 
Math Functions in C Scanf Printf
Math Functions in C Scanf PrintfMath Functions in C Scanf Printf
Math Functions in C Scanf Printfyarkhosh
 
Operators in C
Operators in COperators in C
Operators in Cyarkhosh
 
Data Types in C
Data Types in CData Types in C
Data Types in Cyarkhosh
 
Escape Sequences and Variables
Escape Sequences and VariablesEscape Sequences and Variables
Escape Sequences and Variablesyarkhosh
 
Introduct To C Language Programming
Introduct To C Language ProgrammingIntroduct To C Language Programming
Introduct To C Language Programmingyarkhosh
 

More from yarkhosh (7)

Arithmetic Operator in C
Arithmetic Operator in CArithmetic Operator in C
Arithmetic Operator in C
 
Algorithm
AlgorithmAlgorithm
Algorithm
 
Math Functions in C Scanf Printf
Math Functions in C Scanf PrintfMath Functions in C Scanf Printf
Math Functions in C Scanf Printf
 
Operators in C
Operators in COperators in C
Operators in C
 
Data Types in C
Data Types in CData Types in C
Data Types in C
 
Escape Sequences and Variables
Escape Sequences and VariablesEscape Sequences and Variables
Escape Sequences and Variables
 
Introduct To C Language Programming
Introduct To C Language ProgrammingIntroduct To C Language Programming
Introduct To C Language Programming
 

Recently uploaded

Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceanilsa9823
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 

Recently uploaded (20)

Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 

Programming Methodology if Statements

  • 1. Programming Methodology & Abstractions 1 Lecture 8 Decision and Control Statements: if CS106 Programming Methodology & Abstractions FALL 2005 Balochistan University of I.T & M.S Faculty of System Sciences Sadique Ahmed Bugti
  • 2. Programming Methodology & Abstractions 2 Conditional Expressions  As we have seen, the following logical, relational and equality operators exist in C:  These operators are used in conjunction with decision and control statements.
  • 3. Programming Methodology & Abstractions 3 Conditional Expressions  For example: heart_rate > 75 performs the necessary comparison and evaluates to 1 (true) when heart_rate is over 75; and evaluates to 0 (false) when heart_rate is not greater than 75.
  • 4. Programming Methodology & Abstractions 4 Conditional Expressions  For example: marks is in the range 40 to 100, (40  marks  b) inclusive (marks >= 40) && (marks <= 100) performs the necessary comparison and evaluates to 1 (true) when marks is greater than or equal to 40 AND marks is less than or equal to 100; and evaluates to 0 (false) when the either expression is false.
  • 5. Programming Methodology & Abstractions 5 Decision and Control Statements  Decision or control-flow statements specify the order in which computations are performed. • they are branching statements  There are two principle control statements: •if-else •switch
  • 6. Programming Methodology & Abstractions 6 if-else statement • The if-else statement is used to carry out a logical test and then take one of two possible actions, depending on whether the outcome of the test is true or false. • The else portion of the statement is optional.
  • 7. Programming Methodology & Abstractions 7 if statement if structure (Single Selection) F T
  • 8. Programming Methodology & Abstractions 8 if statement  The simplest possible if-else statement takes the form: if(expression) statement;  The expression is evaluated: • If expression has a nonzero value (i.e., if expression if true), statement is executed. • If expression has a value of zero (i.e., if expression is false) then the statement will be ignored.  The expression must be placed in parenthesis, as shown.
  • 9. Programming Methodology & Abstractions 9 if statement  For example: if (heart_rate > 75) printf(“Heart rate is normaln”); if (y != 0.0) x = x / y;
  • 10. Programming Methodology & Abstractions 10 if statement  Be careful! What happens here? a = -12; if (a > 0) printf(“a is positiven”); b = sqrt(a);
  • 11. Programming Methodology & Abstractions 11 if statement  Where appropriate, compound statements can be used to group a series of statements under the control of a single if expression. • For example: if (j < k) if (j < k) { min = j; min = j; if (j < k) max = k; max = k; }
  • 12. Programming Methodology & Abstractions 12 Compound if statement  Computes the growth rate of a population from time t1 to time t2. if (pop_t2 > pop_t1) { growth = pop_t2 – pop_t1; growth_pct = (growth/pop_t1) * 100; printf(“The growth % is %.2fn”, growth_pct); }
  • 13. Programming Methodology & Abstractions 13 if-else statement  The if-else statement is an extension of if used in situations where there are two alternatives: if(expression) statement1; else statement2;  The expression is evaluated: • If expression has a nonzero value (i.e., if expression is true), statement1 is executed. • If the expression has a value of zero (i.e., if expression is false) and there is an else part, statement2 is executed.
  • 14. Programming Methodology & Abstractions 14 if-else statement if else structure (double selection) TF
  • 15. Programming Methodology & Abstractions 15 if-else statement  For example: if (marks >=40) printf(“Pass); else printf(“Fail”);  If marks >= y is true, then “Pass” will be printed; if it is false, “Fail” will be printed.
  • 16. Programming Methodology & Abstractions 16 if-else statement  For example: if (ch >= ‘a’ && ch <= ‘z’) ++lower_char; else ++other_char;  If ch >= ‘a’ && ch <= ‘z’ (c is a lowercase character) is true, the variable lower_char is incremented; if it is false, other_char is incremented.
  • 17. Programming Methodology & Abstractions 17 Example: Finding the Minimum Value /* Find the minimum of two values */ #include <stdio.h> void main(void) { int x, y, min; printf(“Input two integers: “); scanf(“%d%d”, &x, &y); if (x < y) min = x; else min = y; printf(“The minimum value is %dn”, min); }
  • 18. Programming Methodology & Abstractions 18 if-else statement  An example of a syntax error: if (a != b){ a = a + 1; b = b + 1; }; else c = a + b;  The syntax error occurs because the semicolon following the right brace creates an empty statement, and consequently the else has nowhere to attach.
  • 19. Programming Methodology & Abstractions 19 The “dangling-else” Problem  There is an ambiguity when an else is omitted from a nested if statement: “dangling else” problem if (marks>= 40) if (marks > 90) printf(“Excellent”); else printf(“Failed”);  This is resolved by associating the else with the closest previous else-less if.
  • 20. Programming Methodology & Abstractions 20 The “dangling-else” Problem  If that’s not what you want, use braces to force the proper association. if (marks>=40{ if (marks >90) printf(“Excellent”); } else printf(“Fail”);  Use braces where there are nested ifs.
  • 21. Programming Methodology & Abstractions 21 Nested if statement  Sometimes the if-else statement is used for a multi-way decision.  The expressions are evaluated in order; if any expression is true, the statement associated with it is executed, and this terminates the whole chain.  The last else can be used to handle the default case where none of the other conditions is satisfied.
  • 22. Programming Methodology & Abstractions 22 Nested if statement if (expression1) statement1; else if (expression2) statement2; : : else if (expressionN) statementN; else default_statement;
  • 23. Programming Methodology & Abstractions 23 Nested if statement  For example if (marks >= 80) printf(“Grade A”); else if (marks >=70) printf(“Grade B”); else if(marks>=50) printf(“Grade C”) else /* marks less than 50 */ printf(“Fail”);
  • 24. Programming Methodology & Abstractions 24 Example: Quadratic Equation  A simple C program that calculates the real roots of a quadratic equation; ax+bx+c=0 using the quadratic formula.
  • 25. Programming Methodology & Abstractions 25 Example: Quadratic Equation (quadratic.c) #include <stdio.h> #include <math.h> void main() { double a, b, c, d, x1, x2; /* Read input data */ printf("na = "); scanf("%lf", &a); printf("b = "); scanf("%lf", &b); printf("c = "); scanf("%lf", &c); /* Perform calculation */ d = sqrt(b * b - 4. * a * c); x1 = (-b + d) / (2 * a); x2 = (-b - d) / (2 * a); /* Display output */ printf("nx1 = %12.3e n x2 = %12.3en", x1, x2); }
  • 26. Programming Methodology & Abstractions 26 Example: Quadratic Equation  The program quadratic.c, listed previously, is incapable of dealing correctly with cases where the  roots are complex (i.e., b2< 4ac),  or cases where a = 0.
  • 27. Programming Methodology & Abstractions 27 Example: Quadratic Equation #include <stdio.h> #include <math.h> #include <stdlib.h> void main() { double a, b, c, d, e, x1, x2; /* Read input data */ printf("na = "); scanf("%lf", &a); printf("b = "); scanf("%lf", &b); printf("c = "); scanf("%lf", &c);
  • 28. Programming Methodology & Abstractions 28 Example: Quadratic Equation /* Test for complex roots */ e = b * b - 4. * a * c; if (e < 0.) { printf("nError: roots are complexn"); exit(1); } /* Test for a = 0. */ if (a == 0.) { printf("nError: a = 0.n"); exit(1); } /* Perform calculation */ d = sqrt(e); x1 = (-b + d) / (2. * a); x2 = (-b - d) / (2. * a); /* Display output */ printf("nx1 = %12.3e x2 = %12.3en", x1, x2); }
  • 29. Programming Methodology & Abstractions 29 Example: Quadratic Equation  The standard library function call exit(1) (header file: stdlib.h) causes the program to abort with an error status.  Execution of the above program for the case of complex roots yields the following output: a = 4 b = 2 c = 6 Error: roots are complex %
  • 30. Programming Methodology & Abstractions 30 Example: Quadratic Equation /* Perform calculation */ e = b * b - 4. * a * c; if (e > 0.) // Test for real roots { /* Case of real roots */ d = sqrt(e); x1 = (-b + d) / (2. * a); x2 = (-b - d) / (2. * a); printf("nx1 = %12.3e x2 = %12.3en", x1, x2); } else { /* Case of complex roots */ d = sqrt(-e); x1 = -b / (2 * a); x2 = d / (2 * a); printf("nx1 = (%12.3e, %12.3e) nx2 = (%12.3e, %12.3e)n", x1, x2, x1, -x2); }
  • 31. Programming Methodology & Abstractions 31 Example: Quadratic Equation  The output from the above program for the case of complex roots looks like: a = 9 b = 2 c = 2 x1 = ( -1.111e-01, 4.581e-01) x2 = ( -1.111e-01, -4.581e-01)