Lecture 8. Daily Puzzle

Similar documents
Computer Programming. Decision Making (2) Loops

Chapter 5: Control Structures

There are algorithms, however, that need to execute statements in some other kind of ordering depending on certain conditions.

Lecture 10. Daily Puzzle

Chapter 4. Flow of Control

Flow of Control. Flow of control The order in which statements are executed. Transfer of control

V2 2/4/ Ch Programming in C. Flow of Control. Flow of Control. Flow of control The order in which statements are executed

BBM 101 Introduc/on to Programming I Fall 2013, Lecture 4

DECISION MAKING STATEMENTS

Control Structure: Selection

MODULE 2: Branching and Looping

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University

Programming for Electrical and Computer Engineers. Loops

Flow Control. CSC215 Lecture

Control Statements. If Statement if statement tests a particular condition

Problem Solving through Programming In C Prof. Anupam Basu Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur

Lecture 6. Statements

Chapter 6. Loops. Iteration Statements. C s iteration statements are used to set up loops.

Decision Making and Loops

Physics 2660: Fundamentals of Scientific Computing. Lecture 5 Instructor: Prof. Chris Neu

Decision Making -Branching. Class Incharge: S. Sasirekha

Lecture 5 Tao Wang 1

PDS Lab Section 16 Autumn Tutorial 3. C Programming Constructs

Conditional Statement

CpSc 1111 Lab 4 Part a Flow Control, Branching, and Formatting

DECISION CONTROL AND LOOPING STATEMENTS

Introduction to C Programming

COMP 208 Computers in Engineering

Conditions and Logical Expressions. C Programming

Note: unless otherwise stated, the questions are with reference to the C Programming Language. You may use extra sheets if need be.

Course Outline Introduction to C-Programming

Control structures in C. Going beyond sequential

More Flow Control Functions in C++ CS 16: Solving Problems with Computers I Lecture #4

Computer Programming: Skills & Concepts (CP) arithmetic, if and booleans (cont)

Computer Science & Engineering 150A Problem Solving Using Computers

Conditional Statement

Unit 3 Decision making, Looping and Arrays

INTRODUCTION TO C++ PROGRAM CONTROL. Dept. of Electronic Engineering, NCHU. Original slides are from

Note: If only one statement is to be followed by the if or else condition then there is no need of parenthesis.

Decision Making in C

CpSc 111 Lab 5 Conditional Statements, Loops, the Math Library, and Redirecting Input

AN OVERVIEW OF C, PART 3. CSE 130: Introduction to Programming in C Stony Brook University

CMSC 104 -Lecture 9 John Y. Park, adapted by C Grasso

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

5. Selection: If and Switch Controls

Introduction. C provides two styles of flow control:

Introduction to C. CS 2060 Week 1. Prof. Jonathan Ventura. Outline Introduction Introduction to C Homework 1 C Coding Style Wrap-up

Materials covered in this lecture are: A. Completing Ch. 2 Objectives: Example of 6 steps (RCMACT) for solving a problem.

SELECTION. (Chapter 2)

Statements. Control Flow Statements. Relational Operators. Logical Expressions. Relational Operators. Relational Operators 1/30/14

ECE 2400 Computer Systems Programming Fall 2018 Topic 1: Introduction to C

BITG 1223: Selection Control Structure by: ZARITA (FTMK) LECTURE 4 (Sem 1, 16/17)

CpSc 1111 Lab 6 Conditional Statements, Loops, the Math Library, and Random Numbers What s the Point?

More examples for Control statements

Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS240 BRANCHING STATEMENTS

BRANCHING if-else statements

Module 4: Decision-making and forming loops

Decisions. Arizona State University 1

Identify skills and personality traits of successful problem solving. Apply standard problem-solving techniques to aid in problem solving.

Programming Basics and Practice GEDB029 Decision Making, Branching and Looping. Prof. Dr. Mannan Saeed Muhammad bit.ly/gedb029

Laboratory 2: Programming Basics and Variables. Lecture notes: 1. A quick review of hello_comment.c 2. Some useful information

Theory of control structures

Computer Programming. Basic Control Flow - Decisions. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

C Language Part 2 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

Following is the general form of a typical decision making structure found in most of the programming languages:

CMSC 104 -Lecture 11 John Y. Park, adapted by C Grasso

