Conditionals, Loops, and Other Statements CS-2301 D-term 20091 Conditionals, Loops, and Other Kinds of Statements CS-2301 System Programming C-term 2009.

Slides:



Advertisements
Similar presentations
1 Conditional Statement. 2 Conditional Statements Allow different sets of instructions to be executed depending on truth or falsity of a logical condition.
Advertisements

Lecture 2 Introduction to C Programming
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 4 – C Program Control Outline 4.1Introduction.
Computer Science 1620 Loops.
Differences between Java and C CS-2303, C-Term Differences between Java and C CS-2303, System Programming Concepts (Slides include materials from.
Display a 12-Month Calendar CS-2301 D-term Programming Assignment #2 12-Month Calendar CS-2301 System Programming C-term 2009 (Slides include materials.
Discussion of Assignment #2 CS-2301, B-Term Discussion of Assignment #2 CS-2301, System Programming for Non-Majors (Slides include materials from.
Introduction to FunctionsCS-2301 D-term Introduction to Functions CS-2301 System Programming C-term 2009 (Slides include materials from The C Programming.
Loose endsCS-2301, B-Term “Loose Ends” CS-2301, System Programming for Non-Majors (Slides include materials from The C Programming Language, 2 nd.
Loops – While, Do, For Repetition Statements Introduction to Arrays
1 Chapter 3 Flow of Control. 2 Outline  How to specify conditions?  Relational, Equality and Logical Operators  Statements  Statements: compound statement.
"Loose ends"CS-2301 D-term “Loose Ends” CS-2301 System Programming C-term 2009 (Slides include materials from The C Programming Language, 2 nd edition,
More on Numerical Computation CS-2301 B-term More on Numerical Computation CS-2301, System Programming for Non-majors (Slides include materials from.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Digression on Loop Invariants CS-2303, C-Term Digression on Loop Invariants CS-2303, System Programming Concepts (Slides include materials from The.
 2007 Pearson Education, Inc. All rights reserved C Program Control.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 4 - Program Control Outline 4.1Introduction 4.2The Essentials of Repetition 4.3Counter-Controlled.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
1 Lecture 5  More flow control structures  for  do  continue  break  switch  Structured programming  Common programming errors and tips  Readings:
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved The switch Multiple-Selection Statement switch.
ספטמבר 04Copyright Meir Kalech1 C programming Language Chapter 2: Control Flow.
Assignment #2, 12- month Calendar CS-2301, B-Term Programming Assignment #2 12-Month Calendar CS-2301, System Programming for Non-Majors (Slides.
Conditionals, Loops, and Other Statements CS-2301, B-Term Conditionals, Loops, and Other Kinds of Statements CS-2301, System Programming for Non-Majors.
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
C Programming Lecture 12. The Compound Statement b A compound statement is a series of declarations and statements surrounded by braces. b A compound.
Algorithms and Computing Lecture 3 Control Statements By Dr. M. Tahir Khaleeq.
EGR 2261 Unit 5 Control Structures II: Repetition  Read Malik, Chapter 5.  Homework #5 and Lab #5 due next week.  Quiz next week.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Program Control Outline 4.1Introduction 4.2The Essentials of Repetition 4.3Counter-Controlled.
Lecture 10: Reviews. Control Structures All C programs written in term of 3 control structures Sequence structures Programs executed sequentially by default.
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
Lecture 4 C Program Control Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee C Language Part 2.
Chapter 3 Control Flow Ku-Yaw Chang Assistant Professor, Department of Computer Science and Information Engineering Da-Yeh University.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 2 Chapter 2 - Introduction to C Programming.
CPS120: Introduction to Computer Science Decision Making in Programs.
Chapter 5: Control Structures II (Repetition). Objectives In this chapter, you will: – Learn about repetition (looping) control structures – Learn how.
CompSci 100E 2.1 Java Basics - Expressions  Literals  A literal is a constant value also called a self-defining term  Possibilities: o Object: null,
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 5: Introduction to C: More Control Flow.
Control Statements in C 1.Decision making statements 2.Looping statements 3.Branching statements
ECE 103 Engineering Programming Chapter 18 Iteration Herbert G. Mayer, PSU CS Status 7/19/2015 Initial content copied verbatim from ECE 103 material developed.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Program Control Outline 4.1Introduction 4.2The Essentials of Repetition 4.3Counter-Controlled.
Repetition and Iteration ANSI-C. Repetition We need a control instruction to allows us to execute an statement or a set of statements as many times as.
Loops cause a section of a program to be repeated a certain number of times. The repetition continues while a condition remains true. When a condition.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 2 - Introduction to C Programming Outline.
Repetition Repetition allows you to repeat an operation or a series of operations many times. This is called looping and is one of the basic structured.
CISC105 – General Computer Science Class 4 – 06/14/2006.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Control structures in C by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile
CC213 Programming Applications Week #2 2 Control Structures Control structures –control the flow of execution in a program or function. Three basic control.
C Program Control September 15, OBJECTIVES The essentials of counter-controlled repetition. To use the for and do...while repetition statements.
1 Lecture 2 - Introduction to C Programming Outline 2.1Introduction 2.2A Simple C Program: Printing a Line of Text 2.3Another Simple C Program: Adding.
Flow Control. Comments u Comments: /* This is a comment */ –Use them! –Comments should explain: v special cases v the use of functions (parameters, return.
Chapter 4 – C Program Control
Statements (6 of 6) A statement causes an action to be performed by the program. It translates directly into one or more executable computer instructions.
Chapter 4 - Program Control
Quick Test What do you mean by pre-test and post-test loops in C?
JavaScript: Control Statements.
Conditionals, Loops, and Other Kinds of Statements
Looping.
Arrays, For loop While loop Do while loop
- Additional C Statements
CS1100 Computational Engineering
Chapter 4 - Program Control
Programming Assignment #1 12-Month Calendar—
2.6 The if/else Selection Structure
Digression on Loop Invariants
ECE 103 Engineering Programming Chapter 18 Iteration
Chapter 4 - Program Control
Chapter 13 Control Structures
Presentation transcript:

Conditionals, Loops, and Other Statements CS-2301 D-term Conditionals, Loops, and Other Kinds of Statements CS-2301 System Programming C-term 2009 (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and Ritchie and from C: How to Program, 5 th and 6 th editions, by Deitel and Deitel)

Conditionals, Loops, and Other Statements CS-2301 D-term Reading Assignment Chapter 3 of Kernighan and Ritchie Helpful to follow along in class Note on §3.8 :– we do not allow goto statements in this course There is rarely, if any, situation at WPI where a goto in C would be the right thing

Conditionals, Loops, and Other Statements CS-2301 D-term Review Expression – a sequence of operators and operands that return a value Assignment – expression with the side effect of changing the value of the left operand

Conditionals, Loops, and Other Statements CS-2301 D-term Definition – Side Effect The changing of the value of some data in the course of evaluating or executing something else Sometimes unrelated data! Examples:– –Explicit assignments x = y + 3; i++; --j; –printf() Writes to internal buffer; flushes buffer to screen on '\n' –scanf() – returns values from input Explicit – assigns data to arguments Implicit – keeps track of where it is in internal buffer

Conditionals, Loops, and Other Statements CS-2301 D-term Definition – Statement Instruction to “do” something Specifies order of execution & evaluation §A.9 – a statement in C may be any of:– labeled-statement expression-statement compound-statement selection-statement iteration-statement jump-statement

Conditionals, Loops, and Other Statements CS-2301 D-term Expression Statement expression optional ; Note: semicolon is terminator Exists primarily for its side effects E.g., x = y + 3; i++; --j; printf(“string”, arg1, arg2, arg3); The following is perfectly legal in C:– y + 3; Evaluates the expression, then throws the result away!

Conditionals, Loops, and Other Statements CS-2301 D-term Compound Statement A sequence of statements surrounded by {} Example:– { x = 0; i++; printf("The value of x is %d\n", x); } Reason:– so that we can group together statements in loops, if-else, etc.

Conditionals, Loops, and Other Statements CS-2301 D-term Compound Statement (continued) Compound statements may be nested {...; { x = 0; i++; } /* no semicolon needed here*/ printf("The value of x is %d\n", x);...; }

Conditionals, Loops, and Other Statements CS-2301 D-term Compound Statement (continued) Compound statements may include declarations inside { double angle; angle = atan2(y, x) * 360/(2*pi); printf(“Angle is %f degrees\n”, angle); } Declarations inside of {} are not known outside of {} Book says declarations must be at beginning of {} Later versions of C relax this rule Declaration must always precede first use of declared identifier Note: declaration-definition of angle allocates memory. This is relinquished at end of {}. atan2(y,x) calculates the arctangent of y  x without zero-divide problems

Conditionals, Loops, and Other Statements CS-2301 D-term Questions?

Conditionals, Loops, and Other Statements CS-2301 D-term If-else Statements if ( expr ) statement 1 /*do this if expr is non-zero*/ else statement 2 /*do this if expr is zero*/ The else clause is optional!

Conditionals, Loops, and Other Statements CS-2301 D-term If-else Examples if (j > limit) return j; /* note semicolon*/ else j += stepValue; /* note semicolon*/... if (++k >= 4) k = 0; /* increment k mod 4*/

Conditionals, Loops, and Other Statements CS-2301 D-term If-else Examples (continued) if (n < maxInput) { scanf("string", &arg1, &arg2, …); n++; printf("string2", arg3, arg4, …); } else { /* note NO semicolon*/ printf("Summary\n", arg5, …); return n; }

Conditionals, Loops, and Other Statements CS-2301 D-term Concatenated If-else Statements if ( expr 1 ) statement 1 /*do this if expr 1 is non-zero*/ else if ( expr 2 ) statement 2 /*i.e., expr 1 == 0, expr 2 != 0*/ else if ( expr 3 ) statement 3 /expr 1 and expr 2 are zero, expr 3 != 0*/ else if ( expr 4 ) statement 4 /expr 1, expr 2, expr 3 all zero, expr 4 != 0*/ else statement 5 /*i.e., all expr are zero*/

Conditionals, Loops, and Other Statements CS-2301 D-term Concatenated If-else Statements Last else is always attached to last if If it should be attached to any other if, use {} to control the flow of execution.

Conditionals, Loops, and Other Statements CS-2301 D-term Switch Statement Somewhat like a concatenated if-else Occasionally easier to read Each arm is called a case Evaluate switch expression, select the appropriate case (if any) –default case is optional Difference from concatenated if-else Need break statement to exit switch after a case Otherwise, control falls through to next case See §3.4 and p. 59

Conditionals, Loops, and Other Statements CS-2301 D-term Switch Statement Example int month, daysInMonth, leapYear; … switch (month) { case 0: printf("January\n"); daysInMonth = 31; break; case 1: printf("February\n"); daysInMonth = leapYear ? 29 : 28; break; case 2: printf("March\n"); daysInMonth = 31; break; case 3: printf("April\n"); daysInMonth = 30; break; … }// switch

Conditionals, Loops, and Other Statements CS-2301 D-term Switch Statement Example int month, daysInMonth, leapYear; … switch (month) { case 0: printf("January\n"); daysInMonth = 31; break; case 1: printf("February\n"); daysInMonth = leapYear ? 29 : 28; break; case 2: printf("March\n"); daysInMonth = 31; break; case 3: printf("April\n"); daysInMonth = 30; break; … }// switch case values must be constants break statement needed to jump over subsequent cases default case is optional (not shown)

Conditionals, Loops, and Other Statements CS-2301 D-term Questions?

Conditionals, Loops, and Other Statements CS-2301 D-term Iterative Statement while loop for loop do-while loop

Conditionals, Loops, and Other Statements CS-2301 D-term while loops while ( expression ) statement Evaluate expression If true, execute statement and then repeat Repeat until expression becomes false statement may be executed zero or more times! Often a compound statement

Conditionals, Loops, and Other Statements CS-2301 D-term int sum = 0; int count = 0; int input; while (scanf("%d", &input) != EOF){ sum += input; count++; printf("Input value of %f recorded.\n", input);... } if (count > 0) printf("Average is %f\n", (double)sum/count); else printf("No inputs recorded\n"); while loop example Note initialization of sum and count What is this?

Conditionals, Loops, and Other Statements CS-2301 D-term while loop examples (continued) Study example on p. 59 (§3.4) A program to count digits, white space characters, and other characters. Includes a while loop with a switch statement inside

Conditionals, Loops, and Other Statements CS-2301 D-term do-while loop do statement while ( expression ); Similar to while loop, but guaranteed to execute statement at least once See §3.6 Note: semicolon is required here

Conditionals, Loops, and Other Statements CS-2301 D-term Breaking out of a Loop When it becomes necessary to terminate a loop prematurely –break; /*exits smallest containing switch or loop*/ When it becomes necessary to terminate the current iteration and start the next one –continue; /*terminates this iteration only*/ See p. 65, §3.7

Conditionals, Loops, and Other Statements CS-2301 D-term Questions?

Conditionals, Loops, and Other Statements CS-2301 D-term for loop A counting loop for (expr 1 ; expr 2 ; expr 3 ) statement Evaluate expr 1 to initialize Evaluate expr 2 to test If true, execute statement If not true, exit for loop Evaluate expr 3 to prepare for next iteration Repeat expr 2 to test Remember: zero is false, non-zero is true

Conditionals, Loops, and Other Statements CS-2301 D-term for loops and while loops The for loop for (expr 1 ; expr 2 ; expr 3 ) statement is exactly equivalent to the following expr 1 ; while (expr 2 ) { statement expr 3 ; } See p. 60

Conditionals, Loops, and Other Statements CS-2301 D-term The most common kind of for -loop int i; for (i = 0; i < limit; i++) {...; /* do something with ith entity */...; } Loop “body” is typically a compound statement

Conditionals, Loops, and Other Statements CS-2301 D-term The most common kind of for -loop int i; for (i = 0; i < limit; i++) {...; /* do something with ith entity */...; } It is traditional in C that for - loops start counting at zero and test that the counter is less than the upper limit

Conditionals, Loops, and Other Statements CS-2301 D-term The most common kind of for -loop int i; for (i = 0; i < limit; i++) {...; /* do something with ith entity */...; } This loop iterates limit times. –Iterations are numbered i = 0, 1, 2, …, limit -1 Reason:– arrays are indexed this way!

Conditionals, Loops, and Other Statements CS-2301 D-term Nested for -loops int i, j; for (i = 0; i < limit; i++) {...;/*prepare subgroup i*/ for (j=0; j < limit2; j++) {...; /* do something with item j of subgroup i*/...; }...; }

Conditionals, Loops, and Other Statements CS-2301 D-term An Extension in Modern C Compilers The following construct (not in book) is legal in C99:– for (int i = 0; i < limit; i++){ expression involving i;...; printf(“Iteration %d completed.\n”, i);...; } The loop counter i is declared in for loop Not visible outside of loop! Common practice Good programming style

Conditionals, Loops, and Other Statements CS-2301 D-term Notes on Loop Style for (int i = 0; i < limit; i++) {...;/*prepare for subgroup i*/ for (int j=0; j < limit2; j++) {...; /* do something with item j of subgroup i*/...; }/* end of loop j */...; } /* end of loop i */ Declare loop variables in for -statements – C99

Conditionals, Loops, and Other Statements CS-2301 D-term Notes on Loop Style for (int i = 0; i < limit; i++) {...;/*prepare for subgroup i*/ for (int j=0; j < limit2; j++) {...; /* do something with item j of subgroup i*/...; }/* end of loop j */...; } /* end of loop i */ Include a comment at end of each loop to show which loop it is

Conditionals, Loops, and Other Statements CS-2301 D-term Questions?

Conditionals, Loops, and Other Statements CS-2301 D-term An Example int startingDay; /* init from user input*/ for (int month = 0; month < 12; month++) { }// for month

Conditionals, Loops, and Other Statements CS-2301 D-term An An Example (continued) int startingDay; /* init from user input*/ for (int month = 0; month < 12; month++) { }// for month This variable is “global” to the loop. I.e., it is remembered from one iteration to the next.

Conditionals, Loops, and Other Statements CS-2301 D-term An Example (continued) int startingDay; /* init from user input*/ for (int month = 0; month < 12; month++) { }// for month At beginning of each iteration, startingDay indicates the day of the week on which that particular month starts. It is the responsibility of the loop to update startingDay for the next month.

Conditionals, Loops, and Other Statements CS-2301 D-term Definition – Loop Invariant Something that is true at a certain point of each iteration of the loop Usually at the start E.g., a relationship of the variables Often expressed as a logical statement called an assertion Needs to be preserved from one iteration to the next Does not necessarily remain true within the loop, but only at the specific point each time through

Conditionals, Loops, and Other Statements CS-2301 D-term An Example (continued) int startingDay; /* init from user input*/ for (int month = 0; month < 12; month++) { const int daysInMonth = …; /* set # of days */ int dayOfWeek = 0; printf(…); //month name printf(…); //days of week }// for month

Conditionals, Loops, and Other Statements CS-2301 D-term An Example (continued) int startingDay; /* init from user input*/ for (int month = 0; month < 12; month++) { const int daysInMonth = …; /* set # of days */ int dayOfWeek; printf(…); //month name printf(…); //days of week for (dayOfWeek = 0; dayOfWeek<startingDay; dayOfWeek++) printf(/*blanks*/); }// for month

Conditionals, Loops, and Other Statements CS-2301 D-term An Example (continued) int startingDay; /* init from user input*/ for (int month = 0; month < 12; month++) { const int daysInMonth = …; /* set # of days */ int dayOfWeek; printf(…); //month name printf(…); //days of week for (dayOfWeek = 0; dayOfWeek<startingDay; dayOfWeek++) printf(/*blanks*/); }// for month Note that dayOfWeek is global to this loop. It is remembered outside this inner loop.

Conditionals, Loops, and Other Statements CS-2301 D-term An Example (continued) int startingDay; /* init from user input*/ for (int month = 0; month < 12; month++) { const int daysInMonth = …; /* set # of days */ int dayOfWeek; printf(…); //month name printf(…); //days of week for (dayOfWeek = 0; dayOfWeek<startingDay; dayOfWeek++) printf(/*blanks*/); }// for month What is the loop invariant associated with this loop?

Conditionals, Loops, and Other Statements CS-2301 D-term An Example (continued) int startingDay; /* init from user input*/ for (int month = 0; month < 12; month++) { const int daysInMonth = …; /* set # of days */ int dayOfWeek; printf(…); //month name printf(…); //days of week for (dayOfWeek = 0; dayOfWeek<startingDay; dayOfWeek++) printf(/*blanks*/); for (int date = 1; date <= daysInMonth; date++){ }// for date }// for month

Conditionals, Loops, and Other Statements CS-2301 D-term An Example (continued) int startingDay; /* init from user input*/ for (int month = 0; month < 12; month++) { const int daysInMonth = …; /* set # of days */ int dayOfWeek; printf(…); //month name printf(…); //days of week for (dayOfWeek = 0; dayOfWeek<startingDay; dayOfWeek++) printf(/*blanks*/); for (int date = 1; date <= daysInMonth; date++){ }// for date }// for month What should the loop invariant be for this loop? Why?

Conditionals, Loops, and Other Statements CS-2301 D-term An Example (continued) int startingDay; /* init from user input*/ for (int month = 0; month < 12; month++) { const int daysInMonth = …; /* set # of days */ int dayOfWeek; printf(…); //month name printf(…); //days of week for (dayOfWeek = 0; dayOfWeek<startingDay; dayOfWeek++) printf(/*blanks*/); for (int date = 1; date <= daysInMonth; date++){ printf("…", date); if (++dayOfWeek>=7) { printf("\n"); dayOfWeek = 0; }; }// for date }// for month

Conditionals, Loops, and Other Statements CS-2301 D-term An Example (continued) int startingDay; /* init from user input*/ for (int month = 0; month < 12; month++) { const int daysInMonth = …; /* set # of days */ int dayOfWeek; printf(…); //month name printf(…); //days of week for (dayOfWeek = 0; dayOfWeek<startingDay; dayOfWeek++) printf(/*blanks*/); for (int date = 1; date <= daysInMonth; date++){ printf(“…”, date); if (dayOfWeek++>=7) { printf(“\n”); dayOfWeek = 0; }; }// for date }// for month Is loop invariant preserved by this loop? Why?

Conditionals, Loops, and Other Statements CS-2301 D-term An Example (continued) int startingDay; /* init from user input*/ for (int month = 0; month < 12; month++) { const int daysInMonth = …; /* set # of days */ int dayOfWeek; printf(…); //month name printf(…); //days of week for (dayOfWeek = 0; dayOfWeek<startingDay; dayOfWeek++) printf(/*blanks*/); for (int date = 1; date <= daysInMonth; date++){ printf(“…”, date); if (dayOfWeek++>=7) { printf(“\n”); dayOfWeek = 0; }; }// for date if (dayOfWeek != 0) printf(“\n”); }// for month What about the original loop invariant for this loop?

Conditionals, Loops, and Other Statements CS-2301 D-term An Example (concluded) int startingDay; /* init from user input*/ for (int month = 0; month < 12; month++) { const int daysInMonth = …; /* set # of days */ int dayOfWeek; printf(…); //month name printf(…); //days of week for (dayOfWeek = 0; dayOfWeek<startingDay; dayOfWeek++) printf(/*blanks*/); for (int date = 1; date <= daysInMonth; date++) { printf(“…”, date); if (++dayOfWeek >= 7){ printf(“\n”); dayOfWeek = 0; }; }// for date if (dayOfWeek !=0) printf(“\n”); startingDay = dayOfWeek; }// for month

Conditionals, Loops, and Other Statements CS-2301 D-term Questions?