6.1 Branching (or Selection)

Similar documents
Sources: On the Web: Slides will be available on:

Outline. Conditional Statements. Logical Data in C. Logical Expressions. Relational Examples. Relational Operators

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Chapter 5. Selection 5-1

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

Senem Kumova Metin & Ilker Korkmaz 1

Chapter 8 Selection 8-1

The C Programming Language

Conditionals (with solutions)

Selection Statements

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

9 Control Statements. 9.1 Introduction. 9.2 Objectives. 9.3 Statements

ASCII Encoding. The char Type. Manipulating Characters. Manipulating Characters

Two-way selection. Branching and Looping

C Programming. Charudatt Kadolkar. IIT Guwahati. C Programming p.1/34

13 Classes & Objects with Constructors/Destructors

Informatica e Sistemi in Tempo Reale

arrays C Programming Language - Arrays

Chapter One Introduction to Programming

Phys4051: C Lecture 2 & 3. Comment Statements. C Data Types. Functions (Review) Comment Statements Variables & Operators Branching Instructions

Lecture 2 Notes: Flow of Control

Student Exploration: Circuits

Module 816. File Management in C. M. Campbell 1993 Deakin University

JavaScript: Control Statements I

About The Tutorial. Audience. Prerequisites. Copyright & Disclaimer

AP Physics Electricity and Magnetism #4 Electrical Circuits, Kirchoff s Rules

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

Tristan s Guide to: Solving Series Circuits. Version: 1.0 Written in Written By: Tristan Miller Tristan@CatherineNorth.com

Computer Science 2nd Year Solved Exercise. Programs 3/4/2013. Aumir Shabbir Pakistan School & College Muscat. Important. Chapter # 3.

CP Lab 2: Writing programs for simple arithmetic problems

Conditions & Boolean Expressions

3/13/2012. Writing Simple C Programs. ESc101: Decision making using if-else and switch statements. Writing Simple C Programs

CS 241 Data Organization Coding Standards

Writing Control Structures

The C Programming Language course syllabus associate level

Computer Programming Tutorial

Introduction to Lex. General Description Input file Output file How matching is done Regular expressions Local names Using Lex

Dr. Estell s C Programs and Examples

6. Control Structures

Tutorial on C Language Programming

Boolean Expressions 1. In C++, the number 0 (zero) is considered to be false, all other numbers are true.

Gates, Circuits, and Boolean Algebra

Microcontroller Systems. ELET 3232 Topic 8: Slot Machine Example

Experiment NO.3 Series and parallel connection

So far we have considered only numeric processing, i.e. processing of numeric data represented

Conditional Statements Summer 2010 Margaret Reid-Miller

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

Introduction to Python

Introduction to Java

Object Oriented Software Design

Chapter 2: Elements of Java

University of Toronto Department of Electrical and Computer Engineering. Midterm Examination. CSC467 Compilers and Interpreters Fall Semester, 2005

C / C++ and Unix Programming. Materials adapted from Dan Hood and Dianna Xu

QUIZ-II QUIZ-II. Chapter 5: Control Structures II (Repetition) Objectives. Objectives (cont d.) 20/11/2015. EEE 117 Computer Programming Fall

Object Oriented Software Design

Visual Logic Instructions and Assignments

J a v a Quiz (Unit 3, Test 0 Practice)

Performing Simple Calculations Using the Status Bar

Digital System Design Prof. D Roychoudhry Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Programming in C an introduction

PROGRAMMING IN C PROGRAMMING IN C CONTENT AT A GLANCE

FEEG Applied Programming 5 - Tutorial Session

W03 Analysis of DC Circuits. Yrd. Doç. Dr. Aytaç Gören

Parallel DC circuits

MATLAB Programming. Problem 1: Sequential

Tristan s Guide to: Solving Parallel Circuits. Version: 1.0 Written in Written By: Tristan Miller Tristan@CatherineNorth.com

Circuit Analysis using the Node and Mesh Methods

