CPS125 Week 5 - 2.

Slides:



Advertisements
Similar presentations
Week 5: Loops 1.  Repetition is the ability to do something over and over again  With repetition in the mix, we can solve practically any problem that.
Advertisements

Computer Science 1620 Loops.
1 ICS103 Programming in C Lecture 8: Data Files. 2 Outline Why data files? Declaring FILE pointer variables Opening data files for input/output Scanning.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 5, 2005.
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
COMP 110 Introduction to Programming Mr. Joshua Stough September 24, 2007.
11 Chapter 4 LOOPS AND FILES. 22 THE INCREMENT AND DECREMENT OPERATORS To increment a variable means to increase its value by one. To decrement a variable.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Control Statements I.
Agenda Perform Quiz #1 (20 minutes) Loops –Introduction / Purpose –while loops Structure / Examples involving a while loop –do/while loops Structure /
Introduction to Computers and Programming Lecture 7:
Repetition Statements (Loops). 2 Introduction to Loops We all know that much of the work a computer does is repeated many times. When a program repeats.
CISC105 – General Computer Science Class 4 – 06/14/2006.
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 11 GEORGE KOUTSOGIANNAKIS 1 Copyright: 2015 Illinois Institute of Technology_ George Koutsogiannakis.
CC213 Programming Applications Week #2 2 Control Structures Control structures –control the flow of execution in a program or function. Three basic control.
Sesi 0607EKT120/4 Computer Programming Week 5 – Repetition / Loops.
CHAPTER 6: REPETITION AND LOOP STATEMENTS Learning outcomes  Define the concept of repetition structure.  Specify.
Week 3.  TO PRINT NUMBERS FROM 1 TO 20  TO PRINT EVEN NUMBERS FROM 1 TO 20 2.
Chapter 3 Structured Program Development in C Part II C How to Program, 8/e, GE © 2016 Pearson Education, Ltd. All rights reserved.1.
Lesson #5 Repetition and Loops.
Chapter 4: Looping Structures LECTURER : MRS ROHANI HASSAN
REPETITION CONTROL STRUCTURE
CHAPTER 4 REPETITION CONTROL STRUCTURE / LOOPING
EKT120 COMPUTER PROGRAMMING
EKT150 INTRODUCTION TO COMPUTER PROGRAMMING
CHAPTER 6: REPETITION AND LOOP STATEMENTS
CS161 Introduction to Computer Science
Lecture 7: Repeating a Known Number of Times
Lesson #5 Repetition and Loops.
Loop Structures.
Lecture 4 - Loops UniMAP EKT120 Sem 1 08/09.
Week 4 – Repetition Structures / Loops
Quick Test What do you mean by pre-test and post-test loops in C?
Review If you want to display a floating-point number in a particular format use The DecimalFormat Class printf A loop is… a control structure that causes.
Repetition-Counter control Loop
Chapter 4 – Control Structures Part 1
Programming Fundamentals
Chapter 5: Looping Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
Iterations Programming Condition Controlled Loops (WHILE Loop)
Control Structures Lecture 7.
Chapter 4 Control structures and Loops
Chapter 4 LOOPS © Bobby Hoggard, Department of Computer Science, East Carolina University / These slides may not be used or duplicated without permission.
Arrays, For loop While loop Do while loop
Looping and Repetition
Outline Altering flow of control Boolean expressions
Lesson #5 Repetition and Loops.
Introduction to Object-Oriented Programming with Java--Wu
T. Jumana Abu Shmais – AOU - Riyadh
Iteration: Beyond the Basic PERFORM
File I/O in C Lecture 7 Narrator: Lecture 7: File I/O in C.
3 Control Statements:.
The ‘while’ loop ‘round and ‘round we go.
Chapter 6: Repetition Statements
Repetition and Loop Statements
Module 4 Loops and Repetition 2/1/2019 CSE 1321 Module 4.
Week 6 CPS125.
Computer programming Lecture 3.
OBJECT ORIENTED PROGRAMMING I LECTURE 11 GEORGE KOUTSOGIANNAKIS
Lesson #5 Repetition and Loops.
Repetition Statements (Loops) - 2
LOOPS The loop is the control structure we use to specify that a statement or group of statements is to be repeatedly executed. Java provides three kinds.
The while Looping Structure
ICS103: Programming in C 5: Repetition and Loop Statements
Module 4 Loops and Repetition 9/19/2019 CSE 1321 Module 4.
Looping and Repetition
Getting Started With Coding
Presentation transcript:

CPS125 Week 5 - 2

Modes of operation

