Engineering Problem Solving with C Fundamental Concepts

Slides:



Advertisements
Similar presentations
INTEC CS160 - Jeanine Ingber Engineering Problem Solving with C Fundamental Concepts Chapter 3 Control Structures and Data Files.
Advertisements

5/17/ Programming Constructs... There are several types of programming constructs in JAVA. - If-else construct or ternary operator - while - do-while.
1 Engineering Problem Solving With C++ An Object Based Approach Chapter 3 Control Structures.
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
Computer Programming 1 Repetition. Computer Programming 2 Objectives Repetition structures Study while and do loops Examine for loops A practical example.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 4 - Program Control Outline 4.1Introduction 4.2The Essentials of Repetition 4.3Counter-Controlled.
Algorithms and Computing Lecture 3 Control Statements By Dr. M. Tahir Khaleeq.
CHAPTER 5: CONTROL STRUCTURES II INSTRUCTOR: MOHAMMAD MOJADDAM.
Fundamentals of C and C++ Programming Control Structures and Functions.
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.
Lecture 10: Reviews. Control Structures All C programs written in term of 3 control structures Sequence structures Programs executed sequentially by default.
Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee C Language Part 2.
1 4.8The do/while Repetition Structure The do/while repetition structure –Similar to the while structure –Condition for repetition tested after the body.
CSCI 3328 Object Oriented Programming in C# Chapter 5: C# Control Statement – Part II UTPA – Fall
Chapter 8 Iteration Dept of Computer Engineering Khon Kaen University.
Chapter 05 (Part III) Control Statements: Part II.
Chapter 3 - Structured Program Development Outline 3.1Introduction 3.2Algorithms 3.3Pseudocode 3.4Control Structures 3.5The If Selection Structure 3.6The.
1 ELEC 206 Chapter 3 Control Structures 5-Step Problem Solving Methodology 1. State the problem clearly. 2. Describe the input and output. 3. Work a.
Chapter 15 JavaScript: Part III The Web Warrior Guide to Web Design Technologies.
REPETITION STATEMENTS - Part1  Also called LOOP STATEMENTS OR LOOP STRUCTURES 1 C++ Statements that repeat one or more actions while some condition is.
Chapter 2: Fundamental Programming Structures in Java Adapted from MIT AITI Slides Control Structures.
1 Midterm 1 Review. 2 Midterm 1 on Friday February 27 Closed book, closed notes No computer can be used 50 minutes 4 or 5 questions write full programs.
Introduction to Programming G50PRO University of Nottingham Unit 6 : Control Flow Statements 2 Paul Tennent
Chapter 7 Control Structures. Java has very flexible three looping mechanisms. You can use one of the following three loops:  while Loop  do...while.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 6.
Lecture 4b Repeating With Loops
Engineering Problem Solving with C
Chapter 4 – C Program Control
Chapter 5: Structured Programming
UMBC CMSC 104 – Section 01, Fall 2016
REPETITION CONTROL STRUCTURE
Control Structures and Data Files
EKT120 COMPUTER PROGRAMMING
EKT150 INTRODUCTION TO COMPUTER PROGRAMMING
Lecture 7: Repeating a Known Number of Times
C Program Controls + Flow Structure
Chapter 4 - Program Control
Engineering Problem Solving with C++, Etter/Ingber
CS1010 Programming Methodology
Lecture 13 & 14.
BY GAWARE S.R. COMPUTER SCI. DEPARTMENT
CiS 260: App Dev I Chapter 4: Control Structures II.
Ch 7: JavaScript Control Statements I.
JavaScript: Control Statements.
2008/10/22: Lecture 12 CMSC 104, Section 0101 John Y. Park
Chapter 5: Control Structures II
Control Structures Lecture 7.
Arrays, For loop While loop Do while loop
Outline Altering flow of control Boolean expressions
2008/10/22: Lecture 12 CMSC 104, Section 0101 John Y. Park
Chapter 2 - Introduction to C Programming
Structured Program
Chapter 4 - Program Control
Chapter 3 - Structured Program Development
Chapter 3 - Structured Program Development
Chapter 2 - Introduction to C Programming
UMBC CMSC 104 – Section 01, Fall 2016
Computer programming Lecture 3.
CPS125 Week
More Loops Topics Counter-Controlled (Definite) Repetition
Chapter 2 - Introduction to C Programming
Control Statements Paritosh Srivastava.
Chapter 4 - Program Control
More Loops Topics Counter-Controlled (Definite) Repetition
More Loops Topics Counter-Controlled (Definite) Repetition
More Loops Topics Counter-Controlled (Definite) Repetition
More Loops Topics Counter-Controlled (Definite) Repetition
ICS103: Programming in C 5: Repetition and Loop Statements
More Loops Topics Counter-Controlled (Definite) Repetition
Presentation transcript:

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

Algorithm Development

Structured Programming Sequence Selection Repetition no yes yes no

Conditional Expressions

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

Logical Operators ! not && and || or

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

Selection Statements

Selection Statements if if else switch

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

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

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

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

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?

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

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

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

Loop Structures

repetition while statement do while statement for statement

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

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.

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.

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

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.

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

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

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.

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;

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++)

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

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

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

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

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

Data Files

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.

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

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

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

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

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.

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

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;

Data file:grade.txt Output: no. score 1 56.000000 2 90.000000 1 56.00 2 90.00 3 78.00 4 56.00 5 67.00 6 89.00 Output: no. score 1 56.000000 2 90.000000 3 78.000000 4 56.000000 5 67.000000 6 89.000000 total score= 436.00 average score = 72.67 Press any key to continue

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;

grade.txt Output:same with previous 1 56.00 2 90.00 3 78.00 4 56.00 1 56.00 2 90.00 3 78.00 4 56.00 5 67.00 89.0 -99 -99 Output:same with previous

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;