CS1010 Programming Methodology A beginning in problem solving in Computer Science. Aaron Tan 20 July 2015

Series and Parallel Circuits

Cornerstone Electronics Technology and Robotics I Week 15 Combination Circuits (Series-Parallel Circuits)

Chapter 5. Parallel Circuits ISU EE. C.Y. Lee

TECH TIP # 37 SOLVING SERIES/PARALLEL CIRCUITS THREE LAWS --- SERIES CIRCUITS LAW # THE SAME CURRENT FLOWS THROUGH ALL PARTS OF THE CIRCUIT

1Meg. 11.A. Resistive Circuit Nodal Analysis

Why using ATmega16? University of Wollongong Australia. 7.1 Overview of ATmega16. Overview of ATmega16

(hours worked,rateofpay, and regular and over time pay) for a list of employees. We have

We will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share.

Keywords: Dynamic pricing, Hotel room forecasting, Monte Carlo simulation, Price Elasticity, Revenue Management System

The design recipe. Programs as communication. Some goals for software design. Readings: HtDP, sections 1-5

T-SQL STANDARD ELEMENTS

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Variables, Constants, and Data Types

Statements and Control Flow

Example of a Java program

Introduction to Computer Programming, Spring Term 2014 Practice Assignment 3 Discussion

PHYSICS 111 LABORATORY Experiment #3 Current, Voltage and Resistance in Series and Parallel Circuits

SOME EXCEL FORMULAS AND FUNCTIONS

Java Basics: Data Types, Variables, and Loops

CS1020 Data Structures and Algorithms I Lecture Note #1. Introduction to Java

Numeral Systems. The number twenty-five can be represented in many ways: Decimal system (base 10): 25 Roman numerals:

Fig. 1 Analogue Multimeter Fig.2 Digital Multimeter

Fundamentals of Programming

C PROGRAMMING FOR MATHEMATICAL COMPUTING

1.00/ Session 2 Fall Basic Java Data Types, Control Structures. Java Data Types. 8 primitive or built-in data types

Decision Logic: if, if else, switch, Boolean conditions and variables

13.10: How Series and Parallel Circuits Differ pg. 571

My EA Builder 1.1 User Guide

Experiment: Series and Parallel Circuits

Transcription:

Chapter 6 Branching 6.1 Branching (or Selection) 6.2 Relational and Logical Operators 6.3 The if Statement 6.4 The if-else Statement 6.5 The if-else if-else Statement 6.6 The Nested-if Statement 6.7 The switch Statement 6.8 The Conditional Operator

6.1 Branching (or Selection) Decision Decision Decision!!!! C statements are executed normally. Sometimes we need to tell the computer to do something only when some conditions are satisfied. This will alter the normal sequential execution. The if statement serves this purpose. Three forms: if statement if... else statement if... else if... else statement The switch statement provides a multi-way decision structure. We can choose one action out of a number of actions depending on some conditions.

6.2 Relational and Logical Operators Used for comparison between two values. Return boolean result: true or false. Relational Operators: operator example meaning == ch == a equal to!= f!= 0.0 not equal to < num < 10 less than <= num <=10 less than or equal to > f > -5.0 greater than >= f >= 0.0 greater than or equal to

Logical operators: Work on one or more relational expressions to yield a logical value: true or false. Allows testing results of comparison of expressions. operator example meaning!!(num < 0) not && (num1 > num2) && (num2 >num3) and (ch == \t ) (ch == ) or! returns true when the operand is false and returns false when the operand is true. && returns true when both operands are true otherwise it returns false. returns false when both operands are false otherwise it returns true.

list of operators of decreasing precedence:! not * / multiply and divide + - add and subtract < <= > >= less, less or equal, greater, greater or equal ==!= equal, not equal && logical and logical or The result of evaluating an expression involving relational and/or logical operators is either 1 or 0. When the result is true, it is 1. Otherwise it is 0, i.e. C uses 0 to represent a false condition.

