Program Control: Selection Subject: T0016 – ALGORITHM AND PROGRAMMING Year: 2013.

Slides:



Advertisements
Similar presentations
Control Statements. Define the way of flow in which the program statements should take place. Control Statements Implement decisions and repetitions.
Advertisements

Decisions If statements in C.
Making Choices in C if/else statement logical operators break and continue statements switch statement the conditional operator.
True or false A variable of type char can hold the value 301. ( F )
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 4 – C Program Control Outline 4.1Introduction.
C++ for Engineers and Scientists Third Edition
Slides prepared by Rose Williams, Binghamton University Chapter 3 Flow of Control if-else and switch statements.
Engineering H192 - Computer Programming The Ohio State University Gateway Engineering Education Coalition Lect 9P. 1Winter Quarter Switch Case Structures.
12-2 Know how if and switch C statements control the sequence of execution of statements. Be able to use relational and logical operators in the conditional.
Fundamentals of Python: From First Programs Through Data Structures
The University of Texas – Pan American
Fundamentals of Python: First Programs
EGR 2261 Unit 4 Control Structures I: Selection  Read Malik, Chapter 4.  Homework #4 and Lab #4 due next week.  Quiz next week.
Algorithms and Computing Lecture 3 Control Statements By Dr. M. Tahir Khaleeq.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Structural Program Development: If, If-Else Outline.
1 Chapter 4: Selection Structures. In this chapter, you will learn about: – Selection criteria – The if-else statement – Nested if statements – The switch.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational operators – Discover.
Control Structures – Selection Chapter 4 2 Chapter Topics  Control Structures  Relational Operators  Logical (Boolean) Operators  Logical Expressions.
More on Input Output Input Stream : A sequence of characters from an input device (like the keyboard) to the computer (the program running). Output Stream.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
Summary of what we learned yesterday Basics of C++ Format of a program Syntax of literals, keywords, symbols, variables Simple data types and arithmetic.
UniMAP Sem1-07/08EKT120: Computer Programming1 Week2.
Flow of Control Part 1: Selection
Constants Numeric Constants Integer Constants Floating Point Constants Character Constants Expressions Arithmetic Operators Assignment Operators Relational.
Lecture 2: Logical Problems with Choices. Problem Solving Before writing a program Have a thorough understanding of the problem Carefully plan an approach.
A First Book of ANSI C Fourth Edition Chapter 4 Selection.
1 Example: Solution of Quadratic Equations We want to solve for real values of x, for given values of a, b, and c. The value of x can be determined from.
Programming C for Engineers An exercise is posted on the web site! Due in one week Single submission.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Selection Statements Selection Switch Conditional.
Chapter 3 - Structured Program Development Outline 3.1Introduction 3.2Algorithms 3.3Pseudocode 3.4Control Structures 3.5The If Selection Structure 3.6The.
Control Statements in C 1.Decision making statements 2.Looping statements 3.Branching statements
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
CCSA 221 Programming in C CHAPTER 6 MAKING DECISIONS 1.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 4 Making Decisions.
1 CS161 Introduction to Computer Science Topic #8.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
Week 4 Program Control Structure
IT CS 200: C ONDITION Lect. Napat Amphaiphan. T HE ABILITY TO CONTROL THE FLOW OF YOUR PROGRAM, LETTING IT MAKE DECISIONS ON WHAT CODE TO EXECUTE 2.
 Control Flow statements ◦ Selection statements ◦ Iteration statements ◦ Jump statements.
