Computer C programming Chapter 3. CHAPTER 3 Program Looping –The for Statement –Nested for Loops –for Loop Variants –The while Statement –The do Statement.

Slides:



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

Solving Problems with Repetition. Objectives At the end of this topic, students should be able to: Correctly use a while statement in a C# program Correctly.
Introduction to Computing Science and Programming I
 2000 Prentice Hall, Inc. All rights reserved. Chapter 2 - Introduction to C Programming Outline 2.1Introduction 2.2A Simple C Program: Printing a Line.
Dr. Yang, Qingxiong (with slides borrowed from Dr. Yuen, Joe) LT4: Control Flow - Loop CS2311 Computer Programming.
Computer programming Lecture 3. Lecture 3: Outline Program Looping [Kochan – chap.5] –The for Statement –Relational Operators –Nested for Loops –Increment.
1 Loops. 2 Often we want to execute a block of code multiple times. Something is always different each time through the block. Typically a variable is.
Computer Science 1620 Loops.
Iteration This week we will learn how to use iteration in C++ Iteration is the repetition of a statement or block of statements in a program. C++ has three.
CS 106 Introduction to Computer Science I 02 / 12 / 2007 Instructor: Michael Eckmann.
Chapter 5: Control Structures II (Repetition)
CS1061: C Programming Lecture 8: Repetition A. O’Riordan, 2004.
Chapter 5: Control Structures II (Repetition)
Introduction to Computer Programming in c
Control Structures - Repetition Chapter 5 2 Chapter Topics Why Is Repetition Needed The Repetition Structure Counter Controlled Loops Sentinel Controlled.
Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.
CHAPTER 5: CONTROL STRUCTURES II INSTRUCTOR: MOHAMMAD MOJADDAM.
1 Chapter 9 Additional Control Structures Dale/Weems/Headington.
Program Looping Making Decisions Copyright © 2012 by Yong-Gu Lee
Loops: Handling Infinite Processes CS 21a: Introduction to Computing I First Semester,
Lecture 8: Choosing the Correct Loop. do … while Repetition Statement Similar to the while statement Condition for repetition only tested after the body.
Loop Control Structures L11-L14. OBJECTIVES To learn and appreciate the following concept The for Statement Relational Operators Nested for Loops for.
Copyright © Nancy Acemian 2004 For Loops-Break-Continue COMP For loop is a counter controlled loop. For loop is a pretest loop. Used when number.
Additional Control Structures. Chapter 9 Topics Switch Statement for Multi-way Branching Do-While Statement for Looping For Statement for Looping Using.
1 Chapter 9 Additional Control Structures Dale/Weems.
1 Additional Control Structures. 2 Chapter 9 Topics  Switch Statement for Multi-way Branching  Do-While Statement for Looping  For Statement for Looping.
Chapter 7 Additional Control Structures. 2 2 void GetYesOrNo (/* out */ char& response) // Inputs a character from the user // Postcondition: response.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Flow Control (for) Outline 4.1Introduction 4.2The.
Repetition Structures Repetition Structures allow you to write programs that will repeat program steps multiple times. –Also called Loops –Counter controlled.
Computer programming Outline Functions [chap 8 – Kochan] –Defining a Function –Arguments and Local Variables Automatic Local.
CCSA 221 Programming in C CHAPTER 8 – PART 1 WORKING WITH FUNCTIONS 1.
Java™ How to Program, Early Objects Version, 8/e © by Pearson Education, Inc. All Rights Reserved.
Introduction to Loops Iteration Repetition Counting Loops Also known as.
CPS120 Introduction to Computer Science Iteration (Looping)
Repetition Statements (Loops) The do while Loop The last iteration structure in C++ is the do while loop. A do while loop repeats a statement or.
1 do-while Statement 2 Do-While Statement Is a looping control structure in which the loop condition is tested after each iteration of the loop. SYNTAX.
Agenda Perform Quiz #1 (20 minutes) Loops –Introduction / Purpose –while loops Structure / Examples involving a while loop –do/while loops Structure /
Program Looping Why we need loops in our code –Make code concise for repetitive processes When to use loops –Run a block of code repetitively –Process.
Think Possibility 1 Iterative Constructs ITERATION / LOOPS C provides three loop structures: the for-loop, the while-loop, and the do-while-loop. Each.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 4 Loops.
CGS 3460 Program looping n Why we need loop lMake code concise for repetitive processes n When to use loop lRun a block of code repetitively lProcess multiple.
1 1 Additional Control Structures Chapter 9 2 New and Improved... Ways to branch Ways to write loops Understanding the break and continue statements.
1 Programming in C++ Dale/Weems/Headington Chapter 9 Additional Control Structures (Switch, Do..While, For statements)
Chapter Looping 5. The Increment and Decrement Operators 5.1.
BY ILTAF MEHDI (MCS, MCSE, CCNA)1. INSTRUCTOR: ILTAF MEHDI (MCS, MCSE, CCNA, Web Developer) BY ILTAF MEHDI (MCS, MCSE, CCNA)2 Chapter No: 04 “Loops”
LECTURE # 8 : REPETITION STATEMENTS By Mr. Ali Edan.
Chapter 2: Fundamental Programming Structures in Java Adapted from MIT AITI Slides Control Structures.
C Language 1 Program Looping. C Language2 Topics Program looping Program looping Relational operators / expressions Relational operators / expressions.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
CC213 Programming Applications Week #2 2 Control Structures Control structures –control the flow of execution in a program or function. Three basic control.
CONTENTS Loop Statements Parts of a loop Types of Loops Nested Loops
Engineering H192 - Computer Programming Gateway Engineering Education Coalition Lect 10P. 1Winter Quarter Repetition Structures Lecture 10.
Lecture 4b Repeating With Loops
Chapter 4 – C Program Control
CSE 220 – C Programming Loops.
REPETITION CONTROL STRUCTURE
Quick Test What do you mean by pre-test and post-test loops in C?
Chapter 2.2 Control Structures (Iteration)
Looping.
Chapter 4 Control structures and Loops
Chapter 6 Decision Making and Looping
Chapter 2.2 Control Structures (Iteration)
Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.
Lab5 PROGRAMMING 1 Loop chapter4.
UMBC CMSC 104 – Section 01, Fall 2016
Computer programming Lecture 3.
More Loops Topics Counter-Controlled (Definite) Repetition
More Loops Topics Counter-Controlled (Definite) Repetition
More Loops Topics Counter-Controlled (Definite) Repetition
Chapter 4: Loops and Iteration
Presentation transcript:

