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

Similar documents
Introduction to Programming

DECISION CONTROL AND LOOPING STATEMENTS

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

Introduction to C Programming

1.4 Control Structures: Selection. Department of CSE

Relational & Logical Operators, if and switch Statements

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

CPE 101, reusing/mod slides from a UW course (used by permission) Lecture 5: Input and Output (I/O)

CS102: Standard I/O. %<flag(s)><width><precision><size>conversion-code

Introduction to Computing Lecture 05: Selection (continued)

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

Other conditional and loop constructs. Fundamentals of Computer Science Keith Vertanen

Course Outline Introduction to C-Programming

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

C: How to Program. Week /Mar/05

Chapter 2 - Introduction to C Programming

Boolean Data-Type. Boolean Data Type (false, true) i.e. 3/6/2018. The type bool is also described as being an integer: bool bflag; bflag = true;

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

Recap. ANSI C Reserved Words C++ Multimedia Programming Lecture 2. Erwin M. Bakker Joachim Rijsdam

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

printf( Please enter another number: ); scanf( %d, &num2);

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

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

Laboratory 4. INSTRUCTIONS (part II) I. THEORETICAL BACKGROUND

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

COMP 208 Computers in Engineering

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

Variables in C. Variables in C. What Are Variables in C? CMSC 104, Fall 2012 John Y. Park

Decision Making -Branching. Class Incharge: S. Sasirekha

Introduction to C Programming. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan

Variables Data types Variable I/O. C introduction. Variables. Variables 1 / 14

C Programming. Lecture no. 2 More on Control Statements

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

BRANCHING if-else statements

Welcome! COMP s1. Programming Fundamentals

Welcome! COMP s1 Lecture 7. COMP s1. Before we begin. Strings. Programming Fundamentals. Overview. Andrew Bennett

These are reserved words of the C language. For example int, float, if, else, for, while etc.

Display Input and Output (I/O)

c) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance.

Data Types and Variables in C language

Overview of C, Part 2. CSE 130: Introduction to Programming in C Stony Brook University

WARM UP LESSONS BARE BASICS

CS 170 Section 3, Spring 2015 Programming in Java Midterm Exam 1. Name (print):

Arrays and Strings. Arash Rafiey. September 12, 2017

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

2008/11/05: Lecture 15 CMSC 104, Section 0101 John Y. Park

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

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

Programming for Engineers Introduction to C

Flow Control. CSC215 Lecture

Lecture 6. Statements

scanf erroneous input Computer Programming: Skills & Concepts (CP) Characters Last lecture scanf error-checking our input This lecture

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

Should you know scanf and printf?

C - Basic Introduction

Full file at C How to Program, 6/e Multiple Choice Test Bank

Chapter 5: Control Structures

The C Programming Language Part 2. (with material from Dr. Bin Ren, William & Mary Computer Science)

Administration. Exceptions. Leftovers. Agenda. When Things Go Wrong. Handling Errors. CS 99 Summer 2000 Michael Clarkson Lecture 11

Conditional Statement

Today s Learning Objectives

ESC101N: Fundamentals of Computing End-sem st semester

2. Numbers In, Numbers Out

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

1/25/2018. ECE 220: Computer Systems & Programming. Write Output Using printf. Use Backslash to Include Special ASCII Characters

CHAPTER 2.1 CONTROL STRUCTURES (SELECTION) Dr. Shady Yehia Elmashad

switch case Logic Syntax Basics Functionality Rules Nested switch switch case Comp Sci 1570 Introduction to C++

Programming - 1. Computer Science Department 011COMP-3 لغة البرمجة 1 لطالب كلية الحاسب اآللي ونظم المعلومات 011 عال- 3

A Fast Review of C Essentials Part I

Michele Van Dyne Museum 204B CSCI 136: Fundamentals of Computer Science II, Spring

Week 4 Selection Structures. UniMAP Sem II-11/12 DKT121 Basic Computer Programming 1

Tutorial 7. Number Colour Black Brown Red Orange Yellow Green Blue Violet Gray White

BLM2031 Structured Programming. Zeyneb KURT

CHRIST THE KING BOYS MATRIC HR. SEC. SCHOOL, KUMBAKONAM CHAPTER 9 C++

Topics. Chapter 5. Equality Operators

بسم اهلل الرمحن الرحيم