Chapter 5. Repetition. Contents. Introduction. Three Types of Program Control. Two Types of Repetition. Three Syntax Structures for Looping in C++

Decision Making and Branching

Physics 2660: Fundamentals of Scientific Computing. Lecture 7 Instructor: Prof. Chris Neu

Example. CS 201 Selection Structures (2) and Repetition. Nested if Statements with More Than One Variable

Computer Science & Engineering 150A Problem Solving Using Computers

CpSc 1011 Lab 5 Conditional Statements, Loops, ASCII code, and Redirecting Input Characters and Hurricanes

Chapter 8. More Control Statements

Programming Lecture 4

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

CS 105 Lecture 5 Logical Operators; Switch Statement. Wed, Feb 16, 2011, 5:11 pm

COP 2000 Introduction to Computer Programming Mid-Term Exam Review

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Day05 A. Young W. Lim Sat. Young W. Lim Day05 A Sat 1 / 14

At the end of this lecture you should be able to have a basic overview of fundamental structures in C and be ready to go into details.

CS 221 Lecture. Tuesday, 4 October There are 10 kinds of people in this world: those who know how to count in binary, and those who don t.

Ch. 7: Control Structures

Chapter 17. Fundamental Concepts Expressed in JavaScript

Statements execute in sequence, one after the other, such as the following solution for a quadratic equation:

Lab - 8 Awk Programming

sends the formatted data to the standard output stream (stdout) int printf ( format_string, argument_1, argument_2,... ) ;

Administration. Conditional Statements. Agenda. Syntax. Flow of control. Lab 2 due now on floppy Lab 3 due tomorrow via FTP

Programming Language. Control Structures: Selection (switch) Eng. Anis Nazer First Semester

Floating-point lab deadline moved until Wednesday Today: characters, strings, scanf Characters, strings, scanf questions clicker questions

Chapter 3 Structured Program Development

Dr. R. Z. Khan, Associate Professor, Department of Computer Science

Subject: PROBLEM SOLVING THROUGH C Time: 3 Hours Max. Marks: 100

UIC. C Programming Primer. Bharathidasan University

Selection Structures II

Tail recursion. Decision. Assignment. Iteration

Chapter 6. Decision and Control Statements

Welcome to... CS113: Introduction to C

C: How to Program. Week /Mar/05

Lecture 5. Daily Puzzle. Variables and Identifiers. Place 10 lumps of sugar in 3 cups so there would be an odd number of lumps in every cup.

Dept. of CSE, IIT KGP

Transcription:

Lecture 8 if and switch Statements Daily Puzzle If a bottle, partly filled with liquid, has a round, square or rectangular bottom which is flat, can you find its volume using only a ruler? You may not add or pour out liquid.

Daily Puzzle Solution: area of base (h 1 +h 2 ) Announcements Assignment sheet error- no two player mode for mugwump Assignment hint sheets posted on website Assignment grading will be the week AFTER the due date - TAs do the grading (not instructors) - will be able to start booking times after the break Next week's labs are a practise lab exam - Monday and Tuesday people can go to other lab times or to extra lab times (will be posted)

Announcements Prof. McCuaig has several raspberry pi kits still and any student who needs one may purchase one today between 2:30 and 4:30 in her office (Reynolds 311) Q&A Do you have a question? (I may have an answer)

if statements What happens here? a = -12; if (a > 0) printf( a is positive\n ); b = log(a); if statements If a is greater than 0, it prints a is positive. It calculates the log of a regardless of the outcome of the if statement.