/* example of the value of relational & logical expressions */ #include <stdio.h> main(void) { float logic_value; /* Numeric value of relational and logical expression */ printf("logic values of the following relations:\n"); logic_value = (3 > 5); printf("(3 > 5) is %f\n", logic_value); logic_value = (3 <= 5); printf("(3 <= 5) is %f\n", logic_value); logic_value = (15!= 3*5); printf("(15!= 3*5) is %f\n", logic_value); logic_value = (10 < 5) && (24 <= 15); printf("(10 < 5) && (24 <=15) is %f\n", logic_value);

} /* notice the portion: 24/0!!! */ logic_value = (10 < 5) && (24/0 <= 15); printf("(10 < 5) && (24/0 <=15) is %f\n", logic_value); logic_value = (36/6 > 2*3) (8 == 8); printf("(36/6 > 2*3) (8 == 8) is %f\n", logic_value); /* 36/0 == 0??? what s going on??? */ logic_value = (8 == 8) (36/0 == 0); printf("(8 == 8) (36/0 == 0) is %f\n", logic_value); $ex6_1 Logic values of the following relations: (3 > 5) is 0.000000 (3 <= 5) is 1.000000 (15!= 3*5) is 0.000000 (10 < 5) && (24 <=15) is 0.000000 (10 < 5) && (24/0 <=15) is 0.000000 (36/6 > 2*3) (8 == 8) is 1.000000 (8 == 8) (36/0 == 0) is 1.000000 $

In general, any integer expression whose value is non-zero is considered true; else it is false. For example: 3 is true, 0 is false 1 && 0 is false 1 0 is true!(5 >= 3) (1) is true scanf(...) returns the number of items read. It returns the value EOF, i.e. -1, when end of input is encountered. For example, scanf( %d %d, &n1, &n2); returns 2 if there is no error in the process of input

Flowcharts (from Chapter 2) Symbol Name Process Decision Input/Output Terminal Flowlines

6.3 The if Statement The format of the if statement: if (expression) statement; false expression true statement statement may be a single statement terminated by a semicolon or a compound statement enclosed by { }

#include <stdio.h> main(void) /* example of simple if statement */ { int num; /* Value supplied by user. */ printf("give me a number from 1 to 10 => "); scanf("%d",&num); if (num > 5) printf("your number is larger than 5.\n"); printf("%d was the number you entered.\n",num); return 0; } $./ex6_2 Give me a number from 1 to 10 => 3 3 was the number you entered. $./ex6_2 Give me a number from 1 to 10 => 7 Your number is larger than 5. 7 was the number you entered. $

6.4 The if-else Statement The format of the if... else statement is if (expression) statement1; else statement2; false true expression statement_2 statement_1 Both statement1 and statement2 may be single statements terminated by a semicolon or a compound statement enclosed by { }

/* This program computes the maximum of num1, num2 */ main(void) { int num1, num2, max; printf("enter two integers:"); scanf("%d %d", &num1, &num2); if (num1 > num2) max = num1; else max = num2; printf("the maximum is %d\n", max); } return 0; Start Read num1, num2 true false num1>num2? max=num1 max=num2 Print max End $./ex6_3 Enter two integers: 9 4 The maximum is 9 $ $./ex6_3 Enter two integers: -2 0 The maximum is 0 $

6.5 The if-else if-else Statement The format is if (expression1) statement1; else if (expression2) statement2; else statement3; true false expression1 true false statement1 expression2 statement2 statement3 Each of statement1, statement2 and statement3 may be a single statement terminated by a semicolon or a compound statement enclosed by { }

We may have as many else if in the if statement as we want (within the compiler limit): if (expression1) statement1; else if (expression2) statement2; else if (expression3) statement3;... else statementn; Statement i is executed when the first i-1 expressions are false and the ith expression is true.

