13&14-2 Know the forms of loop statements in C (while,do/while,for). Understanding how data conversion occurs. Read/Write data in files using Unix redirection.

Slides:



Advertisements
Similar presentations
11-2 Identify the parts of the “main” function, which include Preprocessor Directives main function header main function body which includes Declaration.
Advertisements

Introduction to C Programming
Loops (Part 1) Computer Science Erwin High School Fall 2014.
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.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 5 Looping.
41 A Depth Program #include int main(void) { int inches, feet, fathoms; //declarations fathoms = 7; feet = 6 * fathoms; inches = 12 * feet; printf(“Wreck.
C Lecture Notes 1 Program Control (Cont...). C Lecture Notes 2 4.8The do / while Repetition Structure The do / while repetition structure –Similar to.
Chapter 5: Loops and Files.
 2007 Pearson Education, Inc. All rights reserved Introduction to C Programming.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 4 - Program Control Outline 4.1Introduction 4.2The Essentials of Repetition 4.3Counter-Controlled.
Chapter 5: Control Structures II (Repetition)
Introduction to C Programming
1 Lecture 5  More flow control structures  for  do  continue  break  switch  Structured programming  Common programming errors and tips  Readings:
12-2 Know how if and switch C statements control the sequence of execution of statements. Be able to use relational and logical operators in the conditional.
Performing Computations C provides operators that can be applied to calculate expressions: example: tax is 8.5% of the total sale expression: tax =
Control Structures - Repetition Chapter 5 2 Chapter Topics Why Is Repetition Needed The Repetition Structure Counter Controlled Loops Sentinel Controlled.
Algorithms and Computing Lecture 3 Control Statements By Dr. M. Tahir Khaleeq.
16&17-2 Grasp the concept of top-down programming Identify Function Headers and Prototypes Understand when and where prototypes used Understand how arguments.
18-2 Understand “Scope” of an Identifier Know the Storage Classes of variables and functions Related Chapter: ABC 5.10, 5.11.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Program Control Outline 4.1Introduction 4.2The Essentials of Repetition 4.3Counter-Controlled.
Lecture 4 C Program Control Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
Mr. Dave Clausen1 La Cañada High School Chapter 6: Repetition Statements.
CPS120: Introduction to Computer Science Decision Making in Programs.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 5: Control Structures II (Repetition)
Chapter 5 Control Structure (Repetition). Objectives In this chapter, you will: Learn about repetition (looping) control structures Explore how to construct.
Control Structures II (Repetition). Objectives In this chapter you will: Learn about repetition (looping) control structures Explore how to construct.
Control Structures II Repetition (Loops). Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1.
Chapter 3 - Structured Program Development Outline 3.1Introduction 3.2Algorithms 3.3Pseudocode 3.4Control Structures 3.5The If Selection Structure 3.6The.
ECE 103 Engineering Programming Chapter 18 Iteration Herbert G. Mayer, PSU CS Status 7/19/2015 Initial content copied verbatim from ECE 103 material developed.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Program Control Outline 4.1Introduction 4.2The Essentials of Repetition 4.3Counter-Controlled.
Quiz 3 is due Friday September 18 th Lab 6 is going to be lab practical hursSept_10/exampleLabFinal/
Loops cause a section of a program to be repeated a certain number of times. The repetition continues while a condition remains true. When a condition.
24-2 Perform File I/O using file pointers FILE * data-type Opening and closing files Character Input and Output String Input and Output Related Chapter:
Loops and Files. 5.1 The Increment and Decrement Operators.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
Copyright © 2012 Pearson Education, Inc. Chapter 5: Loops.
Repetition Repetition allows you to repeat an operation or a series of operations many times. This is called looping and is one of the basic structured.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 5 Looping.
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.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
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.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
Chapter 4 Repetition Statements Program Development and Design Using C++, Third Edition.
Computer C programming Chapter 3. CHAPTER 3 Program Looping –The for Statement –Nested for Loops –for Loop Variants –The while Statement –The do Statement.
Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1.
C Program Control September 15, OBJECTIVES The essentials of counter-controlled repetition. To use the for and do...while repetition statements.
Week 3.  TO PRINT NUMBERS FROM 1 TO 20  TO PRINT EVEN NUMBERS FROM 1 TO 20 2.
Chapter 4 – C Program Control
REPETITION CONTROL STRUCTURE
EKT120 COMPUTER PROGRAMMING
EKT150 INTRODUCTION TO COMPUTER PROGRAMMING
Lecture 7: Repeating a Known Number of Times
Chapter 4 - Program Control
Week 4 – Repetition Structures / Loops
Lecture 13 & 14.
Looping.
Arrays, For loop While loop Do while loop
CS1100 Computational Engineering
Structured Program
Chapter 4 - Program Control
Program Control Topics While loop For loop Switch statement
Computer programming Lecture 3.
ECE 103 Engineering Programming Chapter 18 Iteration
Chapter 4 - Program Control
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.
ICS103: Programming in C 5: Repetition and Loop Statements
Presentation transcript:

13&14-2 Know the forms of loop statements in C (while,do/while,for). Understanding how data conversion occurs. Read/Write data in files using Unix redirection operators ( ). Learn various methods for detecting the end of file. Related Chapters: ABC Chapter

13& Problem Definition Use a while statement to read a list of integers from a file and compute the average. 2. Refine, Generalize, Decompose the problem definition (i.e., identify sub-problems, I/O, etc.) Input = integers from file “input.dat” Output=real number representing the arithmetic average =(sum of values)/(count of number of values) 3. Develop Algorithm (processing steps to solve problem)

13&14-4 Flowchart while EOF != scanf value total = total + value; count = count + 1; TrueFalse total = 0; count = 0; printf total/(double) count (double) is a cast see slide #14

13&14-5 /* C Program to compute the average of a list of numbers. */ #include void main(void) { int value,total = 0,count = 0; /*Why initialized to zero?*/ /* while the scanf function has not reached the EndOfFile */ while ( EOF != scanf("%i", &value) ) { total = total + value; count = count + 1; } /* end of while loop */ /* Output the average use a cast */ printf("Average of the %i numbers = %f \n",count,total/(float)count); }

13& Use gedit to enter the above code in a file problem1.c, and make sure to save the file. 2. Use gedit to create an input file input.dat and enter in integers into this file. Save and exit this file. 3. Compile the problem1.c code by typing gcc problem1.c

13& Run the program using Unix redirection <./a.out < input.dat 5. What happens if you type./a.out output.dat Note: if you do this a second time it will fail because Unix will not let you over-write an existing file. 6. To append the results to the existing file output.dat./a.out > output.dat

13&14-8 A second form of a declaration in C : data-type variable_name = initializer; /*Why are total and count initialized to zero?*/ Answer: Un-initialized variables have unknown (garbage) values. int value,total = 0,count = 0;

13&14-9 while(expression) statement; if expression evaluates to true, the statement is executed and then execution loops up and re-evaluates expression; otherwise execution passes to the next statement in the program. while statement format while(value >= 0.0); /* Error! Don’t put semicolon here */ /* This is an example of a logical error */ while (EOF != scanf("%i", &value)) { total = total + value; count = count +1; } /* end of while loop */

13&14-10 We can also execute multiple statements when a given expression is true: while (expression) { statement1; statement2; statementn; } if expression evaluates to true, all the statements are executed and then execution loops up and re-evaluates expression otherwise execution passes to the next statement in the program

13&14-11 { statement1; statement2;... statementn; } A sequence of statements surrounded by a pair of curly braces is called a block or compound statement. 1) From outside, the compound statement looks like a single statement. A compound statement can go where any single C statement can go. (e.g. a branch of if-else, body of a for loop,...)