if statements To fix this, use a compound statement! a = -12; if (a > 0) { printf( a is positive\n ); b = log(a); if statements NOTE: No semicolons after the curly braces!

if-else statements No Is the condition true? Yes if-else statements The simplest possible if-else statement takes the form:! if (expression)!!! statement1;!!! else!!! statement2;

if-else statements statement1 is executed if expression has a nonzero value. If expression has a value of zero, the statement2 is executed. if-else example #include <stdio.h> int main(void) { int a_number; printf( Enter a number: ); scanf( %d, &a_number); if (a_number % 2 == 0) printf( %d is even\n, a_number); else printf( %d is odd\n, a_number); return 0;

if-else statements There are *many* different combinations: if (expression) if (expression){ statement1; statement1a; else { statement1b; statement2a; statement2b; else statement2; if-else statements For example:!! if (x < y)!! min = x;!! else!! min = y; If x < y is true, then min is assigned the value of x; if it is false, min is assigned the value of y.

if-else statements For example: if (denominator == 0.00)!! printf( Divide by zero );! else!! f = numerator/denominator; if-else statements If the value of the variable denominator is less than zero, an error message is printed otherwise the value of f is computed.

if-else statements /* Find the minimum of two values */ #include <stdio.h> int 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 %d\n, min); return 0; if-else statements An example of a syntax error:! if ( a!= b) {! a = a + 1;! b = b + 1;! ;! else! c = a + b;

if-else statements The syntax error occurs because the semicolon following the right brace creates an empty statement, and consequently the else has nowhere to attach! dangling else There is an ambiguity when an else is omitted from a nested if statement. This is the dangling else problem.! if (n > 0)! if (a > b)!! c = a;! else!! c = b;

dangling else For example consider a conditional statement to calculate shipping charges: 1. To ship a 1 lb packet within Canada, the cost is $5, except for Yukon. To ship to Yukon (which is very remote), the cost $10. 2. To ship a 1 lb packet outside Canada, the cost is $20 dangling else The following is an if-statement that computes the shippingcharge : double shippingcharge; shippingcharge = 5.00; if ( country == "CANADA") if ( province == "YT" ) shippingcharge = 10.00; else shippingcharge = 20.00;

dangling else Can be syntactically interpreted in two ways: double shippingcharge; shippingcharge = 5.00; if ( country == "CANADA") if ( province == "YT" ) shippingcharge = 10.00; else shippingcharge = 20.00; double shippingcharge; shippingcharge = 5.00; if ( country == "CANADA") if ( province == "YT" ) shippingcharge = 10.00; else shippingcharge = 20.00; = ambiguity dangling else C interprets it the following way: double shippingcharge; shippingcharge = 5.00; if ( country == "CANADA") if ( province == "YT" ) shippingcharge = 10.00; else shippingcharge = 20.00;

dangling else C associates the else with the closest previous else-less if. dangling else If that s not what you want, use braces to force the proper association.! if (n > 0) {! if (a > b)!! c = a;!! else!! c = b;

dangling else C interprets it the following way: double shippingcharge; shippingcharge = 5.00; if ( country == "CANADA") { if ( province == "YT" ) shippingcharge = 10.00; else shippingcharge = 20.00; dangling else /* Find the maximum of three real values */ #include <stdio.h> int main(void) { double x, y, z, max; printf( Input three real numbers: ); scanf( %lf%lf%lf, &x, &y, &z); if (x > y) if (x > z) max = x; else max = z; else if ( y < z) max = z; else max = y; printf( The maximum value is %f\n, max); return 0;

nested if 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 statement terminates the whole chain. nested if The last else can be used to handle the default case where none of the other conditions is satisfied.

nested if if (expression1) statement1; else if (expression2) statement2; else if (expression3) statement3;... else statementn; nested if int posn=0, negn=0, zeron=0; if (x > 0) posn = posn + 1; else if (x < 0) negn = negn + 1; else zeron = zeron + 1;

nested if if (score == 100) printf( Superb\n ); else if (score >= 90) printf( Excellent\n ); else if (score >= 80) printf( Very good\n ); else if (score >= 70) printf( Good\n ); else if (score >= 60) printf( Satisfactory\n ); else if (score >= 50) printf( Pass\n ); else printf( Fail\n ); what happens here? In mathematics the expression 2<k<7 means that k is greater than 2, and less than 7. int k = 8; if (2 < k < 7) printf( true ); else printf( false );

what happens here? true is always printed. Why? 2 < k < 7 is equivalent to (2 < k) < 7 Because 2 < k is true, its value is 1. Therefore 2 < k < 7 is equivalent to 1 < 7 Which is obviously true. what happens here? The correct way to write a test is: 2 < k && k < 7 which is equivalent to: ((2 < k) && (k < 7))

switch statements The switch statement is a multiway conditional statement generalizing the ifelse statement. It is a far neater way of writing multiple if statements. switch statements The switch statement evaluates the value of an expression and branches to one of the case labels. Duplicate labels are not allowed, so only one case will be selected. The expression must evaluate an integer, or character.

switch statements Is condition 1 true? no yes break Is condition 2 true? no yes break default switch statements switch (expression){ case label1: statement1; case label2: statement2;... case labeln: statementn; default: default_statement;

switch statements The case labels can be in any order and must be integers. switch statements How does it work? Evaluate a switch expression. Go to the case label having a value that matches the value of the expression found in step 1.

switch statements If a match is not found, go to the default label; if there is no default label, terminate the switch. Terminate the switch when a break is encountered or by falling off the end. default label The default label can be put anywhere in the switch. When C sees a switch statement, it evaluates the expression and then looks for a matching case label. If none is found, the default label is used.

default label There may be at most one default label in a switch. Typically, it occurs last although it can occur anywhere. break statement A break statement inside a switch means that execution will continue after the switch statement. If a break statement is not there, execution falls through to the next statement.

break statement switch (expression){ case label1: statement1; break; case label2: statement2; break;... case labeln: statementn; break; default: default_statement; break statement The break statement interrupts the normal flow of control. switch (x) { case 1: x = x + 1; case 2: x = x + 2; break; // exit switch statement case 3: x = x + 3; default: x = 0; // break jumps to here

falling through At the end of the first case, there is no break, so the program falls through. Therefore, when x=1, the following statements will be executed: x = x + 1;! x = x + 2; falling through End every case in a switch with a break or the comment //Fall through switch (x) { case 1: x = x + 1; // Fall through case 2: x = x + 2; break; // exit switch statement case 3: x = x + 3; // Fall through default: x = 0;

if switch int x, y, r; if (y == 1) r = x; else if (y == 2) r = x * x; else if (y == 3) r = x * x * x; else printf( not a valid calculation ); if switch int x, y, r; switch (y) { case 1 : r = x; break; case 2 : r = x * x; break; case 3 : r = x * x * x; break; default : printf( not a valid calculation );

not always switch 52 lines of case statements switch (score) { case 100 : printf( Superb\n ); break; case 99 : ; case 98 : ;... case 90 : printf( Excellent\n ); break;... case 59 : ; case 58 : ;... case 50 : printf( Pass\n ); break; default : printf( Fail\n ); Sometimes switch is not the most appropriate structure Case study: quadratic

Case study: quadratic Input: a, b, c will cause a divide by zero error true if a = 0? false calculate Case study: quadratic if (a == 0) printf( Error: DIV by zero\n"); else { A = 2 * a; D = b * b - 4 * a * c; S = sqrt(fabs(d));

Case study: quadratic Input: a, b, c true if a = 0? false calculate false if b = 0? true calculate trivial case no roots ➊ further processing 1 root Case study: quadratic if (a == 0) if (b == 0){ printf( Sorry, no roots\n"); else { x = -c / b; printf("linear equation: root = %.2f\n", x); else { A = 2 * a; D = b * b - 4 * a * c; S = sqrt(fabs(d)); // more calculations

Case study: quadratic if (a == 0) if (b == 0){ printf( Sorry, no roots\n"); else { x = -c / b; printf("linear equation: root = %.2f\n", x); else { A = 2 * a; D = b * b - 4 * a * c; S = sqrt(fabs(d)); // more calculations Case study: quadratic calculate calculate 2 complex roots true if D < 0? false calculate single real root true if D = 0? false calculate 2 real roots

Case study: quadratic if (a == 0) if (b == 0){ printf( Sorry, no roots\n"); else { x = -c / b; printf("linear equation: root = %.2f\n", x); else { A = 2 * a; D = b * b - 4 * a * c; S = sqrt(fabs(d)); if (D < 0){ // roots are complex if (D == 0){ // roots are real and equal if (D > 0){ // roots are real Case study: quadratic if (a == 0) if (b == 0){ printf( Sorry, no roots\n"); else { x = -c / b; printf("linear equation: root = %.2f\n", x); else { A = 2 * a; D = b * b - 4 * a * c; S = sqrt(fabs(d)); if (D < 0){ // roots are complex else if (D == 0){ // single real root else { // roots are real

Case study: quadratic if (D < 0){ xr = -b / A; xi = S / A; printf("complex roots: root1 = %.2f+%.2fi\n", xr, xi); printf(" root2 = %.2f-%.2fi\n", xr, xi); else if (D == 0){ x = -b / A; printf("single root = %.2f\n", x); else { x1 = (-b + S) / A; x2 = (-b + S) / A; printf("real roots: root1 = %.2f\n", x1); printf(" root2 = %.2f\n", x2);