UNIT 4. CONTROL FLOW. Programming Year Grade in Industrial Technology Engineering. Paula de Toledo. David Griol

ITC213: STRUCTURED PROGRAMMING. Bhaskar Shrestha National College of Computer Studies Tribhuvan University

Fundamental of Programming (C)

Q1: Multiple choice / 20 Q2: C input/output; operators / 40 Q3: Conditional statements / 40 TOTAL SCORE / 100 EXTRA CREDIT / 10

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

Making Decisions. Agenda

An overview of Java, Data types and variables

Chapter 1 & 2 Introduction to C Language

Fundamentals of Programming

Fundamental of Programming (C)

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

CS349/SE382 A1 C Programming Tutorial

Lecture 14 CSE11 Fall 2013 For loops, Do While, Break, Continue

Comments. Comments: /* This is a comment */

.. Cal Poly CPE 101: Fundamentals of Computer Science I Alexander Dekhtyar..

Data Types. Data Types. Integer Types. Signed Integers

Preview from Notesale.co.uk Page 6 of 52

Fundamentals of Programming. Lecture 3: Introduction to C Programming

2. Numbers In, Numbers Out

Functions BCA-105. Few Facts About Functions:

C Programming Basics

CS 170 Section 3, Spring 2015 Programming in Java Midterm Exam 1. Name (print):

CS113: Lecture 7. Topics: The C Preprocessor. I/O, Streams, Files

Transcription:

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

Topics Multiple Selection vs Binary Selection switch Statement char data type and getchar( ) function Reading newline characters 2