Computer C programming Chapter 3

CHAPTER 3 Program Looping –The for Statement –Nested for Loops –for Loop Variants –The while Statement –The do Statement –The break Statement –The continue Statement

Program Looping Looping: doing one thing over and over Program loop: a set of statements that is executed repetitively for a number of times Simple example: displaying a message 100 times : printf(“hello !\n”); … printf(“hello !\n”); Repeat 100 times printf(“hello !\n”); Program looping: enables you to develop concise programs containing repetitive processes that could otherwise require many lines of code !

The need for program looping #include int main (void) { int triangularNumber; triangularNumber = ; printf ("The eighth triangular number is %i\n", triangularNumber); return 0; } What if we have to compute the 200-th (1000-th, etc) triangular number ? Example problem: computing triangular numbers. (The n-th triangular number is the sum of the integers from 1 through n) In C: 3 different statements for looping: for, while, do

Example – 200 th triangular number n=1 triangularNumber = triangularNumber + n n<=200 n=n+1 yes no triangularNumber = 0 Print triangularNumber Statement before loop init_expression loop_condition statement loop_expression Statement after loop

Example - for /* Program to calculate the 200th triangular number Introduction of the for statement */ #include int main (void) { int n, triangularNumber; triangularNumber = 0; for ( n = 1; n <= 200; n = n + 1 ) triangularNumber = triangularNumber + n; printf ("The 200th triangular number is %i\n", triangularNumber); return 0; }

The for statement for ( init_expression; loop_condition; loop_expression ) program statement init_expression Program statement loop_condition Loop expression yes no

The for statement for ( n = 1; n <= 200; n = n + 1 ) triangularNumber = triangularNumber + n; yes no

How for works The execution of a for statement proceeds as follows: 1. The initial expression is evaluated first. This expression usually sets a variable that will be used inside the loop, generally referred to as an index variable, to some initial value. 2. The looping condition is evaluated. If the condition is not satisfied (the expression is false – has value 0), the loop is immediately terminated. Execution continues with the program statement that immediately follows the loop. 3. The program statement that constitutes the body of the loop is executed. 4. The looping expression is evaluated. This expression is generally used to change the value of the index variable 5. Return to step 2.

Infinite loops It’s the task of the programmer to design correctly the algorithms so that loops end at some moment ! // Program to count #include int main (void) { int i, n = 5, sum =0; for ( i = 1; i <= n; n = n + 1 ){ sum = sum + i; printf (“%i %i %i\n", i, sum, n); } return 0; } What is wrong here ? Does the loop end?

