Programming Control Flow. Sequential Program S1 S2 S5 S4 S3 int main() { Statement1; Statement2; … StatementN; } Start End.

Slides:



Advertisements
Similar presentations
CSE 1301 Lecture 5B Conditionals & Boolean Expressions Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison.
Advertisements

Making Choices in C if/else statement logical operators break and continue statements switch statement the conditional operator.
1 Conditional Statement. 2 Conditional Statements Allow different sets of instructions to be executed depending on truth or falsity of a logical condition.
BBS514 Structured Programming (Yapısal Programlama)1 Selective Structures.
For loops For loops are controlled by a counter variable. for( c =init_value;c
Selection Statements Selects statements to execute based on the value of an expression The expression is sometimes called the controlling expression Selection.
Problem Solving and Program Design in C (5th Edition) by Jeri R. Hanly and Elliot B. Koffman Chapter 4 (Conditional Statements) © CPCS
true (any other value but zero) false (zero) expression Statement 2
ECE122 L7: Conditional Statements February 20, 2007 ECE 122 Engineering Problem Solving with Java Lecture 7 Conditional Statements.
Logical Operators and Conditional statements
לולאות 02 יולי יולי יולי 1502 יולי יולי יולי 1502 יולי יולי יולי 15 1 Department of Computer Science-BGU.
1 Agenda Variables (Review) Example Input / Output Arithmetic Operations Casting Char as a Number (if time allow)
1 Lecture 5  More flow control structures  for  do  continue  break  switch  Structured programming  Common programming errors and tips  Readings:
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.
Programming Variables. Named area in the computer memory, intended to contain values of a certain kind (integers, real numbers, characters etc.) They.
Algorithms and Computing Lecture 3 Control Statements By Dr. M. Tahir Khaleeq.
Conditional Statement
C programming for Engineers Lcc compiler – a free C compiler available on the web. Some instructions.
Programming C for Engineers An exercise is posted on the web site! Due in one week Single submission.
Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee C Language Part 2.
1 if and if-else statements. 2 Relational Operators x < y < is an operator x and y are its operands ( x < y ) is called a logical expression. Logical.
CPS120: Introduction to Computer Science Decision Making in Programs.
CMSC 104, Version 8/061L11Relational&LogicalOps.ppt Relational and Logical Operators Topics Relational Operators and Expressions The if Statement The if-else.
Programming in Java (COP 2250) Lecture 11 Chengyong Yang Fall, 2005.
Chapter 4 Selection Structures: Making Decisions.
1 Lecture 5: Selection Structures. Outline 2  Control Structures  Conditions  Relational Operators  Logical Operators  if statements  Two-Alternatives.
1 If statement and relational operators –, >=, ==, != Finding min/max of 2 numbers Finding the min of 3 numbers Forming Complex relational expressions.
Copyright © 2012 Pearson Education, Inc. Chapter 4: Making Decisions.
Flow of Control Part 1: Selection
A First C Program /* Print a Message */ #include main() { printf("This is a test!\n"); } The program is compiled and run as cc pg32.c  a.out  This is.
A First Book of ANSI C Fourth Edition Chapter 4 Selection.
Decision making statements. Decision making statements are used to skip or to execute a group of statements based on the result of some condition. The.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4: Making Decisions.
Programming C for Engineers An exercise is posted on the web site! Due in one week Single submission.
CSE 1301 Lecture 8 Conditionals & Boolean Expressions Figures from Lewis, “C# Software Solutions”, Addison Wesley Richard Gesick.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
Selection-making Decisions Selection allows you to choose between two or more possible program flow --- it lets you make decisions in your program. Examples.
Introduction to C Programming CE Lecture 3 Control Structures in C.
Problems Reads a letter grade from user and displays the corresponding range for that letter grade (A  , B  80-89, C  70-79, D  60-69, otherwise.
1 Agenda If Statement True/False Logical Operators Nested If / Switch Exercises & Misc.
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.
CSCI 171 Presentation 3. Operators Instructs C to perform some operation Assignment = Mathematical Relational Logical.
1 Lecture03: Control Flow 9/24/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
Control structures in C by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile
Dr. Sajib Datta Jan 23,  A precedence for each operator ◦ Multiplication and division have a higher precedence than addition and subtraction.
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.
Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1.
 Real numbers representation - Floating Point Notation  First C Program  Variables Declaration  Data Types in C ◦ char, short, int, long, float, double,
Dr. Sajib Datta Sep 3,  A new operator used in C is modulus operator: %  % only used for integers, not floating-point  Gives the integer.
CNG 140 C Programming (Lecture set 3)
Control Structures Combine individual statements into a single logical unit with one entry point and one exit point. Used to regulate the flow of execution.
Chapter 4: Making Decisions.
Chapter 4 (Conditional Statements)
Chapter 4 - Program Control
Chapter 4: Making Decisions.
CSE1320 INTERMEDIATE PROGRAMMING Operators+Conditionals+Loop
Introduction to Programming
- Additional C Statements
C Programming Variables.
Relational and Logical Operators
Week 2 Variables, flow control and the Debugger
CPS125 Week 5.
Control Structures Lecture 6.
Chapter 4 - Program Control
Comparing Data & the ‘switch’ Statement
Flow of Control.
ICS103: Programming in C 4: Selection Structures
Presentation transcript:

Programming Control Flow

Sequential Program S1 S2 S5 S4 S3 int main() { Statement1; Statement2; … StatementN; } Start End

Absolute Value Given a user input we would like to calculate its absolute value. Something along the lines If the number is negative “make it positive” Notice that we only execute “make it positive” in case the number is negative!

Conditional Statements Selects statements to execute based on the value of an expression  The expression is sometimes called the guard Conditional statements:  if statement  switch statement

if Statement Used to conditionally execute a statement or block of statements. if (expression) statement; if (grade > 60) printf("Congratulations! You passed"); printf("Your grade is %d", grade); Expr Statement Rest of Program True False

Operators In C, every expression has a numeric value When using arithmetic operators (+, -, *, /) this is straightforward  The value of A+B is the sum of A and B  And so on…

More About Operators Expressions with relational operators (, >=, etc.) have values as well (intuitively, we are used to thinking about them as ‘true’ or ‘false’) A < B evaluates to zero if A is larger than or equal to B, and some non-zero value if A is smaller than B The exact non-zero value varies (and is not important for that matter)

Relational operators They are:  A == B (Note the difference from A = B)  A != B  A < B  A > B  A <= B  A >= B The expression is “false” if it’s value is zero and “true” otherwise

True or False In C, every expression has a numeric value An expression is ‘true’ when its value is non- zero it is false it evaluates to zero. Therefore, in the following – if (expression) statement statement is executed if expression evaluates to non-zero.

Block A sequence of statements enclosed within curly braces {} if (grade > 60) { printf("Congratulations! You passed"); printf("Hip Hip Hooray!"); } printf("Your grade is %d", grade);

Example - Absolute Value void main() { double num; printf("Please enter a real number: "); scanf("%lf", &num); if (num < 0) num = -num; printf("The absolute value is %g\n", num); }

if-else Statement if (expression) statement 1 else statement 2 if expression is true, statement 1 is executed. if expression is false, statement 2 is executed both statements can be (and very often are) replaced by blocks of statements (“compound statements”) Expr Statement1 Rest of Program True False Statement2

Example - min int first, second, min;... if (first < second) { min = first; printf ("The first number is smaller than the second.\n"); } else { min = second; printf ("The second number is smaller than the first\n"); } printf("The smaller number is %d\n", min);

Nested if The statement in the if statement’s body can be an if statement if (expression) statement if (expression) statement1 else statement2

Example – Nested if-else if (x == y) if (y == 0) printf("x == y == 0"); else printf("x == y; x,y != 0");

Indentation if (x == y) if (y == 0) printf("x == y == 0"); else printf("x == y; x,y != 0"); Misleading indentation else is associated with the closest if use {} for clarity and to change the meaning

Indenting if Statements if (x == y) if (y == 0) printf("x == y == 0"); else printf("x == y; x,y != 0");

Indenting if Statements if (x == y) { if (y == 0) printf("x == y == 0"); else printf("x == y; x,y != 0"); }

Indenting if Statements if (x == y) { if (y == 0) { printf("x == y == 0"); } else { printf("x == y; x,y != 0"); } }

if-else Statement (cont.) if (x == y) { if (y == 0) printf("x == y == 0"); } else printf("x == y; x,y != 0");

else if if statements distinguish between exactly 2 cases and execute different code in each case The else-if construction allows for a multi-way selection

Indenting else if if (expression 1 ) statement 1 else if (expression 2 ) statement 2 else if (expression 3 ) statement 3 else statement 4

Example if (grade >= 90) { printf ("A\n"); } else if (grade >= 80) { printf ("B\n"); } else if (grade >= 70) { printf ("C\n"); } else if (grade >= 60) { printf ("D\n"); } else { printf ("F\n"); }

Example – Different Indentation if (grade >= 90) { printf ("A\n"); } else { if (grade >= 80) { printf ("B\n"); } else { if (grade >= 70) { printf ("C\n"); } else { if (grade >= 60) { printf ("D\n"); } else { printf ("F\n"); } } } }

Example int a, b; printf("Enter two numbers\n"); scanf("%d%d", &a, &b); if (a == b) { printf("The numbers equal %d\n", a); printf("The expression a == b is %d\n", a == b); } else { printf("The numbers are not equal\n"); printf("The expression a == b is %d\n", a == b); } some non-zero value 0

Assignment Expression = Assignment expressions have a value. It is the value of the right-hand-side expression For example: (x = 4) evaluates to 4 x = y = z = 0 ( )

A Common Error Confusing between the equality and assignment operators  we wanted if (x == 4) …  we wrote if (x = 4) …

Example void main() { int i = 2; printf("i = %d\n", i); printf("(i==4) = %d\n", i==4); printf("i = %d\n", i); printf("(i=4) = %d\n", i=4); printf("i = %d\n", i); } i = 2 (i==4) = 0 i = 2 (i=4) = 4 i = 4

Rule of Thumb When comparing to a constant it is better to write the constant first how does this help us? (4 == i) is the same as (i == 4) BUT (4 = i) is a compilation error

Logical Operators  !A – ‘not’ - True when A is false, and vice versa.  A && B – ‘and’ - True when both A and B are true  A || B – ‘or’ (inclusive or) - True when either A or B (or both) are true

Logical Operators !- not  !, negate the value of the expression. &&- and  &&, True when both expressions are true ||- or  ||, True when at least one of the expressions is true

Truth Tables X && YYX False TrueFalse True X ||YYX False True False TrueFalseTrue !XX TrueFalse True NOT ORAND

Compound Expressions Expressions can be combined using logical operators If we want to check that a value is within a range Instead of : Write: if (grade >= 55) if (grade < 60) { /* recheck the exam */ } if (grade >= 55 && grade < 60) { /* recheck the exam */ }

Compound Expressions Do something if a char is A, C, G or T Instead of: You can write: if (c == 'A' || c == 'C' || c == 'G' || c == 'T') { /* do something */ } if (c == 'A') { /* do something */ } else if (c == 'C') { /* it’s the same thing as before */ } else if (c == 'G') { /* write it again? */ } else if (c == 'T') { /* not again!!! */ }

Revisiting main Programs are executed in an environment Upon termination a termination status should be passed to the environment void main() {... } int main() {... return 0; }

return Statement return Terminates the program (for now) Return the value of to the environment For now:  1 – an error occurred  0 – program terminated without errors.

Validating Input When getting input from the user, it is highly recommended to check whether it is valid. If it’s not, you should display an appropriate message and return a non-zero value. For example – if (grade 100) { printf(“Invalid grade!\n”); return 1; }

A silly example int main(void) { int grade; printf("Please enter your grade: "); scanf("%d", &grade); if (grade 100) { printf("This is not a valid grade!\n"); return 1; } printf("This is indeed a grade.\n"); return 0; } Error!! All is well

Exercise Read a single letter from the user Make sure the input is valid In case the letter is lowercase convert to uppercase. In case the letter is uppercase convert to lowercase.

Solution int main() { char c; printf("Please enter a letter: "); scanf("%c", &c); if (c >= 'a' && c <= 'z') printf("%c in uppercase is %c\n", c, c-'a'+'A'); else if (c >= 'A' && c <= 'Z') printf("%c in lowercase is %c\n", c, c-'A'+'a'); else{ printf("%c is not a letter!\n", c); return 1; } return 0; }

Exercise Input  Two integers, A and B Output  Their relation (i.e. displays A==B, A B)

Solution int main() { int m, n; printf("Enter two numbers\n"); scanf("%d%d", &m, &n); if (m == n) printf("%d == %d\n", m, n); else if (m > n) printf("%d > %d\n", m, n); else printf("%d < %d\n", m, n); return 0; }

The conditional operator expr 1 ? expr 2 : expr 3 This is an expression. It has a value! If expr 1 is True (non-zero), expr 2 is evaluated; otherwise expr 3 is evaluated

The conditional operator int main() { int i, j, min; printf("Please enter two numbers: "); scanf("%d%d", &i, &j); min = (i < j) ? i : j; printf("The minimum between %d and %d is %d\n", i, j, min); return 0; }

?: vs. if int main() { int i, j, min; printf("Please enter two numbers: "); scanf("%d%d", &i, &j); if (i < j) min = i; else min = j; printf("The minimum between %d and %d is %d\n", i, j, min); return 0; }

The ?: operator int main() { int i, j, min; printf("Please enter two numbers: "); scanf("%d%d", &i, &j); printf("The minimum between %d and %d is %d\n", i, j, (i < j)? i : j); return 0; }

The switch statement A multi-way conditional statement  similar to if-else..if-else  allows the selection of an arbitrary number of choices based on an integer value switch (expression) { case int-const-expr: statement break; case int-const-expr: statement break; … default: statement }

The switch statement expression must have an integer value (char, int) when the switch statement is executed:  the expression is evaluated  if a case matches the value of the expression, the program jumps to the first statement after that case label  otherwise, the default case is selected  the default is optional

That grade example again switch (grade/10) { case 10: case 9: printf ("A\n"); break; case 8: printf ("B\n"); break; case 7: printf ("C\n"); break; case 6: printf ("D\n"); break; default: printf ("F\n"); }

Give me a break when the switch transfers to the chosen case, it starts executing statements at that point it will “fall through” to the next case unless you “break out” break causes the program to immediately jump to the next statement after the switch

What will it print? Given your ID return the test score int id, score;... switch (id) { case 1: score = 90; case 2: score = 100; case 3: score = 87; default: score = 0; } printf(“Your test score is %d\n“, score);

Without break if (id == 1) jump to a; if (id == 2) jump to b; if (id == 3) jump to c; jump to d; score = 90; score = 100; score = 87; score = 0; a: b: c: d: end: Code executes sequentially

With break if (id == 1) jump to a; if (id == 2) jump to b; if (id == 3) jump to c; jump to d; score = 90; jump to end score = 100; jump to end score = 87; jump to end score = 0; a: b: c: d: end:

A more interesting example int main( ) { double n1, n2, res; char op; printf("Please enter two numbers: "); scanf("%lf%lf", &n1, &n2); printf("Please enter an arithmetical operator (+, -, * or /): "); scanf(" %c", &op); Continued on the next slide

Another example switch(op) { case '+': res = n1 + n2; break; case '-': res = n1 - n2; break; case '*': res = n1 * n2; break; case '/': /* We're not checking for division by zero for clarity... */ res = n1 / n2; break; default: printf("%c is an invalid arithmetical operator!\n", op); return 1; } /* Display the expression and its result */ printf("%g %c %g = %g\n", n1, op, n2, res); return 0; }

Exercise Write a program that accepts a number between 1 and 100 from the user. If there is a coin of that value in cents, it should display its name. Otherwise, it should report that there is no such coin 1 = cent, 5 = nickel, 10 = dime, 25 = quarter, 100 = dollar Remember to check for the validity of the input!

Solution int main() { int num; printf("Please enter a number from 1 to 100: "); scanf("%d", &num); /* Make sure the input is valid */ if (num 100) { printf("Invalid input!\n"); return 1; } /* Display the correct coin name, or a default message if there's no such coin */ switch (num) { case 1: printf("It's a cent!\n"); break; case 5: printf("It's a nickel!\n"); break; case 10: printf("It's a dime!\n"); break; case 25: printf("It's a quarter!\n"); break; case 100: printf("It's a whole dollar!\n"); break; default: printf("It's not a coin!\n"); } return 0; }