So far, we have only seen binary selection. if ( age >= 18 ) { printf( Vote!\n ) ; if ( age >= 18 ) { printf( Vote!\n ) ; else { printf( Nope!\n ) ; 3

Sometimes it is necessary to branchin more than two directions. We do this using multiple selection. 4

if (day == 0 ) { printf ( Sunday ) ; if (day == 1 ) { printf ( Monday ) ; if (day == 2) { printf ( Tuesday ) ; if (day == 3) { printf ( Wednesday ); (continued) if (day == 4) { printf ( Thursday ) ; if (day == 5) { printf ( Friday ) ; if (day == 6) { printf ( Saturday ) ; if ((day < 0) (day > 6)) { printf( Invalid day.\n ); 5

if (day == 0 ) { printf ( Sunday ) ; else if (day == 1 ) { printf ( Monday ) ; else if (day == 2) { printf ( Tuesday ) ; else if (day == 3) { printf ( Wednesday ) ; else if (day == 4) { printf ( Thursday ) ; else if (day == 5) { printf ( Friday ) ; else if (day == 6) { printf ( Saturday ) ; else { printf ( Invalid day.\n ) ; Why is this if-else structure is more efficient than the corresponding if structure? 6

if (day == 0 ) { printf ( Sunday ) ; day = 3; if (day == 1 ) { printf ( Monday ) ; if (day == 2) { printf ( Tuesday ) ; if (day == 3) { printf ( Wednesday ) ; if (day == 4) { printf ( Thursday ) ; vs. if (day == 0 ) { printf ( Sunday ) ; day = 3; else if (day == 1 ) { printf ( Monday ) ; else if (day == 2) { printf ( Tuesday ) ; else if (day == 3) { printf ( Wednesday ) ; else if (day == 4) { printf ( Thursday ) ; 7

The multiple selection mechanism in C is the switch statement. Test a single integer variable against multiple different constant integer values Execute statements based on the success of each test. Will fall through and execute the statements in the next value unless told otherwise 8

switch( integer expression ) { case constant1: statement(s) break ; case constant2: statement(s) break;... default: statement(s) break; 9

The last statement of each casein the switch should almost always be a break. The breakcauses program control to jump to the closing brace of the switch structure. Without the break, the code flows into the next case. This is almost never what you want. A switch statement will compile without a defaultcase, but always consider using one. 10

Include a defaultcase to catch invalid data. Inform the user of the type of error that has occurred (e.g., Error -invalid day. ). If appropriate, display the invalid value. If appropriate, terminate program execution 11

Is this structure more efficient than the equivalent nested ifelse structure? switch ( day ) { case 0: printf ( Sunday\n ) ; break ; case 1: printf ( Monday\n ) ; break ; case 2: printf ( Tuesday\n ) ; break ; case 3: printf ( Wednesday\n ) ; break ; case 4: printf ( Thursday\n ) ; break ; case 5: printf ( Friday\n ) ; break ; case 6: printf ( Saturday\n ) ; break ; default: printf ( Invalid.\n ); break ; 12

A switch statement can be more efficient than an if-else. A switch statement may also be easier to read. Also, it is easier to add new cases to a switch statement than to a nested if-else structure. 13

The chardata type holds a single character. char ch; Example assignments: char grade, symbol; grade = B ; symbol = $ ; The charis held as a one-byte integer in memory. The ASCII code is what is actually stored, so we can use them as characters or integers, depending on our need. 14

Use scanf( %c, &ch) ; to read a single character into the variable ch. Use printf( %c, ch) ; to display the value of a character variable. 15

#include <stdio.h> int main ( ) { char ch ; printf ( Enter a character: ) ; scanf ( %c, &ch) ; printf ( The value of %c is %d.\n, ch, ch) ; return 0 ; If the user entered an A, the output would be: The value of A is 65. 16

The getchar( ) function is found in the stdio library. The getchar( ) function reads one character from stdin(the keyboard) and returns that character s ASCII value. The value can be stored in either a character variable or an integer variable. 17

#include <stdio.h> int main ( ) { char ch ; /* int ch would also work! */ printf ( Enter a character: ) ; ch = getchar( ) ; /*same as scanf( %c, &ch); */ printf ( The value of %c is %d.\n, ch, ch) ; return 0 ; If the user entered an A, the output would be: The value of A is 65. 18

When getting characters, whether using scanf( ) or getchar( ), realize that you are reading only one character. What will the user actually type? The character -followed by pressing ENTER. So, the user is actually entering twocharacters, the response and the newline character. Unless you handle this, the newline character will remain in the stdinstream causing problems the next time you want to read a character. Another call to scanf() or getchar( ) will remove it. 19

When we were reading integers using scanf( ), we didn t seem to have problems with the newline character, even though the user was typing ENTER after the integer. That is because scanf( ) was looking for the next integer and ignored the newline (whitespace). If we use scanf( %d, &num); to get an integer, the newline is still stuck in the input stream. If the next item we want to get is a character, whether we use scanf( ) or getchar( ), we will get the newline. We have to take this into account and remove it. 20

#include <stdio.h> int main ( ) { char ch, newline ; printf ( Enter a character: ) ; ch = getchar( ) ; newline = getchar( ) ; printf ( The value of %c is %d.\n, ch, ch) ; printf ( Enter another character: ) ; ch = getchar( ) ; newline = getchar( ) ; printf ( The value of %c is %d.\n, ch, ch) ; return 0 ; 21

Choose one option: 1 Convert Fahrenheit to Celsius 2 Convert kilometers to miles 3 Convert knots to miles per hour 0 Exit program 1. Display this menu to the user s console 2. Get the user s choice as a character 3. Call an appropriate method to perform that conversion 22

int main() { int num = 0; do { while ( num < 0 ) ; return 0; 23

int main() { int num = 0; do { printf ("Enter a positive number: "); scanf ("%d", &num) ; if ( num < 0 ) { printf ("\ntry again\n"); while ( num < 0 ) ; return 0; 24

int main() { char option ; do { printf ("Choose one option: \n");... option = getchar(); if (option == 0 ) {... if (option == 1 ) {...... while (option < 0 option > 3 ) ; 25

if (option == 1 ) { convertfahrenhettocelsius(); else if (option == 2 ) { convertkilostomiles(); else if (option == 3 ) { convertknotstomph(); else if (option == 0 ) { return 0 ; 26

switch (option) { case 1 : convertfahrenhettocelsius(); break; case 2 : convertkilostomiles() ; break; case 3 : convertknotstomph() ; break; case 0 : return 0 ; break; default: printf( %c is invalid\n,option); break; 27

switch (option) { case 1 :... break; case : case \n : case \t : break; // blank // newline // tab default:... break; 28

class IfElseDemo{ public static void main(string[] args) { inttestscore= 76; char grade; if (testscore>= 60) { grade = 'D'; else if (testscore>= 70) { grade = 'C'; else if (testscore>= 80) { grade = 'B'; else if (testscore>= 90) { grade = 'A'; else { grade = 'F'; System.out.println("Grade = " + grade); 29