CSCI 171 Presentation 3. Operators Instructs C to perform some operation Assignment = Mathematical Relational Logical.
Control Flow Statements
UNIMAP Sem2-07/08EKT120: Computer Programming1 Week 2 – Introduction to Programming.
Making Decisions in c. 1.if statement Imagine that you could translate a statement such as “If it is not raining, then I will go swimming” into the C.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
Computer Science: A Structured Programming Approach Using C1 Objectives ❏ To understand how decisions are made in a computer ❏ To understand the logical.
Introduction to C Programming I Subject: T0016 – ALGORITHM AND PROGRAMMING Year: 2013.
Program Control: Selection Subject: T0016 – ALGORITHM AND PROGRAMMING Year: 2013.
Selection (if-then-else) Programming Has 3 Types of Control: Sequential (normal): Control of Execution Proceeds One after the Other Selection (if-then-else):
C++ for Engineers and Scientists Second Edition Chapter 4 Selection Structures.
BY ILTAF MEHDI(MCS,MCSE, CCNA) 1. INSTRUCTOR: ILTAF MEHDI (MCS, MCSE, CCNA, Web Developer) BY ILTAF MEHDI(MCS,MCSE, CCNA) 2 Programming Fundamentals Chapter.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational operators – Discover.
CSE1301 Sem Selection Lecture 25 Lecture 9: Selection.
Chapter 4 – C Program Control
CNG 140 C Programming (Lecture set 3)
The if…else Selection Statement
More on the Selection Structure
EKT120 COMPUTER PROGRAMMING
Decisions Chapter 4.
The Selection Structure
BY GAWARE S.R. COMPUTER SCI. DEPARTMENT
Control Structures – Selection
Lecture 2: Logical Problems with Choices
Chapter 4: Control Structures I (Selection)
Structured Program
Summary of what we learned yesterday
Controlling Program Flow
Switch Case Structures
Structural Program Development: If, If-Else
Presentation transcript:

Program Control: Selection Subject: T0016 – ALGORITHM AND PROGRAMMING Year: 2013

3 Learning Outcomes At the end of this session, student will be able to: Demonstrate usage of selection control in C programming language (LO2 & LO3) T Algorithm and Programming

4 Sub Topics Program Control – Selection: –Selection Definition –If –If-Else –Nested If –Program Examples Using If –Switch-Case –?: Operator –Error Type –Program Examples Using Switch-Case –Program Examples Using ?: –Exercise T Algorithm and Programming

5 Selection Definition  In an algorithm implementation, an instruction or block of instructions may be executed (or not) with certain predetermined condition  Syntax: –if –if-else –switch-case T Algorithm and Programming

6 Selection: IF Syntax : if (boolean expression) statement; or if (boolean expression) { statement1; statement2; Block of statements …… } If boolean expression resulting in True, then a statement or some statements will be executed. T Algorithm and Programming

7 Selection: IF  Flow Chart of IF Statement T Algorithm and Programming true false statements condition

8 Selection: IF-ELSE Syntax : if (boolean expression) statement1; else statement2; or if (boolean expression){ statement1; statement2; Block statement1 …… } else { statement3; statement4; Block statement2 … } T Algorithm and Programming If boolean expression resulting in TRUE, then statement1 or block statement1 will be executed, if FALSE then statement2 or block statement2 be executed.

9 Selection: IF-ELSE  Flow Chart of IF-ELSE Statement T Algorithm and Programming true false statements 1 condition statements 2

10 Selection: NESTED-IF Nested selection occurs when the word IF appears more than once within IF statement. Syntax : if (boolean expression) statement1; if (boolean expression) statement2; if (boolean expression) statement3; or if (boolean expression) statement1; else if (boolean expression) statement2; else if (boolean expression) statement3; T Algorithm and Programming

11 Program Examples Using IF Example 1: Program example to find the roots of a quadratic equation Algorithm : 1. Get the value of coefficients a, b, and c from keyboard 2. Calculate discriminant d = b*b – 4*a*c 3. if d >= 0 then calculate x1 and x2 if d < 0 then stated imaginer, stop. 4. Stop calculate x1 using : calculate x2 using : T Algorithm and Programming -b +  d 2*a -b -  d 2*a

12 Program Examples Using IF T Algorithm and Programming #include int main() { float a,b,c,d,x1,x2; printf(“ Input coef. a : “); scanf(“%f”,&a); printf(“ Input coef. b : “); scanf(“%f”,&b); printf(” Input coef. c : ”); scanf(“%f”,&c); d = b*b - 4 * a * c; if (d >= 0){ x1 = (-b + sqrt(d)) / (2 * a); x2 = (-b - sqrt(d)) / (2 * a); printf(“x1=%f\n x2=%f\n”,x1,x2); } else printf(” Imaginer root equation”); return 0; } sqrt() is a function used to calculate root from a number, and it is defined on library