Modes of operation Interactive mode: User responds to prompts by typing in data. Data is entered with the keyboard. Batch mode: program takes its data from a data file prepared beforehand. To read from a file we use fscanf instead of scanf. To write to a file instead of displaying on screen we used fprintf. To create a data file, we can use a simple text editor like notepad.

Reading Data from a File If your input data is lengthy and you are planning to execute your program many times, it is not convenient to input your data from the keyboard. this is true especially if you want to make only minor changes to the input data each time you execute the program. You must remember ,though , that when you create your input file using your editor that you give that file the same name you have specified in the code for your program. File pointer is a variable whose memory cell contains an address instead of an int ,float, or double value. This address gives the key to accessing the file stored on disk.

Reading from a file To do that you need first to declare the file FILE *in; /*notice that FILE is all upper case and the * before the name of the file variable.*/ Then the file must be opened in = fopen (“mydata.txt”,”r”); /* must exist on your disk! */ To read from the file,we use fscanf fscanf(in, “%d” ,&var); The file must be closed when not longer needed fclose(in);

Writing to a file To do that you need first to declare the file FILE *out; Then the file must be opened Out = fopen (“result.txt”,”w”); /* w is for write – it will create a new file on your disk */ To write to the file,we use fprintf fprintf(out, “%d” ,var); The file must be closed when not longer needed fclose(out);

Writing to A FILE #include <stdio.h> void main(void) { double income=123.45, expenses=987.65; int week=7, year=1996; FILE *myfile; myfile = fopen("L3_8.OUT","w"); fprintf(myfile,"Week=%5d\nYear=%5d\n",week,year); fprintf(myfile,"Income =%7.2lf\n Expenses=%8.3lf\n", income,expenses); fclose(myfile); }

Conditional Operator Very similar to if … else … expression1 ? expression2 : expression3; Means: If expression1 is TRUE, Do expression2 Otherwise Do expression3 Similarly we could have used this: if expression1 expression2; else expression3;

Loops 1. THE FOR LOOP 2. THE WHILE LOOP 3. THE DO WHILE LOOP

Repetition and Loops Loop: A control structure that repeats a group of steps (statements) in a program. Loop body: Contains the statements that are repeated in the loop.

Do I need a loop? 1. Are there any steps you must repeat to solve the problem? If yes, you need a loop. 2. Do you know in advance the number of repetitions? If yes, you need a counting loop. 3. Do you know when to stop the repetition? If no, you will not be able to program the loop.

Types of loops Counting Loop: A loop with a fixed number of repetitions. Ex: Repeat 100 times... Sentinel-Controlled Loop: A loop that reads values from a file or keyboard and stops reading when a certain value (called a sentinel) is read. Ex: Read numbers continuously until you encounter a value of -99.

Types of loops End-of-file Controlled Loop: A loop that reads values from a file and stops when there are no more values to read. Ex: Read numbers continuously until you encounter the end of the file. Input Validation Loop: A loop that keeps asking a value from the user until the user gets it right. Ex: Keep asking the user for a positive number until the user enters one.

Types of loops General Conditional Loop: A loop that checks a certain condition and repeats the statements in the loop body if the condition is true. When the condition is false, the loop is ended and the statements are not repeated. This kind of loop encompasses all the other kinds. Ex: Print numbers on the screen while the numbers are below 100.

Comparison of Loops Kinds When Used C implementation Structures Counting loop We can determine before loop execution exactly how many loop repetitions will be needed to solve the problem while for Sentinel-controlled loop Input of a list of data of any length ended by a special value while, for Endfile-controlled loop Input of a single list of data of any length from a data file Input validation loop Repeated interactive input of a data value until a value within the valid range is entered do-while General conditional loop Repeated processing of data until a desired condition is met

Flow Diagram of Loop choice process Any steps repeated? No No loop required Yes Use one of the conditional loops sentinel-controlled endfile-controlled input Validation general conditional Know in advance how many times to repeat? No Yes Use a counting loop

Loops in C In C, all loop are implemented with general conditional loops. By programming them properly, we can achieve all the types of loops. For example, a counting loop (repeat 100 times) will be done by starting a variable at 1, then have a condition to stop the loop when the variable becomes larger than 100. Inside the loop the program will add 1 to the variable at each repetition.

The for Loop No Semicolon Here! Doing a task or a number of tasks a known number of times. General Syntax: for ( LOOP_INDEX; LOOP_CONDITION; INDEX_CHANGE ) { /* BODY OF FOR LOOP */ } The for statement permits the repetition of the statements until the condition becomes false. No Semicolon Here!