13&14-12 A block is any compound statement that may include variable declaration(s). 1) As a compound statement, from outside, the block looks like a single C statement. A block can go where any single C statement can go. 2) The importance of a block is that, the curly braces of the block delimit the (i.e. the region of validity) of the variables declared in the block. 3) The concept of lies at the heart of Structured Programming, as will be discussed in a future lecture on Modularity.

13&14-13 The program makes use of the fact that the scanf function returns and integer value representing the number of successful conversions. For example in the code fragment: Example: int number,value1,value2,value3; number = scanf("%i%i%i",&value1,&value2,&value3); the variable number could take one the value -1,0,1,2 or 3. EOF is a built-in constant in C (usually assigned -1). If you are checking for End-of-File then use this constant. EOF != scanf("%i", &value)

13&14-14 To fix the above use the cast operator where data_type is a valid C data type. float result; int total = 10, count = 4 ; result = total / (float) count; /* result now has the value 2.5 */ Example, float result; int total = 10, count = 4 ; result = total / count; /* result has the value 2.0 */ ( data_ type ) printf("Average of the %i numbers = %f\n",count, total/(float)count );

13&14-15 data_type1 x; data_type2 result ; result = x; If x and result have different data types then an automatic conversion takes place. Data could be lost. Example, float x = ; int result; result = x; /* result now has the value 3 */ 1) Conversion of assigned values

13& , -, *, / x op y ;where op is If x and y have different (mixed) data types then C automatically converts data from the lower rank to the higher rank and then performs the computation. Note: % (modulus) is only defined on integers. The ranking is given by the following table. Higher double float integer Lower 2) Conversion of values with mixed data types in an expression using arithmetic operators

13&14-17 Example, float result, x = ; int y = 3; result = x + y; /* result now has the value */ Example, int x = 2.5; float result, y; y = x; result = 1 / y; /* result now has the value.5 */

13& Problem Definition Write a program that reads a file of characters one character at a time and writes out each non-blank character to another file. 2. Refine, Generalize, Decompose the problem definition (i.e., identify sub-problems, I/O, etc.) Input = characters in a file “input2.dat” Assume this file is non-empty. Output=Non-blank characters from input2.dat are output to the file output2.dat 3. Develop Algorithm (processing steps to solve problem)

13&14-19 Flowchart while EOF != scanf c TrueFalse scanf c if c != ‘ ‘ /* a blank */ printf c

13&14-20 /* C Program to remove the blanks from a text file. */ #include void main(void) { char c; scanf("%c",&c); do { if (c != ' ') printf("%c",c); } while(EOF != scanf("%c",&c)); }

13& Use gedit to enter the above code in a file problem2.c, and make sure to save the file. 2. Use gedit to create an input file input2.dat and enter in any number of lines of text including blanks. Save and exit this file. 3. Compile the problem2.c code by typing gcc problem2.c 4. Run the program using Unix redirection./a.out output2.dat 5. View the contents of output2.dat more output2.dat

13&14-22 do statement; while(expression); The statement is executed first. Then if expression evaluates to true, execution loops up and the statement is executed again; otherwise execution passes to the next statement in the program. The general form of the do-while statement is: do/while statement format do { statement1; while-statementn; } while (expression);

13& Problem Definition Use a for statement to read a list of integers from a file and compute the average. The first number in the list gives the count of the numbers to be read. This first value is not used in the computation of the average. 2. Refine, Generalize, Decompose the problem definition (i.e., identify sub-problems, I/O, etc.) Input = integers from file “input3.dat” Output=real number representing the arithmetic average (sum of values)/(count of number of values) 3. Develop Algorithm Use a counter controlled loop. (processing steps to solve problem)

13&14-24 Flowchart for i = 1 ; i <= count; i=i+1 total = total + value; TrueFalse total = 0; scanf count printf total/(double) count scanf value