13 Program Examples Using IF Standard Library Function : sqrt() –The previous slide shows program example using sqrt() function –Syntax : double sqrt (double x); –Header file –To find a square root for a value x, where x is non-negative –Example: z = sqrt(45.35); then value of z is 6.73 T Algorithm and Programming

14 Program Examples Using IF-ELSE Example 2: (Calculator Program) T Algorithm and Programming #include int main() { float val1, val2; char op; while(1) { printf(“\n Type val1 operator val2, (example: 3 * 4) \n”); scanf(“%f %c %f”, &val1, &op, &val2); if(op == ‘+’) printf(“ = %f”, val1 + val2); else if(op == ‘-’) printf(“ = %f”, val1 - val2); else if(op == ‘*’) printf(“ = %f”, val1 * val2); else if(op== ‘/’) printf(“ = %f”, val1 / val2); else{ printf(“ error: choose operator +,-,* and / \n”); break; } return 0; }

15 Program Examples Using IF-ELSE Example 3: Wrong IF (unclear IF statement) T Algorithm and Programming #include int main() { int degree: printf(“Input degree: “); scanf(“%d”, &degree); if (degree < 80) if (degree > 30) printf (“Hot\n”); else printf (“Cool\n”); }

16 Selection: SWITCH-CASE Switch-Case Operation This statement is used in exchange of IF-ELSE, when if-else nested number of level is enormous and difficult to read Syntax: switch (expression) { case constant1 : statements1; break;. case constant2 : statements2; break; default : statements; } T Algorithm and Programming

17 Selection: SWITCH-CASE Switch statement evaluate an expression by looking up for each case constant value. If an expression value matches with a case constant value then related statement/s is executed. If nothing match then default statement is executed. Note: Expression and constant type should be integer (including char) T Algorithm and Programming

18 Selection: SWITCH-CASE  Flow Chart of SWITCH-CASE Statement T Algorithm and Programming true false case a case a action(s) break case b case b action(s)break false case z case z action(s)break true default action(s)

19 Program Examples Using SWITCH-CASE  Example: T Algorithm and Programming #include int main() { float val1, val2; char op; while(1) { printf(“\n Type val1 operator val2 \n”); scanf(“%f %c %f”, &val1, &op, &val2); switch(op){ case(‘+’): printf(“ = %f”, val1 + val2); break; case(‘-’) : printf(“ = %f”, val1 - val2); break; case(‘*’) : printf(“ = %f”, val1 * val2); break; case(‘/’) : printf(“ = %f”, val1 / val2); break; default : printf(“ unknown operator!”); } return(0); } Note: case (’+’) can also written case ’+’

20 ?: Operator The operator ? : is similar to the IF statement, but it returns a value Syntax: condition ? then-expression : else-expression Using this operator, you can rewrite if(a > b) max_value = a; else max_value = b; as max_value = (a > b) ? a : b; T Algorithm and Programming

21 Program Examples Program Example: (Exam Grading System) Grading table Algorithm and Programming subject comes with laboratory class; thus the final score calculation is: –Class score = 50%(final) + 30%(mid term) + 20%(assignment) –Lab. score = 40%(final) + 30%(mid term) + 30%(assignment) –Final score = 0.8* Class + 0.2* Lab T Algorithm and Programming ScoreWeightGrade A : high distinction 75 – 843B : distinction 65 – 742C : pass 50 – 641D : conceded pass E : fail

22 Program Examples T Algorithm and Programming /* Exam Grading Program */ #include int assignClass, assignLab; int midClass, midLab, finalScore; int finalClass, finalLab; float scoreClass, scoreLab; char answer;