Example – for with a body of 2 // Program to generate a table of triangular numbers #include int main (void) { int n, triangularNumber; printf ("TABLE OF TRIANGULAR NUMBERS\n\n"); printf (" n Sum from 1 to n\n"); printf (" \n"); triangularNumber = 0; for ( n = 1; n <= 10; ++n ) { triangularNumber += n; printf (" %i %i\n", n, triangularNumber); } return 0; } The body of the loop consists in a block of 2 statements

Program input #include int main (void) { int n, number, triangularNumber; printf ("What triangular number do you want? "); scanf ("%i", &number); triangularNumber = 0; for ( n = 1; n <= number; ++n ) triangularNumber += n; printf ("Triangular number %i is %i\n", number, triangularNumber); return 0; } Scanf: similar to printf: first argument contains format characters, next arguments tell where to store the values entered at the keyboard More details -> in a later chapter ! Reads integer from keyboard It’s polite to display a message before

Nested loops #include int main (void) { int n, number, triangularNumber, counter; for ( counter = 1; counter <= 5; ++counter ) { printf ("What triangular number do you want? "); scanf ("%i", &number); triangularNumber = 0; for ( n = 1; n <= number; ++n ) triangularNumber += n; printf ("Triangular number %i is %i\n\n", number, triangularNumber); } return 0; } Remember indentations!

for loop variants Multiple expressions (comma between…) for(i=0, j=10 ; i<j ; i++, j--) Omitting fields (semicolon have to be still…) i=0; for( ; i<10 ; i++ ) Declaring variables for(int i=0 ; i=10 ; i++ )

The while statement while ( expression ) program statement while ( number <= 0 ) { printf (“The number must be >0“); printf (“Give a new number: “); scanf(“%i“, &number); }

The while statement while ( expression ) program statement statement Loop_expression yes no Loop with the test in the beginning ! Body might never be executed !

Example: A program to find the greatest common divisor of two nonnegative integer values …

Example - while /* Program to find the greatest common divisor of two nonnegative integer values */ #include int main (void) { int u, v, temp; printf ("Please type in two nonnegative integers.\n"); scanf ("%i%i", &u, &v); while ( v != 0 ) { temp = u % v; u = v; v = temp; } printf ("Their greatest common divisor is %i\n", u); return 0; }

Example: A program to print out the digits of a number in reverse order …

Example - while // Program to reverse the digits of a number #include int main (void) { int number, right_digit; printf ("Enter your number.\n"); scanf ("%i", &number); while ( number != 0 ) { right_digit = number % 10; printf ("%i", right_digit); number = number / 10; } printf ("\n"); return 0; }

Example – while not quite OK ! // Program to reverse the digits of a number #include int main (void) { int number, right_digit; printf ("Enter your number.\n"); scanf ("%i", &number); while ( number != 0 ) { right_digit = number % 10; printf ("%i", right_digit); number = number / 10; } printf ("\n"); return 0; } What happens if you enter number=0 ?

The do statement do program statement while ( loop_expression ); statement loop_expression yes no Loop with the test at the end ! Body is executed at least once !

Example – do while // Program to reverse the digits of a number #include int main () { int number, right_digit; printf ("Enter your number.\n"); scanf ("%i", &number); do { right_digit = number % 10; printf ("%i", right_digit); number = number / 10; } while ( number != 0 ); printf ("\n"); return 0; }

Which loop to choose ? Criteria: Who determines looping –Entry-condition loop -> for, while –Exit-condition loop -> do Criteria: Number of repetitions: –Indefinite loops ->while –Counting loops -> for In C, you can actually rewrite any while as a for and viceversa !

Example: while vs for #include int main (void) { int count = 1; while ( count <= 5 ) { printf ("%i\n", count); ++count; } return 0; } #include int main (void) { int count; for ( count=1; count<=5; count++ ) { printf ("%i\n", count); } return 0; }

The break Statement Can be used in order to immediately exiting from a loop After a break, following statements in the loop body are skipped and execution continues with the first statement after the loop If a break is executed from within nested loops, only the innermost loop is terminated

The break statement Programming style: don’t abuse break !!!... while ( number != 0 ) { // Statements to do something in loop printf("Stop, answer 1: "); scanf ("%i", &answer); if(answer == 1) break; // very bad idea to do this }

Similar to the break statement, but it does not make the loop terminate, just skips to the next iteration The continue statement

Continue also not so good style!!!... while ( number != 0 ) { // Statements to do something in loop printf(“Skip next statements answer 1: "); scanf ("%i", &answer); if(answer == 1) continue; // not so good idea… // Statements to do something in loop // If answer was 1 these statements are // not executed. They are skipped. // Go straight to the beginning of while }