Presentation is loading. Please wait.

Presentation is loading. Please wait.

Engineering Problem Solving with C Fundamental Concepts

Similar presentations


Presentation on theme: "Engineering Problem Solving with C Fundamental Concepts"— Presentation transcript:

1 Engineering Problem Solving with C Fundamental Concepts
Chapter 3 Control Structures and Data Files

2 Algorithm Development

3 Structured Programming
Sequence Selection Repetition no yes yes no

4 Conditional Expressions

5 Relational Operators == equality != non equality < less than
> greater than <= less than equal to >= greater than equal to

6 Logical Operators ! not && and || or

7 Operator Precedence < <= > >= == != && || 5 ! Example
< <= > >= == != && || 5 ! Example int b=3,c=5; !(b==c || b==5.5)

8 Selection Statements

9 Selection Statements if if else switch

10 If statement if(Boolean expression) statement; //single statement
[if the condition is true, execute the statement; if condition is false, skip the statement] { //more than one statement statement1; . statement n; } Compound/block statement

11 If statement - examples
if (x>0) k++; if(x>0) { x=sqrt(x);

12 if - else statement if(Boolean expression) statement; else {
statement block }

13 nested if-else if(x > y) if(y < z) k++; else m++; j++;
The value of k is incremented when x>y and y<z (both). The value of m is Incremented when x>y and y>=z. The value of j is incremented when X<=y

14 Practice! int x=9, y=7, z=2, k=0, m=0, j=0; if(x > y) if(y < z)
else m++; j++; What are the values of j, k and m?

15 Switch Statement case constant: statement(s); break;
switch(expression) { case constant: statement(s); break; /* default is optional*/ default: }

16 Switch Statement Expression must be of type integer or character
The keyword case must be followed by a constant break statement is required unless you want all subsequent statements to be executed

17 Practice! Convert the following nested if/else statements to a switch statement: if (rank==1 || rank==2) printf("Lower division \n"); else { if (rank==3 || rank==4) printf("Upper division \n");   {  if (rank==5) printf("Graduate student \n"); printf("Invalid rank \n"); }

18 Loop Structures

19 repetition while statement do while statement for statement

20 Additional statement in Loop
C allows to use 2 additional statements with loops to modify their performance: BREAK statement CONTINUE statement

21 while statement while(condition) statement; { }
The condition is evaluated first before the statements within the loop are executed. If condition is false, the loop statements are skipped and the execution continues with the statement following the loop.

22 While Statement: continue
If the condition is true, then the statements are executed and the condition is evaluated again. If still true, then the same process as above. This repetition continues until the condition is false.

23 do while do statement; while(expression); { statement1; statement2;
note - the expression is tested after the statement(s) are executed, so statements are executed at least once (difference with the while loop).

24 Similarities and Differences
while loop and do while are similar. can be used interchangeable, however, adjustment need to be done in the statements of the loop body Differences while loop – the test expression is tested first, if false the loop body is not executed do-while – the loop body always is executed once. After that the test expression is tested, if the test result is false, the loop body is not executed again.

25 for statement Initialization:use to initialize loop-control variable
Test: specifies the condition that should be true to continue the loop repetition. Increment/decrement: specifies the modification to the loop control variable. for(initialization; test; increment/decrement) statement; { }

26 for(initialization; test; increment/decrement)
for statement initialize test increment/ decrement true statement(s) statement(s) for(initialization; test; increment/decrement) statement;

27 Example: for loop Execute a loop 10 times with the loop variable k going from 1 to 10 in increment of 1. for (k=1;k<=10;k++) { statements; } for (n=20;n<=0;n-=2) Execute the loop with the value of variable going from 20 to 0 with increment of -2.

28 for statement - examples
int sum =0; for(int k=1;k<10;k+=2) sum = sum + k; int fact =1; for(int n=5;n>1;n--) fact = fact * n;

29 Practice! Determine the number of times that each of the following for loops are executed. for (k=3; k<=20; k++) { statements; } for (k=3; k<=20; ++k) for (count=-2; count<=14; count++)

30 Problem 1 Write a program to computes the distance a body falls in feet per second, for the first 5 seconds of free fall as given by the equation s= ½ a t2 s- distance in feet a- acceleration due to gravity (32ft/sec2) t- time in seconds

31 break statement break; terminates loop
execution continues with the first statement following the loop Example for(int i=0;i<100;i++) { printf(“i=%d\n”,i); if(i==10)break; } printf(“Out of loop\n”);

32 Output: i=0 i=1 i=2 i=3 i=4 i=5 i=6 i=7 i=8 i=9 i=10 Out of loop
Press any key to continue

33 continue statement continue;
forces next iteration of the loop, skipping any remaining statements in the loop Example int i=0; while(i<10) { i++; printf(“%d\n”,i); if(i>5) continue; }

34 Output 1 3 5 7 8 9 10 Press any key to continue

35 Data Files

36 Why? 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 keyboard. So, use data file to store data.

37 Example:Reading data from a file
# include<stdio.h> void main(void) { double xx; int ii,kk; FILE *inptr; inptr=fopen("C3_6.txt","r"); fscanf(inptr,"%d",&ii); fscanf(inptr,"%d %lf",&kk,&xx); fclose(inptr); printf("ii=%5d\nkk=%5d\nxx=%9.3lf\n",ii,kk,xx); return ; } Variable declarations Declaring a pointer variable to use with functions fopen and fscanf Calling function fopen to allow program to access disk file C3_6.txt the function,fscanf,works similar to scanf. However it uses the file pointed to by inptr Closing the file pointed to by inptr

38 Input file C3_6.txt Output: 36 123 456.78 ii= 36 kk= 123 xx= 456.780
Output: ii= 36 kk= 123 xx= Press any key to continue

39 Data Files Each data file must have a file pointer
file pointer must be defined FILE *sensor1; FILE *balloon; FILE *inptr; file pointer must be associated with a specific file using the fopen function sensor1 = fopen(“sensor1.dat”, “r”); balloon = fopen(“balloon.dat”, “w”); Inptr = fopen(“C3_6.txt”.”r”);

40 I/O Statements Input file - use fscanf instead of scanf
fscanf(sensor1, “%lf %lf”, &t, &motion); Output file - use fprint instead of printf fprintf(balloon, “%f %f %f\n”, time, height, velocity);

41 Data Files To read data from files, know the details about file.
File name so that can use fopen statements to associate file with pointer/ Know order and data typedeclare corresponding identifiers correctly. Any special info in the fileto determine the length of file, in attempting to execute fscanf statement. In order to avoid error after we have read all the data in the file, need to know when we have read all the data.

42 Reading Data Files Data files have 3 common structures:
1. counter controlled loop for loop 2. sentinel controlled loop while loop 3. end of file controlled loop

43 Example:counter control loop
#include <stdio.h> FILE *data; int main() { int counter,i; double score,total=0,average; data =fopen ("grade.txt","r"); if (data==NULL) printf("error opening file.\n"); else fscanf(data,"%d",&counter); printf("no.\tscore\n"); /* read data and compute summary information*/ for(int j=1;j<=counter;j++) fscanf(data,"%d %lf",&i,&score); printf("%d %lf\n",i,score); total += score; } printf("total score= %.2lf\n",total); average = total/counter; printf("average score = %.2lf\n",average); /* close and exit program*/ fclose(data); return 0;

44 Data file:grade.txt Output: no. score 1 56.000000 2 90.000000
Output: no. score total score= average score = 72.67 Press any key to continue

45 Example:Trailer or Sentinel
#include<stdio.h> FILE *data; int main() { int num,count=0; double score,total=0,average; data=fopen("grade1.txt","r"); fscanf(data,"%d %lf",&num,&score); while(num >= 0) count++; printf("%d %.2lf\n",num,score); total+=score; } printf("Total=%.2lf\n",total); average=total/count; printf("average=%.2lf\n",average); fclose(data); return 0;

46 grade.txt Output:same with previous 1 56.00 2 90.00 3 78.00 4 56.00
89.0 Output:same with previous

47 End of file controlled loop
#include<stdio.h> //end of file controlled loop FILE *data; int main() { int i; double score,total=0,average; data=fopen("grade.txt","r"); int count=0; while((fscanf(data,"%i %lf",&i,&score))==2) count++; printf("%d %.2lf\n",i,score); total+=score; } printf("total=%.2lf\n",total); average=total/count; printf("average=%.2lf\n",average); return 0;


Download ppt "Engineering Problem Solving with C Fundamental Concepts"

Similar presentations


Ads by Google