Introduction to Programming

Similar documents
Concept of algorithms Understand and use three tools to represent algorithms: Flowchart Pseudocode Programs

Introduction to Programming

Introduction to Programming

Introduction to Programming

More examples for Control statements

Slides adopted from T. Ferguson Spring 2016

C/Java Syntax. January 13, Slides by Mark Hancock (adapted from notes by Craig Schock)

C/Java Syntax. Lecture 02 Summary. Keywords Variable Declarations Data Types Operators Statements. Functions. if, switch, while, do-while, for

Introduction to Programming

& Technology. Expression? Statement-x. void main() int no; scanf("%d", &no); if(no%2==0) if(no%2!=0) Syllabus for 1. of execution of statements.

Flow of Control. Selection. if statement. True and False in C False is represented by any zero value. switch

Lecture 02 Summary. C/Java Syntax 1/14/2009. Keywords Variable Declarations Data Types Operators Statements. Functions

Decision Making and Loops

CP FAQS Q-1) Define flowchart and explain Various symbols of flowchart Q-2) Explain basic structure of c language Documentation section :

Precedence and Associativity Table. % specifiers in ANSI C: String Control Codes:

Problem # 1. calculate the grade. Allow a student the next grade if he/she needs only 0.5 marks to obtain the next grade. Use else-if construction.

Decision Making. if Statement. Decision Making

Computer Programming. Decision Making (2) Loops

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

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

EECE.2160: ECE Application Programming Spring 2016 Exam 1 Solution

PDS Lab Section 16 Autumn Tutorial 3. C Programming Constructs

Computer Programing. for Physicists [SCPY204] Class 02: 25 Jan 2018

Flow Chart. The diagrammatic representation shows a solution to a given problem.

Programming Language A

COMP 208 Computers in Engineering

Lecture 3. More About C

COP 2000 Introduction to Computer Programming Mid-Term Exam Review

Introduction to C Programming

16.216: ECE Application Programming Fall 2011

BSM540 Basics of C Language

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

Computer Programming: Skills & Concepts (CP) Variables and ints

Lecture 8. Daily Puzzle

UIC. C Programming Primer. Bharathidasan University

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

Decision making with if Statement : - Control Statements. Introduction: -

Data types, variables, constants

CSE123 LECTURE 3-1. Program Design and Control Structures Repetitions (Loops) 1-1

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

Type Conversion. and. Statements

DECISION CONTROL AND LOOPING STATEMENTS

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

Informatica e Sistemi in Tempo Reale

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

Fundamentals of Programming

{C} Programming. Part 1/2 Basics Variables, Conditions, Loops, Arrays, Pointer basics

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

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

Selection Statements. Pseudocode

C: How to Program. Week /Mar/05

MA 511: Computer Programming Lecture 3: Partha Sarathi Mandal

MODULE 2: Branching and Looping

Pointers. Pointer Variables. Chapter 11. Pointer Variables. Pointer Variables. Pointer Variables. Declaring Pointer Variables

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

University of Maryland College Park Dept of Computer Science CMSC106 Fall 2013 Midterm I Key

Applied Programming and Computer Science, DD2325/appcs15 PODF, Programmering och datalogi för fysiker, DA7011

DECISION MAKING STATEMENTS

C-Programming. CSC209: Software Tools and Systems Programming. Paul Vrbik. University of Toronto Mississauga

CS 115 Lecture 8. Selection: the if statement. Neil Moore

CPS 101 Introduction to Computational Science

Basic Assignment and Arithmetic Operators

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

Unit 5. Decision Making and Looping. School of Science and Technology INTRODUCTION

EECE.2160: ECE Application Programming Fall 2017

Summary of Lecture 4. Computer Programming: Skills & Concepts (INF-1-CP1) Variables; scanf; Conditional Execution. Tutorials.

Copy: IF THE PROGRAM or OUTPUT is Copied, then both will have grade zero.

Conditional Expressions

Programming Language A

Operators And Expressions

Lecture 5: Multidimensional Arrays. Wednesday, 11 February 2009

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

Control Flow, Functions and Basic Linkage

Programming for Electrical and Computer Engineers. Loops

Structured programming. Exercises 3

What we have learned so far

Fundamental of Programming (C)

دستور خروجی. :cout این شی ء در فایل سرآیند iostream.h قرار دارد نکته: در 2008 این شی ء با افزودن ; std using namespace قابل دسترسی است.