If the body includes more than one statement then braces MUST be used. Explanation: For A ‘C’ Keyword ( ) To set up the loop parameters ; To separate the loop parameters Loop_Index Index of the FOR loop Loop_Condition Condition of looping Index_Change How to change the index { } Marks the body of the FOR loop Note !!!: If the body includes only ONE statement, we don’t need to use the braces. We, however, could use them if we want. If the body includes more than one statement then braces MUST be used.

How Does For Loop Work? for ( loop_index; loop_condition; index_change){ /* body of the for loop */ /* The body of the for loop is repeated as long as the condition is true */ } /* You are here!, if the condition is false */

STEPS TO EXECUTE A FOR LOOP Loop index is initialized, Loop condition is checked, If the condition is valid (TRUE), then the body of the for loop is executed, otherwise if the condition is FALSE, then the statement immediately after the body of the for loop will be executed. Go to top of the for loop again, Loop index is changed according to the index_change expression, Go to step 2.

/* PROGRAM #1*/ /* TO PRINT INTEGER NUMBER 1 THROUGH 100 */ #include <stdio.h> #define NUMBER 100 main (){ int counter; for(counter=1; counter<=NUMBER; counter=counter+1) printf("Counter is %d.\n",counter); printf("The counter after the loop is finished: %d.\n",counter); }/* PROGRAM #2*/ /* TO PRINT INTEGER NUMBER 1 THROUGH 100 */ printf("The counter after the loop is finished: %d.\n",counter);}

How Does For Loop Work? for ( loop_index; loop_condition; index_change){ /* body of the for loop */ /* The body of the for loop is repeated as long as the condition is true */ } /* You are here!, if the condition is false */

STEPS TO EXECUTE A FOR LOOP Loop index is initialized, Loop condition is checked, If the condition is valid (TRUE), then the body of the for loop is executed, otherwise if the condition is FALSE, then the statement immediately after the body of the for loop will be executed. Go to top of the for loop again, Loop index is changed according to the index_change expression, Go to step 2.

/* PROGRAM #1000*/ /* TO PRINT INTEGER NUMBER 1 THROUGH 100 */ #include <stdio.h> #define NUMBER 100 main (){ int counter; for(counter=1; counter<=NUMBER; counter=counter+1) ; printf("Counter is %d.\n",counter); printf("The counter after the loop is finished: %d.\n",counter); }/* PROGRAM #2000*/ /* TO PRINT INTEGER NUMBER 1 THROUGH 100 */ for(counter=1; counter<=NUMBER; counter=counter+1) printf("The counter after the loop is finished: %d.\n",counter);}

/* PROGRAM #3*/ /* TO PRINT INTEGER NUMBER 1 THROUGH 100 */ #include <stdio.h> #define NUMBER 100 main (){ int counter; for(counter=1; counter<=NUMBER; counter=counter+1){ printf("Counter is %d.\n",counter); } printf("The counter after the loop is finished: %d.\n",counter); } /* PROGRAM #4*/ /* DEMONSTRATES USE OF FOR STATEMENT */ main (){ int counter; /*Print integer numbers from1 to 100*/ for(counter=1; counter<=100; counter=counter+1){ printf("Counter is %d.\n",counter); printf("You are still in the BODY OF THE FOR LOOP!.\n",counter); } printf("\n The counter after the loop is finished: %d.\n",counter); }

/* PROGRAM #5*/ /* FOR LOOP USING POST_INCREMENT OPERATOR */ #include <stdio.h> #define NUMBER 100 main (){ int count; /*Print the number 1 through 100,use of post-increment*/ for(count=1; count<=NUMBER; count++) printf("Count = %d.\n",count); } /* PROGRAM #6 */ /* FOR LOOP USING POST_INCREMENT OPERATOR */ main (){ int count; /*Print the number 1 through 100,use of pre-increment*/ for(count=1; count<=NUMBER; ++count) printf("Count = %d.\n",count); }

/* PROGRAM #7 */ /* FOR LOOP USING POST_INCREMENT OPERATOR */ #include <stdio.h> #define NUMBER 100 main (){ int count; /*Print the number 1 through 100,use of pre-increment*/ for(count=1; count<=NUMBER; ++count); printf("Count = %d.\n",count); }

Sum Algorithm Objective: calculate the sum of integer numbers from 1 to 10, ie, 1+2+3+…+9+10 HOW TO DO THIS? Start with SUM equal to zero, (0) Then add 1 to it, now SUM is 1, (0+1) Then add 2 to it, now SUM is 3, (0+1+2) … Then add 10 to it, now SUM is 55, (0+1+2+…+10) It appears that we need repeatedly (10 times) add numbers to SUM. We can use a FOR LOOP for this as follows: