CS1010 Programming Methodology

Slides:



Advertisements
Similar presentations
CS1010 Programming Methodology
Advertisements

CHAPTER 5: LOOP STRUCTURES Introduction to Computer Science Using Ruby (c) 2012 Ophir Frieder et al.
Chapter 5: Control Structures II (Repetition)
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
 Decision making statements Decision making statements if statement if...else statement Nested if...else statement (if...elseif....else Statement) 
Algorithms and Computing Lecture 3 Control Statements By Dr. M. Tahir Khaleeq.
CHAPTER 5: CONTROL STRUCTURES II INSTRUCTOR: MOHAMMAD MOJADDAM.
Lecture 10: Reviews. Control Structures All C programs written in term of 3 control structures Sequence structures Programs executed sequentially by default.
CS1010: Programming Methodology
Repetitive Structures BBS514 Structured Programming (Yapısal Programlama)1.
WEEK 4 Class Activities Lecturer’s slides.
1 Flowchart notation and loops Implementation of loops in C –while loops –do-while loops –for loops Auxiliary Statements used inside the loops –break –continue.
Chapter 5: Control Structures II (Repetition). Objectives In this chapter, you will: – Learn about repetition (looping) control structures – Learn how.
Control Structures II (Repetition). Objectives In this chapter you will: Learn about repetition (looping) control structures Explore how to construct.
1. Agenda for loop Short-handed notation How to use break and continue 2.
Lecture 4: Calculating by Iterating. The while Repetition Statement Repetition structure Programmer specifies an action to be repeated while some condition.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Chapter 5: Structured Programming
Repetition. Control of Flow SEQUENCE SELECTION (if..else, switch…case) REPETITION.
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.
CSCI 171 Presentation 5. The while loop Executes a block as long as the condition is true general form: while (condition) { statement 1; statement 2;
Think Possibility 1 Iterative Constructs ITERATION / LOOPS C provides three loop structures: the for-loop, the while-loop, and the do-while-loop. Each.
Beginning C For Engineers Fall 2005 Lecture 3: While loops, For loops, Nested loops, and Multiple Selection Section 2 – 9/14/05 Section 4 – 9/15/05 Bettina.
IT CS 200: R EPEATATION Lect. Napat Amphaiphan. T HE ABILITY TO DO THE SAME TASK AGAIN BY AGAIN UNTIL THE CONDITION IS MET LOOP 2.
Sesi 0607EKT120/4 Computer Programming Week 5 – Repetition / Loops.
Problem Solving and Program Design in C Chap. 5 Repetition and Loop Statement Chow-Sing Lin.
CHAPTER 4 REPETITION STRUCTURES 1 st semester King Saud University College of Applied studies and Community Service Csc 1101 A.AlOsaimi.
CS1010 Programming Methodology
Chapter 5: Structured Programming
CSE 220 – C Programming Loops.
Chapter 4 Repetition Statements (loops)
REPETITION CONTROL STRUCTURE
EKT120 COMPUTER PROGRAMMING
EKT150 INTRODUCTION TO COMPUTER PROGRAMMING
CS1010 Programming Methodology
Lecture 7: Repeating a Known Number of Times
C Program Controls + Flow Structure
Chapter 5: Control Structures II
Loop Structures.
Lecture 4 - Loops UniMAP EKT120 Sem 1 08/09.
Week 4 – Repetition Structures / Loops
Control Structures II (Repetition)
Chapter 2.2 Control Structures (Iteration)
Computer Science 101 While Statement.
2008/10/22: Lecture 12 CMSC 104, Section 0101 John Y. Park
Chapter 5: Control Structures II
Control Structures Lecture 7.
Looping.
Outline Altering flow of control Boolean expressions
CS1100 Computational Engineering
2008/10/22: Lecture 12 CMSC 104, Section 0101 John Y. Park
Exam 1 Date: Feb. 2nd, 2015 during class time (50 minutes) Coverage
3 Control Statements:.
CSC215 Lecture Control Flow.
CMPT 102 Introduction to Scientific Computer Programming
Chapter 6: Repetition Statements
Repetition and Loop Statements
UMBC CMSC 104 – Section 01, Fall 2016
REPETITION STATEMENTS
More Loops Topics Counter-Controlled (Definite) Repetition
More Loops Topics Counter-Controlled (Definite) Repetition
ECE 103 Engineering Programming Chapter 18 Iteration
More Loops Topics Counter-Controlled (Definite) Repetition
More Loops Topics Counter-Controlled (Definite) Repetition
More Loops Topics Counter-Controlled (Definite) Repetition
CSC215 Lecture Control Flow.
More Loops Topics Counter-Controlled (Definite) Repetition
ICS103: Programming in C 5: Repetition and Loop Statements
More Loops Topics Counter-Controlled (Definite) Repetition
Presentation transcript:

CS1010 Programming Methodology http://www.comp.nus.edu.sg/~cs1010/ UNIT 6 Repetition Statements

Unit 6: Repetition Statements CS1010 Programming Methodology © NUS CS1010 (AY2014/5 Semester 1) Unit 6: Repetition Statements Objectives: Using repetition structure to repeat some action until a terminating condition is reached Using different types of repetition structure Reference: Chapter 4 Lessons 4.7 – 4.11

Unit 6: Repetition Statements (1/2) CS1010 Programming Methodology © NUS CS1010 (AY2014/5 Semester 1) Unit 6: Repetition Statements (1/2) Loops! The while loop 2.1 Demo 2.2 Loop Condition 2.3 Style: Indentation The do-while loop The for loop Example: Odd Integers Common Errors Some Notes of Caution

Unit 6: Repetition Statements (2/2) CS1010 Programming Methodology © NUS CS1010 (AY2014/5 Semester 1) Unit 6: Repetition Statements (2/2) Using break in Loop Using continue in Loop

Recall: Control Structures CS1010 Programming Methodology © NUS CS1010 (AY2014/5 Semester 1) Recall: Control Structures Sequence Selection if-else, switch Repetition

CS1010 Programming Methodology © NUS CS1010 (AY2014/5 Semester 1) 1. LOOPS! (1/2) “A program without a loop and a structure variable isn’t worth writing.” Alan J.Perlis Yale University The first recipient of ACM Turing Award A loop is a statement whose job is to repeatedly execute some other statement(s).

CS1010 Programming Methodology © NUS CS1010 (AY2014/5 Semester 1) 1. LOOPS! (2/2) Each round of the loop is called an iteration. Loop condition cond? Some statement(s) true false loop body

CS1010 Programming Methodology © NUS CS1010 (AY2014/5 Semester 1) 1. Loop: Demo (1/3) Enter a number: 12 You entered: 12 Enter a number: 0 You entered: 0 Enter a number: 26 You entered: 26 Enter a number: 5 You entered: 5 Enter a number: -1 Keep prompting the user to input a non-negative integer, and output that integer. Halt the loop when the input is negative. Key observations: You keep repeating a task while certain condition is met, or alternatively, you repeat until the condition is not met. You do not know beforehand how many iterations there will be.

CS1010 Programming Methodology © NUS CS1010 (AY2014/5 Semester 1) 1. Loop: Demo (2/3) Algorithm: read num if (num >= 0) { print the value entered } else end input request print the value entered read num .... Enter a number: 12 You entered: 12 Enter a number: 0 You entered: 0 Enter a number: 26 You entered: 26 Enter a number: 5 You entered: 5 Enter a number: -1 condition Same code repeated body

CS1010 Programming Methodology © NUS CS1010 (AY2014/5 Semester 1) 1. Loop: Demo (3/3) #include <stdio.h> int main(void) { int num; printf("Enter a number: "); scanf("%d", &num); while (num >= 0) { printf("You entered: %d\n", num); } return 0; Unit6_ReadandPrint.c num >= 0? printf … scanf … true false

CS1010 Programming Methodology © NUS CS1010 (AY2014/5 Semester 1) 2. The while Loop cond? Loop body true false while ( condition ) { // loop body } If condition is true, execute loop body; otherwise, terminate loop.

2.1 The while Loop: Demo (1/3) CS1010 Programming Methodology © NUS CS1010 (AY2014/5 Semester 1) 2.1 The while Loop: Demo (1/3) Keep prompting the user to input a non- negative integer, and print that integer. Halt the loop when the input is negative. Print the maximum integer input. Enter a number: 12 Enter a number: 0 Enter a number: 26 Enter a number: 5 Enter a number: -1 The maximum number is 26

2.1 The while Loop: Demo (2/3) CS1010 Programming Methodology © NUS CS1010 (AY2014/5 Semester 1) 2.1 The while Loop: Demo (2/3) maxi = 0; read num; if (num >= 0) { if (maxi < num) maxi = num; } else stop; ... print maxi; maxi = 0; read num; while (num >= 0) { if (maxi < num) maxi = num; } print maxi;

2.1 The while Loop: Demo (3/3) CS1010 Programming Methodology © NUS CS1010 (AY2014/5 Semester 1) 2.1 The while Loop: Demo (3/3) #include <stdio.h> int main(void) { int num, maxi = 0; printf("Enter a number: "); scanf("%d", &num); while (num >= 0) { if (maxi < num) { maxi = num; } prinf("The maximum number is %d\n", maxi); return 0; Unit6_FindMax.c

2.2 Condition for while Loop: (1/2) CS1010 Programming Methodology © NUS CS1010 (AY2014/5 Semester 1) 2.2 Condition for while Loop: (1/2) // pseudo-code a = 2; b = 7; while (a == b) { print a; a = a + 2; } Output: ? When the loop condition is always false, the loop body is not executed.

2.2 Condition for while Loop: (2/2) CS1010 Programming Methodology © NUS CS1010 (AY2014/5 Semester 1) 2.2 Condition for while Loop: (2/2) // pseudo-code a = 2; b = 7; while (a != b) { print a; a = a + 2; } 2 4 6 8 10 : Output: ? Ctrl-c to interrupt When the loop condition is always true, the loop body is executed forever – infinite loop.

2.3 Style: Indentation for while Loop CS1010 Programming Methodology © NUS CS1010 (AY2014/5 Semester 1) 2.3 Style: Indentation for while Loop Loop body must be indented. Comment in loop body must be aligned with statements in loop body. Closing brace must be on a line by itself and aligned with the while keyword. while (cond) { // loop body statement-1; statement-2; ... } while (cond) { // loop body statement-1; statement-2; ... } or while (cond) { // loop body statement-1; ... } while (cond) { // loop body statement-1; statement-2; } No indentation!

CS1010 Programming Methodology © NUS CS1010 (AY2014/5 Semester 1) 3. The do-while Loop (1/3) do { // loop body } while ( condition ); Execute loop body at least once. cond? Loop body true false

CS1010 Programming Methodology © NUS CS1010 (AY2014/5 Semester 1) 3. The do-while Loop (2/3) do { // loop body } while ( condition ); Example: Count the number of digits in an integer. // Precond: n > 0 int count_digits(int n) { int counter = 0; do { counter++; n /= 10; } while (n > 0); return counter; } Unit6_CountDigits.c

CS1010 Programming Methodology © NUS CS1010 (AY2014/5 Semester 1) 3. The do-while Loop (3/3) Style: similar to while loop do { // loop body statement-1; statement-2; } while (cond); or do { // loop body statement-1; statement-2; } while (cond); do { // loop body statement-1; statement-2; } while (cond); No indentation!

CS1010 Programming Methodology © NUS CS1010 (AY2014/5 Semester 1) 4. The for Loop (1/2) for ( initialization; condition; update ) { // loop body } Initialization: initialize the loop variable Condition: repeat loop while the condition on loop variable is true Update: change value of loop variable

CS1010 Programming Methodology © NUS CS1010 (AY2014/5 Semester 1) 4. The for Loop (2/2) Example: Print numbers 1 to 10 int n; for (n=1; n<=10; n++) { printf("%3d", n); } Steps: n=1; if (n<=10) { printf(…); n++; Go to step 2 } Exit the loop

5. Example: Odd Integers (1/2) CS1010 Programming Methodology © NUS CS1010 (AY2014/5 Semester 1) 5. Example: Odd Integers (1/2) #include <stdio.h> void print_odd_integers(int); int main(void) { int num; printf("Enter a positive integer: "); scanf("%d", &num); print_odd_integers(num); return 0; } // Precond: n > 0 void print_odd_integers(int n) { int i; for (i=1; i<=n; i+=2) printf("%d ", i); printf("\n"); Unit6_OddIntegers_v1.c

5. Example: Odd Integers (2/2) CS1010 Programming Methodology © NUS CS1010 (AY2014/5 Semester 1) 5. Example: Odd Integers (2/2) // Precond: n > 0 void print_odd_integers(int n) { int i; for (i=1; i<=n; i++) if (i%2 != 0) printf("%d ", i); printf("\n"); } Unit6_OddIntegers_v2.c // Precond: n > 0 void print_odd_integers(int n) { for ( ; n > 0; n--) if (n%2 != 0) printf("%d ", n); printf("\n"); } Unit6_OddIntegers_v3.c Values printed from largest to smallest. Empty statement

CS1010 Programming Methodology © NUS CS1010 (AY2014/5 Semester 1) 6. Common Errors (1/2) What are the outputs for the following programs? (Do not code and run them. Trace the programs manually.) We will discuss this in class. int i; for (i=0; i<10; i++); printf("%d\n", i); Unit6_CommonErrors1.c int i = 0; while (i<10); { printf("%d\n", i); i++; } Unit6_CommonErrors2.c

CS1010 Programming Methodology © NUS CS1010 (AY2014/5 Semester 1) 6. Common Errors (2/2) int z = 3; while (z = 1) { printf("z = %d\n", z); z = 99; } Unit6_CommonErrors3.c Off-by-one error; make sure the loop repeats exactly the correct number of iterations. Make sure the loop body contains a statement that will eventually cause the loop to terminate. Using ‘=’ where it should be ‘==’ Putting ‘;’ where it should not be (just like for the ‘if’ statement)

7. Some Notes of Caution (1/2) CS1010 Programming Methodology © NUS CS1010 (AY2014/5 Semester 1) 7. Some Notes of Caution (1/2) Involving real numbers Trace the program manually without running it. double one_seventh = 1.0/7.0; double f = 0.0; while (f != 1.0) { printf("%f\n", f); f += one_seventh; } Unit6_Caution1.c

7. Some Notes of Caution (2/2) CS1010 Programming Methodology © NUS CS1010 (AY2014/5 Semester 1) 7. Some Notes of Caution (2/2) Involving ‘wrap-around; Trace the program manually without running it. int a = 2147483646; int i; for (i=1; i<=5; i++) { printf("%d\n", a); a++; } Unit6_Caution2.c

CS1010 Programming Methodology © NUS CS1010 (AY2014/5 Semester 1) 8. Using break in Loop (1/4) You have seen break’in switch statement break can also be used in a loop Test out Unit6_BreakInLoop.c

CS1010 Programming Methodology © NUS CS1010 (AY2014/5 Semester 1) 8. Using break in Loop (2/4) Without 'break': 1 Ya 2 3 4 5 // without 'break' printf ("Without 'break':\n"); for (i=1; i<=5; i++) { printf("%d\n", i); printf("Ya\n"); } // with 'break' printf ("With 'break':\n"); for (i=1; i<=5; i++) { printf("%d\n", i); if (i==3) break; printf("Ya\n"); } With 'break': 1 Ya 2 3

CS1010 Programming Methodology © NUS CS1010 (AY2014/5 Semester 1) 8. Using break in Loop (3/4) With ... 1, 1 Ya 1, 2 1, 3 2, 1 2, 2 2, 3 3, 1 3, 2 3, 3 // with 'break' in a nested loop printf("With 'break' in a nested loop:\n"); for (i=1; i<=3; i++) { for (j=1; j<=5; j++) { printf("%d, %d\n", i, j); if (j==3) break; printf("Ya\n"); } In a nested loop, break only breaks out of the inner-most loop that contains it.

CS1010 Programming Methodology © NUS CS1010 (AY2014/5 Semester 1) 8. Using break in Loop (4/4) Use break sparingly, because it violates the one-entry- one-exit control flow. A loop with break can be rewritten into one without break. // without break int n, i = 1, sum = 0; int isValid = 1; while ((i <= 5) && isValid){ scanf("%d", &n); if (n < 0) isValid = 0; else { sum += n; i++; } // with break int n, i = 1, sum = 0; while (i <= 5) { scanf("%d", &n); if (n < 0) break; sum += n; i++; }

9. Using continue in Loop (1/3) CS1010 Programming Methodology © NUS CS1010 (AY2014/5 Semester 1) 9. Using continue in Loop (1/3) Test out Unit6_ContinueInLoop.c continue is used even less often than break

9. Using continue in Loop (2/3) CS1010 Programming Methodology © NUS CS1010 (AY2014/5 Semester 1) 9. Using continue in Loop (2/3) Without 'continue': 1 Ya 2 3 4 5 // without 'continue' printf ("Without 'continue':\n"); for (i=1; i<=5; i++) { printf("%d\n", i); printf("Ya\n"); } With 'continue': 1 Ya 2 3 4 5 // with 'continue' printf ("With 'continue':\n"); for (i=1; i<=5; i++) { printf("%d\n", i); if (i==3) continue; printf("Ya\n"); } The rest of the loop body is skipped if (i==3), and continue to next iteration.

9. Using continue in Loop (3/3) CS1010 Programming Methodology © NUS CS1010 (AY2014/5 Semester 1) 9. Using continue in Loop (3/3) With ... 1, 1 Ya 1, 2 1, 3 1, 4 1, 5 2, 1 2, 2 2, 3 2, 4 2, 5 // with 'continue' in a nested loop printf("With 'continue' in a nested loop:\n"); for (i=1; i<=3; i++) { for (j=1; j<=5; j++) { printf("%d, %d\n", i, j); if (j==3) continue; printf("Ya\n"); } 3, 1 Ya 3, 2 3, 3 3, 4 3, 5 In a nested loop, continue only skips to the next iteration of the inner-most loop that contains it.

CS1010 Programming Methodology © NUS CS1010 (AY2014/5 Semester 1) Summary In this unit, you have learned about The use of if-else construct and switch construct to alter program flow The use of relational and logical operators Style issues such as indentation, naming of boolean flags and replacing if statement with an assignment statement The use of break and continue in a loop How to test a selection construct with exhaustive test data, and to ensure that all alternative paths in the selection construct are examined

CS1010 Programming Methodology © NUS CS1010 (AY2014/5 Semester 1) End of File