Presentation is loading. Please wait.

Presentation is loading. Please wait.

CPS125 Week 5 - 2.

Similar presentations


Presentation on theme: "CPS125 Week 5 - 2."— Presentation transcript:

1 CPS125 Week 5 - 2

2 Modes of operation

3 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.

4 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.

5 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);

6 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);

7 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); }

8

9 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;

10 Loops THE FOR LOOP THE WHILE LOOP THE DO WHILE LOOP

11 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.

12 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.

13 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.

14 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.

15 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.

16 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

17 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

18 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.

19 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!

20 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.

21 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 */

22 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.

23 /* 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);}

24 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 */

25 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.

26 /* 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);}

27 /* 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); }

28 /* 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); }

29 /* 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); }

30 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:


Download ppt "CPS125 Week 5 - 2."

Similar presentations


Ads by Google