Lecture 6. Statements

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

Control structures in C. Going beyond sequential

Structured programming

Computers Programming Course 7. Iulian Năstac

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

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

Flow Control. CSC215 Lecture

PESIT Bangalore South Campus Hosur Road (1km before Electronic City), Bengaluru Department of Basic Science and Humanities

Q1: C input/output; operators / 46 Q2: Conditional statements / 34 Q3: While and do-while loops / 20 TOTAL SCORE / 100 Q4: EXTRA CREDIT / 10

Chapter 4: Expressions. Chapter 4. Expressions. Copyright 2008 W. W. Norton & Company. All rights reserved.

EECE.2160: ECE Application Programming Spring 2018

Chapter 3 Structured Program Development

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

Arithmetic type issues

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

UNIVERSITY OF TORONTO FACULTY OF APPLIED SCIENCE AND ENGINEERING

Slide Set 1. for ENCM 339 Fall Steve Norman, PhD, PEng. Electrical & Computer Engineering Schulich School of Engineering University of Calgary

COP 3275: Chapter 09. Jonathan C.L. Liu, Ph.D. CISE Department University of Florida, USA

Unit 3. Operators. School of Science and Technology INTRODUCTION

Expressions. Arithmetic expressions. Logical expressions. Assignment expression. n Variables and constants linked with operators

Midterm Exam. CSCI 2132: Software Development. March 4, Marks. Question 1 (10) Question 2 (10) Question 3 (10) Question 4 (10) Question 5 (5)

Transcription:

Introduction to Programming Lecture 6: Making Decisions

What We Will Learn Introduction Conditions and Boolean operations if-else statement switch-case statement Conditional expressions 2

What We Will Learn Introduction Conditions and Boolean operations if-else statement switch-case statement Conditional expressions 3

Decision Decisions are based on conditions Read the C programming language Next week you have exam :-O ;-) In programming Do statements based on conditions True The statements will be done False The statement wont be done 4

Conditions Conditions by comparisons; e.g., If a is greater then b If c equals to d Comparing numbers: Relational Operators 5

Relations Relations are not a complete statement int a, b; a == b; //ERROR a <= b; //ERROR Relations produce a boolean value int a, b; bool bl; // #include <stdbool.h> bl = a == b; bl = a <= b; 6

Boolean operations Multiple conditions in decision making Logical relation between conditions if you are student and you have the programming course You should read the book C Boolean operators and && or not! p q p && q p q!p False False False False True False True False True True True False False True False True True True True False 7

Boolean operations (cont d) Examples bool a = true, b = false, c; c =!a; // c = false c = a && b; // c = false c = a b; // c = true c =!a b; // c = false 8

Precedence 9

Relations, No type effect int a = 10, b = 20; float f = 54.677f; double d = 547.775; char c1 = 'A', c2 = 'a'; bool b1; b1 = a == f; b1 = a <= d + 5; b1 = d < c1 * 10; b1 = c1 == c2; b1 = '1' < '2'; b1 = c1 + f < d + a; // false // true // true // false // true // true 10

Casting In logical operations 0 False, non-zero True In mathematical & comparison operations False 0, True 1 bool b1, b2; int i = 0, j = 20; b1 = i && j; b2 = j j; // b1 = false // b2 = true i = b1 + b2; // i = 1 j = (i < j) + (b1 && b2); // j = 1 11

Examples x [10, 20] Wrong Version 10 <= x <= 20 Let x = 30 10 <= 30 <=20 (10 <= 30) <= 20 true <= 20 1 <= 20 true!!! Correct Version (10 <= x) && (x <= 20) Let x = 30 (10 <= 30) && (30 <= 20) true && false false 12

Examples a,b > 0 Wrong version a && b > 0 Let a = -10, b = 20-10 && 20 > 0-10 && (20 > 0) -10 && true true && true true!!! Correct version (a > 0) && (b > 0) Let a = -10, b = 20 (-10 > 0) && (20 > 0) false && true false 13

Lazy evaluation When final result is found, does not evaluate remaining int i; bool a = true, b = false, c = true; bool d = a b c bool d = b && (a c) bool d = (i > 0) && (sqrt(i) > 5.6) 14

What We Will Learn Introduction Conditions and Boolean operations if-else statement switch-case statement Conditional expressions 15

Type of statements (دستور عبارتي) Expression statement Single statements x = y + 10; scanf("%d", &i); (دستور كنترلي) Control statement Control the flow of program Decisions and loops (دستور مركب) Compound statement Starts with { and ends with } All statements can be between { and } 16

if statement Decision making in C if( <expression> ) else <statements1> <statements2> Expression A boolean statement: a <= b A mathematical statement: a + b or a variable: a zero false Non-zero true 17

Flowchart if(<expression>) <statement> if(<expression>) <statement1> else <statement2> 18

برنامه اي كه يك عدد را از كاربر مي گيرد و مشخص مي كند كه اين عدد فرد است يا زوج #include <stdio.h> int main(void){ int number_to_test, remainder; printf("enter your number to be tested: "); scanf("%d", &number_to_test); remainder = number_to_test % 2; if(remainder == 0) printf ("The number is even.\n"); else printf ("The number is odd.\n"); } return 0; 19

Statements in if-else Empty statement if(a > b) Printf("A is larger \n"); else ; Block statements if(a <= b){ printf("a is less than b or "); printf("a is equal b\n"); } else printf("a is greater than b\n"); 20

#include <stdio.h> int main(void){ int i; char c; printf("enter a char: "); scanf(" %c", &c); printf("enter an int: "); scanf("%d", &i); برنامهاي كه يك حرف و يك عدد را ميگيرد. در مورد عدد مشخص ميكند كه آيا بزرگتر صفر است يا نه. در مورد حرف اگر حرف عددي باشد پيغام چاپ ميكند. if(i > 0) printf("your number is larger than 0\n"); else printf("your number is less than or equal 0\n"); } if((c >= '0') && (c <= '9')) printf("your char is Numeric \n"); return 0; 21

More than two choices If statement: 2 choices If conditions are true if statements If conditions are false else statements How to make decisions when there are multiple choices? 22

Map numeric grade to alphabetic int numg; char alphag; if((numg < 25) alphag = 'D'; if((numg >= 25) && (numg < 50)) alphag = 'C'; if((numg >= 50) && (numg < 75)) alphag = 'B'; if(numg >= 75) alphag = 'A'; 23

More than two choices To avoid repeating conditions in if statements To avoid running unnecessary statements Nested if: check multiple conditions <Statements 1> becomes an if-else statement <Statements 2> becomes an if-else statement Repeat it as many as needed 24

Nested if if(<condition 1>) <statement 1> else{ if(<condition 2>) <statement 2> else <statement 3> } if(<condition 1>) <statement 1> else if(<condition 2>) <statement 2> else <statement 3> 25

Map numeric grade to alphabetic int numg; char alphag; if(numg < 25) alphag = D ; else{ if(numg < 50) alphag = C ; else{ if(numg < 75) alphag = B ; else alphag = A } } 26

Map numeric grade to alphabetic int numg; char alphag; if(numg < 25) alphag = 'D'; else if(numg < 50) alphag = 'C'; else if(numg < 75) alphag = 'B'; else alphag = 'A'; 27

Map numeric grade to alphabetic int numg; char alphag; if(numg < 50){ if(numg < 25) alphag = 'D'; else alphag = 'C'; } else{ if(numg < 75) alphag = 'B'; else alphag = 'A'; } 28

Nested if: Example 2 Determine a char is alphabetic, Uppercase or not, numeric, less or greater than 5 or none of them /* 0 : 48, 9 : 57, A : 65, Z : 90, a : 97, z : 122 */ char c; if(((c >= 'a') && (c <= 'z')) ((c >= 'A') && (c <= 'Z'))){ } if(c >= 'a') else printf("the char is Lowercase \n"); printf("the char is Uppercase \n"); else if((c >= '0') && (c <= '9')){ } else if(c > '5') else printf("the char is greater than 5\n"); printf("the char is less than or equal 5\n"); printf("the char is not either alphabetic or numeric"); This can be written in other ways 29

Equivalent if-else of Nested if-else if(c1) if(c2) s1 else s2 else if(c3) s3 else s4 if(c1 && c2) s1 if (c1 &&!(c2)) s2 if (!(c1) && c3) s3 if (!(c1) &&!(c3)) s4 30

Nested if: Incomplete branch 1) else part is optional 2) else always associates with the nearest if 1 + 2 can be dangerous specially in incomplete branchs Example: Tell user to move or game over if(gameisover == 0) else if(playertomove == YOU) printf ("Your Move\n"); printf ("The game is over\n"); To avoid error you should Close off you code or Use Empty statements 31

Nested if: close off & empty statement if(gameisover == 0){ if(playertomove == YOU) printf ("Your Move\n"); } else printf ("The game is over\n"); //-------------------------------- if(gameisover == 0) if(playertomove == YOU) printf ("Your Move\n"); else ; else printf ("The game is over\n"); This one is better. 32

Print in base-2, 0 <= input < 16 33

Duplicate zero, input is 3 digit 34

What We Will Learn Introduction Conditions and Boolean operations if-else statement switch-case statement Conditional expressions 35

switch-case: Multiple choices Multiple conditions If-else if-else if-. Select from alternative values of a variable switch-case Values should be constant not expression: i, i+j, Values & Variables should be int or char switch(variable){ } case value1: <statements 1> case value2: <statements 2> 36

How does switch-case work? Each switch-case can be rewritten by If-else if-else version of switch-case in the previous slide if(variable == value1)} <statements 1> <statements 2> } else if(variable == value2){ <statements 2> } 37

switch-case: complete version switch(variable){ case value1: <statements 1> break; case value2: <statements 2> break; default: <statements 3> } If(variable == value1) { <statements 1> } else if(variable == value2) { <statements 2> } else{ <statements 3> } 38

#include <stdio.h> #include <stdlib.h> int main(void){ int res, opd1, opd2; char opr; printf("operand1 : "); scanf("%d", &opd1); printf("operand2 : "); scanf("%d", &opd2); printf("operator : "); scanf(" %c", &opr); switch(opr){ case '+': res = opd1 + opd2; break; 39 برنامهاي كه دو عدد و يك عملگر ميگيرد عملگر را بر روي اعداد اعمال و نتيجه را چاپ ميكند. را

} case '-': res = opd1 - opd2; break; case '/': res = opd1 / opd2; break; case '*': res = opd1 * opd2; break; default: printf("invalid operator \n"); return -1; } printf("%d %c %d = %d\n", opd1, opr, opd2, res); return 0; 40

switch-case (cont d) All values used in case should be different switch(i){ case 1: case 2: case 1: //Error 41

switch-case (cont d) All values must be value, not expression of variables switch(i){ case j: case 2: case k+10: //Error 42

switch-case: multiple matches switch(variable){ case value1: case value2: <statements 1> break; case value3: <statements 2> } If( (variable == value1) (variable == value2) ){ <statements 1> } else if (variable == value3) { <statements 2> } 43

switch-case vs. if-else if-else is more powerful than switch-case switch-case is only for checking the values of a variable and the values must be constant Some if-else cannot be rewritten by switch-case double var1, var2; if(var1 <= 1.1) <statements 1> if(var1 == var2) <statements 2> 44

Nested switch-case bool b; //b = x && y switch (x){ case 0: b = 0; break; case 1: switch(y){ case 0: b = 0; break; case 1: b = 1; break; } break; } 45

What We Will Learn Introduction Conditions and Boolean operations if-else statement switch-case statement Conditional expressions 46

Conditional Expression Assign value according to conditions A ternary ( تايي (سه operator int i, j, k; bool b;... i = b? j : k; /* if(b) * i = j * else * i = k; */ 47

Conditional Expression: Examples y = abs(x) y = (x > 0)? x : -x; signum = (x < 0)? -1 : (x > 0? 1 : 0) 48

Map Alphabetic Grade to Numeric int d = numg / 25 charg = (d == 0)? D : ((d == 1)? C : (d == 2)? B : A ); 49

Common Bugs Equality of floating point numbers Two float numbers may or may NOT be equal double d1, d2; d1 = 1e20 + 1; d2 = 1e20-1; if(d1 == d2) printf("they are equal :-o \n"); else printf("they are not equal :D \n"); They are equal :-o 50

Common Bugs Danger of empty statement Danger of assignment (=) and equality (==) int a = 10; int b = 20; if(a=b) // Logical Error Danger of similarity between C and mathematic if(a < b < c) // Logical Error if(a && b > 0) // Logical Error 51

Avoiding Bugs Precedence of operators if(!a && b) or if(!(a && b)) Use parenthesis in conditions Close-off code as much as you can 52

Reference Reading Assignment: Chapter 3 of C How to Program 53

Homework Homework 3 54