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

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 Decisions in C or If condition

Cs1123 5 selection_if
Cs1123 5 selection_ifCs1123 5 selection_if
Cs1123 5 selection_if
TAlha MAlik
 
CONTROLSTRUCTURES.ppt
CONTROLSTRUCTURES.pptCONTROLSTRUCTURES.ppt
CONTROLSTRUCTURES.ppt
Sanjjaayyy
 
Operators in c language
Operators in c languageOperators in c language
Operators in c language
Amit Singh
 

Similar to Decisions in C or If condition (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 (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

%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
masabamasaba
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
masabamasaba
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
masabamasaba
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
masabamasaba
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
masabamasaba
 

Recently uploaded (20)

%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
Harnessing ChatGPT - Elevating Productivity in Today's Agile Environment
Harnessing ChatGPT  - Elevating Productivity in Today's Agile EnvironmentHarnessing ChatGPT  - Elevating Productivity in Today's Agile Environment
Harnessing ChatGPT - Elevating Productivity in Today's Agile Environment
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 

Decisions in C or If condition

  • 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)