13&14-25 /* C Program to compute the average of a list of numbers. */ #include void main(void) { int value,total = 0,count; int i; /* loop counter */ scanf("%i",&count); for(i=1;i<=count;i=i+1) { scanf("%i",&value);/* read value */ total = total + value; } /* end of for loop */ /* Output the average. */ printf("Average of %i numbers = %f \n",count,total/(float)count); }

13& Use gedit to enter the above code in a file problem3.c, and make sure to save the file. 2. Use gedit to create an input file input3.dat and enter in integers into this file.The first integer is the count of integers to be averaged. Save and exit this file. 3. Compile the problem1.c code by typing gcc problem3.c 4. Run the program using Unix redirection <./a.out < input3.dat

13&14-27 for(init. expressions ; expression ; update stmnts. ) statement; C allows more than one initialization expression or update statement but these statements or expressions must be separated by a comma not a semicolon. Also, if there is more than one init. expression or update statement then the order of execution is from left to right. The initialization expressions are executed once (and only once). If expression evaluates to true, statement1 is executed and execution loops up and evaluates all the update stmnts. and then expression is re-evaluated; otherwise execution passes to the next statement in the program. The following order of must be observed … init. expressions; expression ; update stmnts

13&14-28 for(init. expressions ; expression ; update stmnts. ) { statement1; statement2;... statementn; } The initialization expressions are executed once (and only once), next: if expression evaluates to true, the statements statement1,...,statementn are executed and execution loops up and evaluates all the update stmnts. and then expression is re-evaluated; otherwise execution passes to the next statement in the program.

13&14-29 Write a code fragment to add the integers from 1 to 100. int i,total; total = 0; for(i=1;i<=100;i=i+1) total = total + i; The above code could be re-written as: int i,total; for(i=1, total = 0; i<=100; total=total+i, i=i+1); but not as: int i,total; for(i=1, total = 0; i<=100; i=i+1, total=total+i); Why not? The order of the statements is critical!

13& Problem Definition Use a for statement to read a list of integers from a file and compute the average. Read the integers until the sentinel value of -999 occurs. Do not use the sentinel value in the computation of the average. 2. Refine, Generalize, Decompose the problem definition (i.e., identify sub-problems, I/O, etc.) Input = integers from file “input4.dat” Output=real number representing the arithmetic average (sum of values)/(count of number of values) 3. Develop Algorithm (processing steps to solve problem)

13&14-31 Flowchart for i = 1 ; ; i=i+1 if value == -999 break; total = total+value; TrueFalse total = 0; printf total/(float) (i-1) scanf value

13&14-32 /* C Program to compute the average of a list of numbers. */ #include void main(void) { int value,total = 0,count; int i; /* loop counter */ for(i=1; ;i=i+1) { scanf("%i",&value);/* read value */ if (value == -999) /* -999 is the sentinel value */ break; total = total + value; } /* end of for loop */ /* Output the average. */ count = i-1; printf("Average of %i numbers = %f \n",count,total/(float)count); }

13&14-33 Omitting the logical expression in a for statement means that the for statement executes as an infinite loop. for(i=1; ;i=i+1) { As with the switch statement the break statement causes the termination of the loop but not the program.

13&14-34 You can use any of the loop statements (for,while,do/while) to code a loop. The for statement is useful especially when you know how many times the loop will iterate. The do/while loop always executes at least once. The break statement may be used in any loop or switch statement. C performs automatic data conversion when 1) assigning values of different data-types and 2) when performing computations on values of different data-types. Use a cast to force data-type conversion. Reading from one data file and writing to one data file can be accomplished with Unix redirection ( ). Later in the semester we will consider fprintf and fscanf functions that will allow the use of multiple input and output files. We considered three methods for indicating that the end of file has been reached. 1) use of the EOF built-in constant. 2) use of a Sentinel value. 3) using the value in the file to indicate the number of values to be read.