1 Lecture03: Control Flow 9/24/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.

Slides:



Advertisements
Similar presentations
Making Choices in C if/else statement logical operators break and continue statements switch statement the conditional operator.
Advertisements

Lecture 2 Introduction to C Programming
Introduction to C Programming
Selection Statements Selects statements to execute based on the value of an expression The expression is sometimes called the controlling expression Selection.
1 ICS103 Programming in C Lecture 3: Introduction to C (2)
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 1.
Copyright © 2012 Pearson Education, Inc. Chapter 4: Making Decisions.
C. About the Crash Course Cover sufficient C for simple programs: variables and statements control functions arrays and strings pointers Slides and captured.
Introduction to Computers and Programming Class 6 Introduction to C Professor Avi Rosenfeld.
C programming an Introduction. Types There are only a few basic data types in C. char a character int an integer, in the range -32,767 to 32,767 long.
The If/Else Statement, Boolean Flags, and Menus Page 180
Introduction to C Programming
Programming Control Flow. Sequential Program S1 S2 S5 S4 S3 int main() { Statement1; Statement2; … StatementN; } Start End.
1 Lecture 5  More flow control structures  for  do  continue  break  switch  Structured programming  Common programming errors and tips  Readings:
Assignment #2, 12- month Calendar CS-2301, B-Term Programming Assignment #2 12-Month Calendar CS-2301, System Programming for Non-Majors (Slides.
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.
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
1 Chapter Four Boolean Expressions and Control Statements.
Algorithms and Computing Lecture 3 Control Statements By Dr. M. Tahir Khaleeq.
Spring 2005, Gülcihan Özdemir Dağ Lecture 3, Page 1 BIL104E: Introduction to Scientific and Engineering Computing, Spring Lecture 3 Outline 3.1 Introduction.
Programming C for Engineers An exercise is posted on the web site! Due in one week Single submission.
Lecture 10: Reviews. Control Structures All C programs written in term of 3 control structures Sequence structures Programs executed sequentially by default.
Principles of Programming - NI July Chapter 5: Structured Programming In this chapter you will learn about: Sequential structure Selection structure.
IF-ELSE IF-ELSE STATEMENT SWITCH-CASE STATEMENT Computer Programming Asst. Prof. Dr. Choopan Rattanapoka and Asst. Prof. Dr. Suphot Chunwiphat.
CSEB 114: PRINCIPLE OF PROGRAMMING Chapter 5: Structured Programming.
1 計算機程式設計 Introduction to Computer Programming Lecture01: Introduction and Hello World 9/10/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction.
Copyright © 2012 Pearson Education, Inc. Chapter 4: Making Decisions.
Repetitive Structures BBS514 Structured Programming (Yapısal Programlama)1.
Lecture 2: Logical Problems with Choices. Problem Solving Before writing a program Have a thorough understanding of the problem Carefully plan an approach.
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.
Making Decisions. 4.1 Relational Operators Used to compare numbers to determine relative order Operators: > Greater than < Less than >= Greater than.
Lecture 4: Calculating by Iterating. The while Repetition Statement Repetition structure Programmer specifies an action to be repeated while some condition.
Introduction to Programming Prof. Rommel Anthony Palomino Department of Computer Science and Information Technology Spring 2011.
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.
Chapter 5: Structured Programming
C Programming Lecture 7 : Control Structures. Control Structures Conditional statement : if, switch Determine a block of statements to execute depending.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 4: Making Decisions.
Chapter Making Decisions 4. Relational Operators 4.1.
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.
Operating System Discussion Section. The Basics of C Reference: Lecture note 2 and 3 notes.html.
 2007 Pearson Education, Inc. All rights reserved. A Simple C Program 1 /* ************************************************* *** Program: hello_world.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 4: Making Decisions 1.
Lecture 6 – Selection FTMK, UTeM – Sem /2014.
CS113 Introduction to C Instructor: Ioannis A. Vetsikas Lecture 2 : August 28 webpage:
Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 6.
Flow Control. Comments u Comments: /* This is a comment */ –Use them! –Comments should explain: v special cases v the use of functions (parameters, return.
Java Programming Fifth Edition
Chapter 4 – C Program Control
Chapter 5: Structured Programming
Administrative things
Chapter 4: Making Decisions.
ICS103 Programming in C Lecture 3: Introduction to C (2)
Chapter 4: Making Decisions.
Chapter 4: Making Decisions.
Administrative things
Introduction to C Programming
CSC215 Lecture Control Flow.
Program Breakdown, Variables, Types, Control Flow, and Input/Output
Relational, Logical, and Equality Operators
CSCE 206 Lab Structured Programming in C
Lecture 4: Selection Control Structure
CSC215 Lecture Control Flow.
Administrative things
Administrative things
Presentation transcript:

1 Lecture03: Control Flow 9/24/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C

Administrative things Any problem with submitting assignment #1? Assignment #2 is on the course webpage due next week. 2

Review from Last Week Variable declaration –Type, variable name C Punctuations –;, “ { } ( % # printf() : write to the screen –printf(format string, arg1, arg2, …) –What is a format string? Format tags whose values are substitute by args. –What are format tags? scanf() : read from the screen (user) –scanf(format string, &arg1, &arg2, …) –Store values into locations pointed by args 3

main.c: Variables & Punctuations #include int main() { int a, b, c; a = 10; b = 20; c = a * b; printf("a = %d b = %d c = %d\n", a, b, c); return 0; } 4

printf(format string, val1, val2); –format string can include placeholders that specify how the arguments val1, val2, etc. should be formatted –%c : format as a character –%d : format as an integer –%f : format as a floating-point number –% : print a % character Example double f = 0.95; printf("f = %f%\n", f * 100); More on printf() 5

scanf() #include int main() { int i; double f; scanf("%d", &i); scanf("%lf", &f); printf("Integer: %d Float: %2.2f\n", i, f); return 0; } 6

New Stuff: Control Flow 7

Statement := ; x = 0; ++i;// i = i + 1; printf("%d", x); 8

Blocks := { } { x = 0; ++i; printf("%d", x); } A block is syntactically equivalent to a single statement. –if, else, while, for –Variables can be declared inside any block. –There is no semicolon after the right brace that ends a block. 9

Example int x = 0; { int x = 5; printf("Inside: x = %d\n", x); } printf("Outside: x = %d\n", x); Inside: x = 5 Outside: x = 0 10

if Statement if ( ) // single statement if (2 < 5) printf("2 is less than 5.\n"); // block if (2 < 5) { printf("I'll always print this line.\n"); printf("because 2 is always less than 5!\n"); } 11

if-else Statement if ( ) else if (x < 0) { printf("%d is negative.\n", x); } else { printf("%d is non-negative.\n", x); } 12

else-if Statement if (a < 5) printf("a < 5\n"); else { if (a < 8) printf("5 <= a < 8\n"); else printf("a >= 8\n"); } if (a < 5) printf("a < 5\n"); else if (a < 8) printf("5 <= a < 8\n"); else printf("a >= 8\n"); 13

if-else Statement Pitfalls if (a > 70) if (a > 80) printf("grade = B\n"); else printf("grade < B\n"); printf("Fail.\n"); printf("Done.\n"); if (a > 70) { if (a > 80) { printf("grade = B\n"); } else { printf("grade < B\n"); } printf("Fail.\n"); printf("Done.\n"); 14

Relational Operators 15 C has the following relational operators a == btrue iff a equals b a != btrue iff a does not equal b a < btrue iff a is less than b a > btrue iff a is greater than b a <= btrue iff a is less than or equal to b a >= btrue iff a is greater than or equal to b a && btrue iff a is true and b is true a || btrue iff a is true or b is true !atrue iff a is false

Booleans in C C DOES NOT have a boolean type. –boolean means true or false. Instead, conditional operators evaluate to integers (int) –0 indicates false. Non-zero value is true. –if ( ) checks whether the condition is non-zero. –Programmer must be very careful to this point! 16 Example if (3) printf("True.\n"); if (!3) // unreachable code if (a = 5) // always true, potential bug (a == 5) int a = (5 == 5); // a = 1

In-Class Exercise #1 Write a program that reads a number grade (0-100) and converts it into a letter grade (ABCF): A:80-100, B:70-79, C:60- 69, and F<60. Your program should have the following input & output: Input a number grade> 80 Letter grade: A 17

Conditional expressions ? : grade = (score >= 70 ? 'S' : 'U'); printf("You have %d item%s.\n", n, n == 1 ? "" : "s"); Conditional expression often leads to concise code. 18

switch Statement A common form of if statement if (x == a) statement1; else if (x == b) statement2;... else statement0; switch statement switch (x) { case a: statement1; break; case b: statement2; break;... default: statement0; } 19

More on switch Statement Fall-through property int month = 2; switch (month) { case 1: printf("Jan.\n"); break; case 2: printf("Feb.\n"); case 3: printf("Mar.\n"); default: printf("Another month.\n"); } Feb. Mar. Another month. 20

More on switch Statement Fall-through property int month = 2; int days; switch (month) { case 2: days = 28; break; case 9: case 4: case 6: case 11: days = 30; break; default: days = 31; } It's always recommended to have default, though it's optional. if (month == 2) { days = 28; } else if (month == 9)) || (month == 6) || (month == 11)) { days = 30; } 21

In-Class Exercise #2 Write a program that reads a month (1-12) and converts it into a season: Spring:3-5, Summer:6-8; Fall:9-11 Winter:12-2. Use the switch statement. Your program should have the following input & output: Input a month(1-12)> 1 Season: Winter 22

while Loop while ( ) If the condition is initially false, the statement is never executed. do while ( ); The statement is executed at least one. 23

for Loop for ( ; ; ) exp1; while (exp2) { statement exp3; } for (i = 0; i < n; ++i) // ++i is the same as i = i + 1; { // do something } 24

Infinite Loop while (1) { // do something } for (;;) { // do something } Both are okay, but for may lead to fewer machine code on some platform, which means it is slightly more efficient. 25

break and continue break int n = 10; while (1) { if (!n) { break; } printf(“%d\n”, n) --n; } continue int i; for (i = 0; i < 10; ++i) { if (i == 0) { continue; } printf("%d\n", i); } 26

Common Pitfalls Always use {} int i; for (i = 0; i < 10; ++i); printf("%d\n", i); Put literals on the left int n = 10; while (n = 1) { printf("%d\n", n); --n; } 27

How to Avoid Bugs? Always use {} int i; for (i = 0; i < 10; ++i) { printf("%d\n", i); } Put literals on the left int n = 10; while (1 == n) { // 1 = n, compilation error printf("%d\n", n); --n; } 28

Review for Today if, else-if ? : switch, case, default, break for ( ; ; ) while ( ) do while ( ); break, continue 29

In-Class Exercise #3 Write a program that print all Fibonacci numbers smaller than 100. Fibonacci numbers are numbers in the following integer sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, … Your program should output exactly the following line. Note that there should not be a “,” after the last number. Fib: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89 30

In-Class Exercise #4 Write a program that print the pi number up to 100 smaller than 100. Fibonacci numbers are numbers in the following integer sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, … Your program should output exactly the following line. Note that there should not be a “,” after the last number. Fib: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89 31