Computer programming Lecture 3.

Slides:



Advertisements
Similar presentations
Lecture 2 Introduction to C Programming
Advertisements

Introduction to C Programming
 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.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 4 – C Program Control Outline 4.1Introduction.
 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.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved The switch Multiple-Selection Statement switch.
Introduction to Computer Programming in c
Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.
Lecture 10: Reviews. Control Structures All C programs written in term of 3 control structures Sequence structures Programs executed sequentially by default.
Lecture 4 C Program Control Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
Program Looping Making Decisions Copyright © 2012 by Yong-Gu Lee
Loops: Handling Infinite Processes CS 21a: Introduction to Computing I First Semester,
Loop Control Structures L11-L14. OBJECTIVES To learn and appreciate the following concept The for Statement Relational Operators Nested for Loops for.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 2 Chapter 2 - Introduction to C Programming.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Flow Control (for) Outline 4.1Introduction 4.2The.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Control Statements I.
+ Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Chapter 5: Looping.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Program Control Outline 4.1Introduction 4.2The Essentials of Repetition 4.3Counter-Controlled.
Computer programming Outline Functions [chap 8 – Kochan] –Defining a Function –Arguments and Local Variables Automatic Local.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
Think Possibility 1 Iterative Constructs ITERATION / LOOPS C provides three loop structures: the for-loop, the while-loop, and the do-while-loop. Each.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 2 - Introduction to C Programming Outline.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 4 Loops.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Copyright 2006 Addison-Wesley Brief Version of Starting Out with C++ Chapter 5 Looping.
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.
1 CSC103: Introduction to Computer and Programming Lecture No 9.
CC213 Programming Applications Week #2 2 Control Structures Control structures –control the flow of execution in a program or function. Three basic control.
Computer C programming Chapter 3. CHAPTER 3 Program Looping –The for Statement –Nested for Loops –for Loop Variants –The while Statement –The do Statement.
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.
Lecture 4b Repeating With Loops
Chapter 4 – C Program Control
REPETITION CONTROL STRUCTURE
Chapter 2 - Introduction to C Programming
Lecture 7: Repeating a Known Number of Times
Quick Test What do you mean by pre-test and post-test loops in C?
Lecture 13 & 14.
Chapter 5: Loops and Files.
Chapter 2.2 Control Structures (Iteration)
Chapter 2 - Introduction to C Programming
Chapter 5: Looping Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
Looping.
Chapter 4 Control structures and Loops
Arrays, For loop While loop Do while loop
Chapter 2 - Introduction to C Programming
Chapter 2 - Introduction to C Programming
Chapter 2 - Introduction to C Programming
Structured Program
Chapter 6 Decision Making and Looping
Chapter 4 - Program Control
Chapter 3 - Structured Program Development
3 Control Statements:.
Chapter 2.2 Control Structures (Iteration)
Chapter 3 - Structured Program Development
Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.
Chapter 2 - Introduction to C Programming
Building Java Programs
Chapter 2 - Introduction to C Programming
Chapter 4 - Program Control
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Based on slides created by Bjarne Stroustrup & Tony Gaddis
More Loops Topics Relational Operators Logical Operators for Loops.
Introduction to C Programming
ICS103: Programming in C 5: Repetition and Loop Statements
Presentation transcript:

Computer programming Lecture 3

Lecture 3: Outline Program Looping [Kochan – chap.5] The for Statement Relational Operators Nested for Loops Increment Operator Program Input 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 Forms of controlling the program flow: Executing a sequence of statements Repeating a sequence of statements (until some condition is met) (looping) Using a test to decide between alternative sequences (branching)

The need for program looping Example problem: computing triangular numbers. (The n-th triangular number is the sum of the integers from 1 through n) #include <stdio.h> int main (void) { int triangularNumber; triangularNumber = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8; 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 ? Program looping: enables you to develop concise programs containing repetitive processes that could otherwise require many lines of code ! In C: 3 different statements for looping: for, while, do

Example - for /* Program to calculate the 200th triangular number Introduction of the for statement */ #include <stdio.h> 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; }

Print triangularNumber Example - for Statement before loop triangularNumber = 0 init_expression n=1 n<=200 no loop_condition yes statement triangularNumber = triangularNumber + n n=n+1 loop_expression Print triangularNumber Statement after loop

The for statement for ( init_expression; loop_condition; loop_expression ) program statement init_expression 1 loop_condition no 5 2 yes 3 Program statement Loop expression 4

The for statement for ( n = 1; n <= 200; n = n + 1 ) no for ( n = 1; n <= 200; n = n + 1 ) triangularNumber = triangularNumber + n; 2 5 4 1 yes 3

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.

Perhaps there is some carelessness error? Infinite loops It’s the task of the programmer to design correctly the algorithms so that loops end at some moment ! // Program to count 1+2+3+4+5 #include <stdio.h> 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? Perhaps there is some carelessness error?

Relational operators Operator Meaning == Is equal to != Is not equal to < Is less than <= Is less or equal > Is greater than >= Is greater or equal The relational operators have lower precedence than all arithmetic operators: a < b + c is evaluated as a < (b + c) ATTENTION ! Do not confuse: the “is equal to” operator == and the “assignment” operator = ATTENTION when comparing floating-point values ! Only < and > comparisons make sense !

Example – for with a body of 2 // Program to generate a table of triangular numbers #include <stdio.h> 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

Increment operator Because addition by 1 is a very common operation in programs, a special operator was created in C for this. Increment operator: the expression ++n is equivalent to the expression n = n + 1. Decrement operator: the expression --n is equivalent to n = n – 1 Increment and decrement operators can be placed in front (prefix) or after (postfix) their operand. The difference between prefix and postfix: can be noticed only in certain cases: Example: if n=4: a=n++ leads to a=4, n=5 // a = n++ a=++n leads to a=5, n=5 // a = ++n 1 2 2 1

Program input #include <stdio.h> 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; } It’s polite to display a message before Reads integer from keyboard 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 !

Remember indentations! Nested loops #include <stdio.h> 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++ )

Example while #include <stdio.h> int main (void) { int count = 1; while ( count <= 5 ) { printf ("%i\n", count); ++count; } return 0;

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 Loop with the test in the beginning ! Body might newer be executed ! Loop_expression no yes statement

Example - while /* Program to find the greatest common divisor of two nonnegative integer values */ #include <stdio.h> 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 - while // Program to reverse the digits of a number #include <stdio.h> 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;

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

Example – do while // Program to reverse the digits of a number #include <stdio.h> 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 !

Statements break and continue 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 }

Statements break and continue 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… // If answer was 1 these statements are // not executed. They are skipped. // Go straight to the beginning of while }