220 likes | 324 Views
Introduction to C Programming CE00312-1. Lecture 4 Further Control Structures in C. Program Control - Iteration. Executing a series of one or more statements a number of times Also referred to as repetition or looping Non-deterministic No pre-set number of iterations Use While Do While
E N D
Introduction to C ProgrammingCE00312-1 Lecture 4 Further Control Structures in C
Program Control - Iteration • Executing a series of one or more statements a number of times • Also referred to as repetition or looping • Non-deterministic • No pre-set number of iterations • Use • While • Do While • Deterministic • Known number of iterations • Use • For
Non-deterministic Loop: While statement Format while (condition) statement; where the statement can be a compound statement e.g. sum=0; scanf(“%d”,&x); while (x!=-9999) { sum=sum+x; scanf(“%d”,&x); }
Read Ahead Technique Input data: 1 4 5 6 –9999 Unwinding the iteration: Read num 1 Process num Read num 4 Process num Read num 5 Process num Read num 6 Process num Read num -9999
The iterated step is: Process num Read num Which leads to: Read num While num != -9999 Process num Read num
Example: While Loop • Define Problem Problem: Read a series of integers terminated by –9999. Count the number of integers that are greater than 150 and find the largest and smallest numbers greater than 150.Print a message if none of the integers are greater than 150. Example Input: 100 200 10 80 400 150 6 -9999 Expected Output: Number of values>150=2 Max=400 Min=200
Initialise:- count=0:max=0:min=99999 Read first number Input values and process While number <> -9999 loop If number > 150 then Increment count Check if new largest If number>=max then max=number Check if new smallest If number <=min then min=number Read next number End loop Print results If count>0 then Print count, max, min Else Print “No values” 2. Design
#include <stdio.h> int main(void) /*program description*/ { int num,max,min,count; count=0; min=99999; max=0; scanf(“%d”, &num); while (num !=-9999) { if (num>150) { ++count; if (num>max) max=num; if (num<min) min=num; } scanf(“%d”,&num); } if (count>0) { printf(“Number of values>150= %d\n”, count); printf(“Max = %d\n”,max); printf(“Min = %d\n”,min); } else printf(“No values over 150”); return 0; } 3. Code
Non-deterministic loop – Do While loop General Form do statement; while (expression); • Unlike the while statement, the expression in the ‘do while’ comes after ‘statement’ (the loop body) which is thus executed at least once. • Note that it is very easy to make mistakes with the do while loop, although it may compile and appear to produce valid code.
Deterministic Loop: For statement For statement format for (initialising list; condition; altering list) statement; initialising list: Executed once altering list: Executed at the end of each iteration condition: Evaluated and checked at the start of each iteration i.e. a leading decision
Example:For loop for (count=1;count<=10;count=count+2) printf(“%3d”,count); Gives output: 1 3 5 7 9 Equivalent While loop: count=1; while (count<=10) { printf(“%3d”,count); count=count+2; }
Increment and Decrement Operators • count=count+1; -> ++count; count++; • count=count-1; -> --count; count--; • count=count+5: -> count+=5; Increment can occur before or after statement actioned • count=3; x=++count; == count: 4, x: 4 • count=3; x=count++; == count:4, x:3 Similarly with decrement operators.
Using increment and decrement operators in for loops for (count=0;count<=10;++count) printf(”%3d”,count); Prints : 1 2 3 4 5 6 7 8 9 10 for (count=0;count<=10;count++) printf(”%3d”,count); Prints : 0 1 2 3 4 5 6 7 8 9 10 Classic Error: for (i=0;i<10;++i); printf(“%d”, i);
Example 1 Deterministic Loop Problem: Print a multiplication table of size N. e.g. 1 2 3 4 5 2 4 6 8 10 3 6 9 12 15 where N=5 4 8 12 16 20 5 10 15 20 25 The structure of the data determines the structure of the program
Design • Data: Repetition of rows Repetition of values (row*column) • Design Read N Perform N times Print a row Perform N times Print a value
Code #include <stdio.h> /* Reads an integer N and prints the N times multiplication table */ int main(void) { int row, col, n; printf(“\nPlease enter the value of N: “); scanf(“%d”, &n); printf(“\n\n”); for (row=1;row<=n;row++) { for (col=1;col<=n;++col) printf(“%6d”, row*col); printf(“\n”); } return 0; }
Deterministic Loops – Example 2 Problem: Write a program to encode lower case letters in a message by performing a cyclic shift one place to the right. Example Input: The cat sat on the mat Example Output: Uif dbu tbu po uif nbu
Code #include <stdio.h> /* Character processing example */ int main(void) { char c; while (scanf(“%c”, &ch) != EOF) if (ch == ‘z’) printf(“%c”, ‘a’); else if (ch >= ‘a’ && ch <=’y’) printf(“%c”, ch+1); else printf(“%c”, ch); return 0; }
End of File Condition • All files have an end of file marker • When scanf() attempts to read this marker, it returns –1 • The following code copies integers until the end of file is found • EOF can also be generated by ctrl-D while (scanf(“%d”, &x) !=-1) printf(“%d”, x); • stdio.h contains • #define EOF –1 • hence: while (scanf(“%d”, &x) !=EOF) printf(“%d”, x); • End of file markers avoid having to select a data terminator result in neater code.
Example of buffered input #include <stdio.h> int main(void) { int num, sum, count; float mean; sum=0; count=0; while (scanf(“%d”, &num) !=EOF) { sum=sum+num; ++count; } printf(“%f\n”, (float)sum/(float)count); return 0; }
Buffered Input Using scanf() Problem Consider the following segment of code: char ch1, ch2; printf(“\n Input first value: “); scanf(“%c”, &ch1); printf(“\n Input second value: “); scanf(“%c”, &ch2); At run time: Prompt: Input first value User response: Q [RETURN] Program Action: ch1=’Q’, ch2=10 (ASCII [RETURN] = 10) Why?
Solution char ch1, ch2; printf(“\n Input first value: “); scanf(“%c%c”, &ch1, &rtn); printf(“\n Input second value: “); scanf(“%c”, &ch2); NOTE: if ch2 is a non-character type e.g. an integer, then there isn’t a problem. Care must be taken when processing characters. Consider: #define EOLN 10 …… while (scanf(“%c”, &ch1)!=EOLN) printf(“%c”,ch1);