23 Program Examples T Algorithm and Programming int main() { clrscr(); printf(” Continue [Y/T] ? ”); scanf(“%c”,&answer); while (toupper(answer) == ’Y’) { printf(” Assign class (0 -100) : ”); scanf(“%d”,&assignClass); printf(” Assign lab (0 -100) : ”); scanf(“%d”,&assignLab); printf(” mid class (0 -100) : ”); scanf(”%d”,&midClass); printf(“ mid lab (0 -100) : ”); scanf(”%d”,&midLab); printf(“ fin class (0 -100) : “); scanf(“%d”,&finalClass); printf(“ fin class (0 -100) : “); scanf(“%d”,&finalLab); scoreClass = 0.2*assignClass+0.3*midClass + 0.5*finalClass; scoreLab = 0.3*assignLab + 0.3*midLab + 0.4*finalLab; finalScore = ceil(0.8*scoreClass + 0.2*scoreLab); if(finalScore >=85) printf(“finalScore = A”); else if(finalScore >=75) printf(“finalScore = B”); else if(finalScore >=65) printf(“finalScore = C”); else if(finalScore >=50) printf(“finalScore = D”); else printf(“finalScore = E”); printf(“\n”); printf(“Continue[Y/T] ? “); scanf(“%c”,&answer); }

24 Program Examples Example on previous slide using: –clrscr() clear screen Header file: –toupper() syntax: int toupper(int c); converting char c to capital letter Header file: and T Algorithm and Programming

25 Go To and Label C is still providing the old fashion goto statement Syntax: goto label; …… label : …… label is written using colon symbol Avoid using goto to improve code readability T Algorithm and Programming

26 Error Type Compile-Time Error –caused by syntax error Link-Time Error –success fully compiled, but cause link error –caused by no object code at link time Run-Time Error –successfully compiled, but error at runtime. Usually caused by numerical operation such as: overflow, floating point underflow, division by zero, etc. Logical Error –wrong result caused by incorrect logical flow/algorithm T Algorithm and Programming

27 Error Type Among those Error Types the most difficult to debug is Logical Error. Example of Compile-Time Error: T Algorithm and Programming Dev-C compiler will give message: In function main missing terminating ” character, syntax error before return

28 Error Type Some C compiler merge the compile and link processes, causing in difficulty to distinguish between Compile- Time Error with Link-Time Error Example of Link-Time Error (Visual C++) T Algorithm and Programming

29 Error Type Example for Run-Time Error T Algorithm and Programming successfully compiled and linked, but RUN result, causing by overflow (char range max 127)

30 Error Type Example for Run-Time Error T Algorithm and Programming Error cause: Division by Zero

31 Error Type Example for Logical-Error T Algorithm and Programming Should be: x1 = 5.00 and x2 = 2.00 Can you find the logic error ??

32 Exercise T Algorithm and Programming #include int main() { int n; for(; ;) { printf(“\n Enter integer : “); scanf(“%d “, &n); if((n%2) == 0) continue; else if((n%3) == 0) break; printf(“\n\t Bottom of loop.”); } print(“\n\t Outside of loop.”); } What are the output if 7, 4 and 9 entered consecutively?

33 Exercise 2.Create a program to input value of student’s IPK (cumulative performance index) and state the grading:  Cumlaude  Outstanding 2.5 – 2.9  Very Good 2.0 – 2.4  Good less than 2.0  Poor Use IF or IF-ELSE T Algorithm and Programming

34 Exercise 3.Given the following code: Explain which “if” keyword does the else is pairing with ? Fix the code to improve readability! T Algorithm and Programming if(n > 0) if(a > b) z = a; else z = b;

35 Summary  In an algorithm implementation, an instruction or block of instructions may be executed (or not) with certain predetermined condition, that’s why we use selection  3 types of selection in C: –if –if-else –switch-case T Algorithm and Programming

36 References Paul J. Dietel,Harvey M. Deitel, C : how to program. PEAPH. New Jersey. ISBN: Chapter 3 & 4 Choosing between Alternatives: Getting Controls: T Algorithm and Programming

37 END T Algorithm and Programming