/* an example of if... else if... else statements */ #include <stdio.h> main(void) { float temp; /* Temperature reading. */ printf("give me the temperature reading: "); scanf("%f",&temp); if ((temp >= 100.0) && ( temp <= 120.0)) printf("temperature OK, continue process.\n"); else if (temp < 100.0) printf("temperature too low, increase energy.\n"); else printf("temperature too high, decrease energy.\n"); return 0; } $./ex6_4 Give me the temperature reading: 105.0 Temperature OK, continue process. $./ex6_4 Give me the temperature reading: 130.0 Temperature too high, decrease energy.

The if-else if-else Statement Start if (mark <= 100 && mark >= 80) Read mark grade = 'A'; else if (mark < 80 && mark >= 70) T mark<=100 && mark>=80? F grade = 'B'; else if (mark < 70 && mark >= 60) grade = 'C'; grade='a' T mark<80 && mark>=70? F else grade = 'F'; grade='b' T mark<70 && mark>=60? F grade='c' grade='f' Print grade End

6.6 Nested-if Both the if branch and the else branch may contain if statement(s). The level of nested if statements can be as many as we want (up to the compiler limit). E.g. if (expression1) statement1; else if (expression2) else statement2; statement3; true statement1 expression1 true statement2 false expression2 false statement3

if (expression1) else if (expression2) statement1; else statement2; statement3; Nested true false expression1 true false expression2 statement3 statement1 statement2

Rule -> C compiler associates an else part with the nearest unresolved if. if (expression1) if (expression2) statement1; else statement2; statement1 - is executed when expression1 and expression2 are true. statement2 - is executed when expression1 is true and expression2 is false. When expression1 is false - neither statements are executed.

Example: Nested-if statements /* This program computes the maximum value of three numbers */ main(void) { int n1, n2, n3, max; printf("please enter three integers:"); Start scanf("%d %d %d", &n1, &n2, &n3); Read n1, n2, n3 if (n1 >= n2) true false if (n1 >= n3) n1>=n2 max = n1;? true false true else max = n3; n1>=n3 n2>=n3 else if (n2 >= n3)?? max = n2; max=n1 max=n3 max=n2 else max = n3; printf("the maximum of the three is %d\n", max); return 0; Print max } End false max=n3

$./ex6_5 Please enter three integers: 1 2 3 The maximum of the three is 3 $./ex6_5 Please enter three integers: 1 3 2 The maximum of the three is 3 $./ex6_5 Please enter three integers: 3 1 2 The maximum of the three is 3 $./ex6_5 Please enter three integers: 2 1 3 The maximum of the three is 3 $

6.7 The switch Statement switch (expression) { } case constant1: statement1; break; case constant2: statement2; break; case constantn: statementn; break; default: The syntax of a switch statement is statementd; expression constant1? true statement1 break false constant2? true statement2 break false constant3? true statement3 break false statementd

switch, case, break and default are reserved words. the result of expression in ( ) must be integral type constant1, constant2,... are called labels. Each must be an integer constant, a character constant or an integer constant expression, e.g. 3, 'A', 4+'b', 5+7,... etc. each of the labels constant1, constant2,... must deliver unique integer value. Duplicates are not allowed.

#include <stdio.h> main(void) { Example ex6_6.c - Using Switch statement char selection; /* Item to be selected by the user */ printf("select the form of Ohm's law needed by letter:\n"); printf("a] Voltage; B] Current; C] Resistance;\n"); printf("your selection (A, B, or C) => "); scanf("%c", &selection); switch (selection) { case 'A' : printf("v = I * R\n"); break; case 'B' : printf("i = V / R\n"); break; case 'C' : printf("r = V / I\n"); break; default : printf("that was not one of the proper selections.\n"); } /* End of switch. */ return 0; } Menu

$./ex6_6 Select the form of Ohm's law needed by letter: A] Voltage; B] Current; C] Resistance; Your selection (A, B, or C) => A V = I * R $./ex6_6... Your selection (A, B, or C) => B I = V / R $./ex6_6... Your selection (A, B, or C) => C R = V / I $./ex6_6... Your selection (A, B, or C) => D That was not one of the proper selections. $

#include <stdio.h> /* Menu-driven application */ main(void) { we may have multiple labels for a statement, for example, to allow both the lower and upper case selection in the previous example, we do this: char selection; /* Item to be selected by the user */ printf("select the form of Ohm's law needed by letter:\n"); printf("a] Voltage; B] Current; C] Resistance;\n"); printf("your selection (A, B, or C) => "); scanf("%c",&selection); switch (selection) { case a : case 'A' : printf("v = I * R\n"); break; case b : case 'B' : printf("i = V / R\n"); break; Menu

} case c : case 'C' : printf("r = V / I\n"); break; default : printf("that was not one of the \ proper selections.\n"); } /* End of switch. */ return 0; if we do not use break after some statements in the switch statement, execution will continue with the statements for the subsequent labels until a break statement or the end of switch statement. This is called fall through situation.

#include <stdio.h> main(void) { char selection; /* User input selection. */... printf("your selection => "); scanf("%c", &selection); switch(selection) { case 'A' : printf("rt = R1 + R2 + R3\n"); case 'B' : printf("it = Vt / Rt\n"); case 'C' : printf("pt = Vt * It\n"); break; default : printf("that was not a correct selection!"); } /* End of switch. */ return 0; }

$./ex6_7... Your selection => A /* fall through */ Rt = R1 + R2 + R3 It = Vt / Rt Pt = Vt * It $./ex6_7... Your selection => B /* fall through */ $./ex65_7... Your selection => C Pt = Vt * It $./ex6_7... Your selection => D That was not a correct selection! $ It = Vt / Rt Pt = Vt * It

Another Example: switch(choice) { case 'a': case 'A': result = num1 + num2; printf("%d + %d = %d\n", num1,num2,result); case 's': case 'S': result = num1 - num2; printf("%d - %d = %d\n", num1,num2,result); case 'm': case 'M': result = num1 * num2; printf("%d1 * %d = %d\n",num1,num2,result); break; default: printf("not the proper choices.\n"); }

Start Read choice, num1, num2 choice case 'A' or 'a'? true result=num1+num2 Print result false case 'S' or 's'? true result=num1-num2 false case 'M' or 'm'? true false Print error message Print result result=num1*num2 Print result break Start

6.8 The Conditional Operator The conditional operator is used in the following way: expression_1? expression_2 : expression_3 The value of this expression depends on whether expression_1 is true or false. If expression_1 is true, then the value of the expression is that of expression_2 otherwise it is expression_3.

Example ex6_8.c: conditional expressions #include <stdio.h> main(void) { float led_voltage; /* Voltage across LED (all in V) */ float resistor_voltage; /* Voltage across resistor */ float source_voltage; /* Voltage of source */ float circuit_current; /* Current in the LED (A) */ float resistor_value; /* Value of resistor in ohms */ printf("enter the source voltage in volts => "); scanf("%f", &source_voltage); printf("enter value of resistor in ohms => "); scanf("%f", &resistor_value); led_voltage = (source_voltage < 2.3)? source_voltage : 2.3;

resistor_voltage = source_voltage - led_voltage; circuit_current = resistor_voltage / resistor_value; printf("total circuit current is %f amperes.\n", circuit_current); } return 0; $./ex6_8 Enter the source voltage in volts => 2 Enter value of resistor in ohms => 50 Total circuit current is 0.000000 amperes. $./ex6_8 Enter the source voltage in volts => 5 Enter value of resistor in ohms => 27 Total circuit current is 0.100000 amperes. $

/* example ex6_9.c: a conditional expression */ #include <stdio.h> main(void) { int selection; /* User input selection */ printf("enter a 1 or a 0 => "); scanf("%d",&selection); selection? printf("a one.\n") : printf("a zero.\n"); } return 0; $./ex6_9 Enter a 1 or a 0 => 1 A one. $./ex6_9 Enter a 1 or a 0 => 0 A zero. $