Introduction to C Programming - · PDF fileET2560 Introduction to C Programming Final Exam...

Preview:

Citation preview

ET2560 Introduction to C ProgrammingET2560 Introduction to C Programming

Final Exam Review

Instructor : Stan Kong

Email : skong@itt‐tech.eduEmail : skong@itt tech.edu

Figure 1.3

fComponents of a Computer

Main Memory• Holds active programs and dataHolds active programs and data.

• Contents:Bit O bi di it 0 1– Bit: One binary digit—0 or 1

– Byte: Eight bits—1 character

– Word: A group of bytes

• Write is a destructive operation.

• Read is not a destructive operation.

• ROM – Read only Memory. (non‐volatile).ROM  Read only Memory. (non volatile).

• RAM – Random Access Memory (volatile)  

Figure 1.11

Entering, Translating, and Running a High‐Level Language Program

Begin and End ShapesBegin and End Shapes

These shapes are used to begin and end aThese shapes are used to begin and end a flowchart

The beginning shape has the algorithm nameThe beginning shape has the algorithm name as its label

Th d h t i th d “E d”The end shape contains the word “End”

Rectangle Shape – Actionsg p

Rectangle has one entry and one exit

The text in the rectangle is pseudo‐code corresponding to one step in the algorithm

Diamond Shape – Decision Pointp

One entry two exits (one for “yes” the otherOne entry, two exits (one for  yes , the other for “no”)

Contains one question with yes/no answerContains one question, with yes/no answer

C Program ExampleC Program Example#include <stdio.h>#define PI 3.14159

/*Your name*//*This program accepts the radius of a circle, calculates the area, and outputs the 

radius and the area */radius and the area. /

int main(void) {double radius;   /*Stores the radius entered by the user*/; / y /double cir;                       /* circumferre */double area;      /*Stores the area after the calculation*/

printf("Enter the radius of the circle>");scanf("%lf", &radius);area = PI * radius * radius;  /*Calculates the area as PI X radius X radius and stores the results in area*/printf("The area of a circle with a radius of %f is %f\n" radius area);printf( The area of a circle with a radius of %f is %f\n , radius, area);

return (0); }

Scope of NamesScope of Names

• Identifiers (variables and functions) defined in the main function can be accessed anywhere within the program – Unless the same name is used within a function or block

• Identifiers (variables and functions) defined in a function can only be accessed within that function 

• Identifiers (variables and functions) defined in 

9

( )a block can only be accessed within that block

Demo 1‐ ScopeDemo 1 Scope #include<stdio.h>

Int main(void){

int x = 0;

i tf("Thi l %d\ " )printf("This x equals %d\n", x);

{

int x=10;int x=10;

x += 10;

printf(" This x equals %d\n", x);p ( q )

}

printf(" The original x equals %d\n", x);

return(0);

} 10

Relational and Equality Operatorsq y p

Table 4‐1

Sample ConditionsSample Conditions

Table 4‐2

Logical OperatorsLogical Operators

• And &&• And  &&(temperature > 90) && (humidity > 0.90)

O ||• Or   ||(salary < MIN_SALARY) || (dependents > 5)

• Not   !!(0 <= n && n <= 100)

Operator PrecedenceOperator PrecedenceTable 4.6

Selection Control StructureSelection Control Structure

E ec tion path changes based on a conditionExecution path changes based on a condition

ConditionF T

DoDo this

Do something 

else

Character ComparisonsCharacter Comparisons

Table 4.8

if Statement with One Alternativeif Statement with One Alternative 

if (condition)ti t f if taction to perform if true;

if (R != 0.0)current = voltage / R;current voltage / R;

if Statement with Two Alternativesif Statement with Two Alternativesif (condition)

action to perform if true;action to perform if true;elseaction to perform if false;action to perform if false;

if (voltage > 3 3 )if (voltage > 3.3 )printf(“A digital High is present!"\n);

lelseprintf(“A digital Low is present!\n");

BlocksBlocks

if (condition){

if (condition) {statement;

statement;statement;

}

statement;}l {}

else{

else {statement;statement;{

statement;statement;

statement;}

}

Nested if StatementsNested if Statements

if (x > 0)num = num + 1;

else {

if (x < 0)num_neg = num_neg + 1;

else /* x equals 0 */num zero = num zero + 1;

}

_ _ ;

Nested if StatementsNested if Statements

if (x > 0)num = num + 1;

else {

if (x < 0)num_neg = num_neg + 1;

else /* x equals 0 */num zero = num zero + 1;

}

_ _ ;

Multiple Alternative if StatementsMultiple Alternative if Statements/* Display perception of noise loudness */

if (noise_db <= 50)

printf(“%d‐decibel noise is quiet.\n”, noise db);printf( %d decibel noise is quiet.\n , noise_db);

else if (noise_db <=70)

printf(“%d‐decibal noise is intrusive. \n”, noise_db);

else if (noise_db <= 90)

printf(“%d‐decibel noise is annoying.\n”, noise_db);

else if (noise_db <= 110)

printf(“%d‐decibel noise is very annoying. \n”, noise_db);

elseelse

printf(“%d‐decible noise is uncomfortable. \n”, noise_db);

Switch Statement• The switch statement  is used in C to select one of several alternatives. 

The switch statement is especially useful when the selection is based on the value of a single variable or a simple expression ( called the controllingthe value of a single variable or a simple expression ( called the controlling expression). The value of this expression may be of type int or char, but not of type double.

• SYNTAX:  switch (controlling expression) {S s tc (co t o g e p ess o ) {

label set1 

statements1,

break;

label set2  

statements2,

break;

label setn  

statementsn,

break;                      ;

default : statementsd,

break;      

}                                          label setn is  ‐ case constant value :                  

Switch and FlowchartSwitch and Flowchart

double discount; // Usually code would be read in char code = 'B' ; switch ( code ){{

case 'A': discount = 0.0; break;

'B'case 'B': discount = 0.1; break;

case 'C':discount = 0.2; break;

default: discount = 0 3;discount = 0.3;

}

for Loop Stylefor Loop Stylefor ( counter start status;

condition is true;

update counter; ) {update counter; ) {Statements to be repeated;

}for (i=0 ;i <= 10; i++){for (i 0 ;i 10; i ){

Statements to be repeated;

}}

Sum & Average with afor Loop

sum=0;for (i=0; i < 10; i++;){

printf(“Enter score: “);scanf(“%d”, &quiz);sum = sum + quiz;

}ave = sum / count;ave = sum / count;

Perform a known number actions with a for Loop

product=0; multiplier=5;product 0; multiplier 5;multiplicand=3;f (i 0for (i=0;

i < multiplier; i++;){

product += multiplicand;p p ;

}

Counter‐Controlled LoopsCounter Controlled Loops• Used when you know the number of times the loop must executeloop must execute

• General steps:1. Set loop control variable to 0

2. Loop control variable < final value• Execute statements

• Increase loop control variable by 1

• For loop is best choice, but while loop will work!  

• Variable called accumulator to hold count value.

Off by One ErrorsOff by One Errors

• This loop executes n+1 times:• This loop executes n+1 times:for (count = 0; count <= n; ++count)++count)sum += count;

Al t t t th l b d i t• Always test at the loop boundaries to verify the loop does the right thing.

Conditional while LoopConditional while Loop

while (condition is true) {while (condition is true) {Statements; 

}

while (freq <= 100000){Statements;Statements;

}

Perform a known number actions with a while Loop

product=0; multiplier=5;product 0; multiplier 5;multiplicand=3; ctr=0;hil ( l i li ){while (ctr < multiplier){product += multiplicand;count++;

}

Sum & Average with awhile Loop

count=0, sum=0;while (count < 10){

printf(“Enter score: “);scanf(“%d”, &quiz);sum = sum + quiz;count++;

}}ave = sum / count;

Conditional LoopsConditional Loops

• Example using a while statement:Example using a while statement:printf("Enter a positive value: ");scanf("%d", &num);scanf( %d , &num);while (num < 0) {

printf("Negative, try again> ");p t ( egat e, t y aga );scanf("%d", &num);

}}

Sentinel‐Controlled LoopSentinel Controlled Loop

• Data value is used to determine end‐Data value is used to determine endpoint.

• General format• General format1. Get a line of data2. While the sentinel value has not been 

encounteredh d lia. Process the data line.

b. Get another line of data.

Correct Sentinel Loopp1. Initialize sum to 0

f2. Get first score

3. while score is not the sentinel

a. Add score to sum

b Get next scoreb. Get next score

Sentinel‐Controlled Loopsum=0;while (score != -99){while (score != 99){

printf(“Enter score, -99 to end”);f(%d” & )scanf(%d”, &score);

if (score !=-99) {sum += score;count++;

}

}ave= sum/count;

Flag‐Controlled Loopsg p

• Declare a flag variable of type int.

I i i li h fl l h i h i• Initialize the flag to a value that is not the exit condition.

• Loop on the flag becoming true or false.

• Set the flag within the loop to indicate exit g pcondition.

Flag‐Controlled Loopdone=0;while (!done){while (!done){

printf(“Enter temperatures”);f(“%d” &t )scanf(“%d”, &temp);

if (temp > 212) done = 1;

}printf(“Water is boiling”);

Break statementflag=1;while (flag){while (flag){

printf(“Enter temperatures”);f(%d” &t )scanf(%d”, &temp);

if (temp > 212) break;

}printf(“Water is boiling”);

Nested loopsflag=‘y’;while (flag){

invalid=1;while (invalid)printf(“Enter score”);scanf(%d”, &score);if (score>=0 && <= 100)if (score>=0 && <= 100)

invalid=0;}}printf(“Enter another? y/n”);scanf(“%c”, &flag);

}

do‐while Statementdo while Statement

do {{Statements; 

} hil ( diti i t )} while (condition is true);** Do while loop always executes at least once.

do {printf(“Enter temperatures”);scanf(“%d”, &temp);

} while (temp <= 212);

Sample ConditionsSample Conditions

Table 4‐2

Types of LoopsTypes of Loops

Table 5.1

PointersPointers• A pointer is a variable that holds the address of another variableof another variable.

• It is an advanced concept, however for our p rposes e ill se it ith certain f nctionspurposes we will use it with certain functions.

• Two new operators

• & is the “Address of” operator

• * is the “Direct Reference” operator p– (sometimes called the dereference operator)

• Examples

44

• Examples 

PointersPointers

• Pointers allow us to directly access a variablePointers allow us to directly access a variable at its memory location.

• This allows us to “by pass” scoping limitations• This allows us to  by‐pass  scoping limitations.

45

/* pointer demo */

#i l d < tdi h>#include<stdio.h>

int main(void){

int i = 4, j = 5;

int *p_i, *p_j;              /* define two integer pointers */ 

p i = &i;p_ ;

p_j = &j;

printf("i equals %d and its address is %d\n", i, &i);

printf("j equals %d and its address is %d\n\n" j &j)printf("j equals %d and its address is %d\n\n", j, &j);

printf("The pointer of i p_i equals %d, it points to the value of i %d\n", p_i, *p_i);

printf("The pointer of j p_j equals %d, it points to the value of i %d\n", p_j, *p_j);

printf("So the i %d is the same as *p_i %d\nAND\n",i, *p_i);

printf("So the p_i %d is the same as &i %d\nAND\n",p_i, &i);

printf("The address of the pointer p i is %d\n",&p i);p ( p p_ \ , p_ );

return(0);

} 46

PointersPointers• int i = 5;  

– is a integer variable equal to 5is a integer variable equal to 5

• int *p_i;  – is a pointer reads as “pointer to I”is a pointer, reads as  pointer to I

• p_i = &i; – assigns the address of i to the pointer of i– assigns the address of i to the pointer of i

• *p_i Reads as “the direct reference to i”– Reads as  the direct reference to i

– This value is five

47

Figure 3.6

“ ”Function sqrt as a “Black Box”

48

Function typesFunction typesReturn Type Purpose # Input 

Parameters# Output 

Parameters Return Result

Defined Type To return a single value 0+ 1 Same as type

void To produce a printed output 0+ 0 Nonep p p

void To compute multiple results 0+ 2+ Pointers

void To modify input arguments 1+ none Pointers

4949

Functions with Input ParametersFunctions with Input Parameters

• Data is passed into the function, but cannot be difi d b h f imodified by the function.

int main(void) {double calcFr(double L double C) ; //prototypedouble calcFr(double L, double C) ; //prototypedouble C1, L1, resonantfreq;C1 = 47E-6; L1 = 100E-3;resonantfreq = calcFr (C1, L1); //invocation

return 0;}

double calcFr(double L, double C) { // definitiondouble Fr;double Fr;Fr = 1 / (2*PI*sqrt(L*C));return (Fr);

}

50

Figure 3.20

Function with Input ArgumentsFunction with Input Arguments and One Result

51

Function with Multiple Results

• Use the address of operator (&) before the name of the variablevariable.

• Example:void calcVoltageCurrent(double W, int R, double *volts, *amps);

calcVoltageCurrent(W, R, &volts, &amps);void calcVoltageCurrent(double W, int R, double *volts, *amps){

*volts = sqrt(W * R);q ( );*amps = sqrt(W / R);

}

5252

Function with Multiple ResultsFunction with Multiple Resultsint main(void){

( * * )void calcVoltageCurrent(double W, int R, double *V, double *I);double power = .1, volts, amps;    int load = 1000;

calcVoltageCurrent(power load &volts &amps);calcVoltageCurrent(power, load, &volts, &amps);printf("V is %f and \n I is %f\n", volts, amps);

return 0;}return 0;}

void calcVoltageCurrent(double W, int R, double *V, double *I){*V  = sqrt(W * R);q ( );*I = sqrt(W / R);

}

53

separate(value, &sn, &whl, &fr);

5454

Figure 6.11

Structure Chart for Common Fraction Problem

55

Top‐Down vs. Bottom‐Up TestingTop Down vs. Bottom Up Testing

Top‐down testing Bottom‐up testing• Create function stubs to 

test the main program.• Separately test each 

function before integration• Add each function as it is 

complete and retest.

integration.• Create a driver to test the 

function.• Unit testing – testing a 

functionI t ti t ti• Integration testing –testing the complete program after all 

56

functions have been added

Numeric Types & RangesNumeric Types & Ranges

Numerical InaccuraciesNumerical Inaccuracies

• Representational errorp– Round‐off error– Caused by coding a real number as a finite number of digits

– Magnified through repeated computations• Cancellation error

– Caused by adding a very large number and a very smallCaused by adding a very large number and a very small number

• Arithmetic underflow– Caused by multiplying very small numbersCaused by multiplying very small numbers

• Arithmetic overflow– Caused by multiplying very large numbers

Implicit ConversionImplicit Conversion

• Assume variables:ssu e a ab es:int k=5, m=4, n;double x=1.5, y=2.1, z;

• Operands of different types– Narrow type converted to wider type before 

l lcalculationk + x /*Evaluates to 6.5 */

• Expression evaluated before assignment• Expression evaluated before assignmentz = k / m; /*Evaluates to 1, assigns 1.0 */n = x * y; /* Evaluates to 3.5, assigns 3. */

Explicit ConversionExplicit Conversion

• Convert data type using a cast• Convert  data type using a castint n1, d1;

f ti (& 1 &dl)scan_fraction(&n1, &dl);/*integer division performed. n1=2 d1=4 result=0*/n1=2, d1=4, result=0*/

frac = n1 / d1; /*U t t f fl ti/*Use cast to force floating point division. Result = 1.5*/

frac = (double)n1 / (double)n2;frac = (double)n1 / (double)n2;

Enumerated TypesEnumerated Types• Used to improve program readability

typedef enum{Black, Brown, Red, … White}

color_code_t;

• Black is an enumeration constant with the value 0, Brown is 1, Red is 2 ….. White is 9!

• Add typedef enum declarations in header immediately after preprocessor directives.int color_code;color_code = brown + red;printf(“The color code is %d \n “, color_code);

Figure 8.1

Elements of Array xElements of Array x

Array Declaration& Initialization

int variableName[10];int variableName[] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73 79 83 89 97};73, 79, 83, 89, 97};

Processing an Array Using a LoopProcessing an Array Using a Loop

• Use a counter‐controlled loopUse a counter controlled loop#define SIZE 11int square[SIZE] i;int square[SIZE], i;for (i= 0; i < SIZE; ++i)

sq are[i] i * isquare[i] = i * i;

Array Search AlgorithmArray Search Algorithm

• Assume the target has not been found.• Start with the initial array element• Repeat while the target is not found and there are 

more array elementsmore array elements– If the current element matches the target

• Set a flag to indicate that the target has been found.– Else

• Advance to the next array element.• If the target was found:

– Return the target index as the search result.g• Else

– Return ‐1 as the search result.

Two‐dimensional ArrayTwo dimensional Array

• Two‐dimensional arrayychar tictac[3][3];

Initializing a Two‐dimensional ArrayInitializing a Two dimensional Array

char tictac[3][3] = {{‘X' ‘O' ‘X'}{‘X', ‘O', ‘X'}, {‘O', ‘X', ‘O'}, {‘O', ‘X', ‘X'}}}

Parallel ArraysParallel Arrays

#define NUM STUDENTS 50_int id[NUM_STUDENTS];double gpa[NUM STUDENTS];double gpa[NUM_STUDENTS];

Arrays with Multiple DimensionsArrays with Multiple Dimensions

• ANSI requires C compilers to allow arrays of six dimensions.six dimensions.

• Two‐ and three‐ dimensional arrays are most commoncommonint enroll[MAXCRS][5][4];

course campusyear

Figure 8.20

Three‐Dimensional Array enrollThree Dimensional Array enroll

Array Elements as Function ArgumentsArray Elements as Function Arguments

• Array elements can be used as input or outputArray elements can be used as input or output arguments.

• Consider the function with the prototype:• Consider the function with the prototype:void do_it (double arg_1, double *arg2 p double *arg3 p);*arg2_p, double *arg3_p);

• Pass array x elements as arguments:d i ( [0] [1] [2])do_it(x[0], &x[1], &x[2]);

input argument output argumentsinput argument output arguments

Figure 8.4

Data Area for Calling Module and Function do itData Area for Calling Module and Function do_it

Figure 8.8

Diagram of a Function ThatDiagram of a Function That Computes an Array Result

Arrays as ParametersArrays as Parameters

• Passing an array as a parameter passesPassing an array as a parameter passes the pointer to the array, not a copy.– Function can modify the arrayFunction can modify the array.

• Function prototype that accepts an array:id fill (i t li t[] i tvoid fill_array (int list[], int n, int, in_value); /* Clearer */

ororvoid fill_array (int *list, int n, int, in_value);_

Passing an Array ArgumentPassing an Array Argument

• Because an array argument refers to a• Because an array argument refers to a memory location, no subscript is 

i drequired:int x[5];fill_array(x, 5, 1); /* better */

orfill_array(&x[0], 5, 1);

Preventing ModificationPreventing Modification

To prevent an array from being modified by a function use the const keyword in thea function, use the const keyword in the function declaration:

int get min sub(const doubleint get_min_sub(const double data[], int data_size) {…}

Declaring and Initializing StringsDeclaring and Initializing Strings

• Declare a string as an array of charactersDeclare a string as an array of characterschar string_var[30];

• Declare and initialize a string• Declare and initialize a stringchar str[20] = "Initial value"

String Input & OutputString Input & Output

• InputInputscanf("%s", &stringName);

OrOrscanf("%s", stringName);

• Outputprintf("%s\n", stringName);

Figure 9.1

Ri ht d L ft J tifi ti f St iRight and Left Justification of Strings

Formatting String OutputFormatting String Output

• Right‐justified stringsRight justified stringsprintf("***%8s***%3s***\n", "Short", "Strings");Short , Strings );

*** Short***Strings***

• Left justified strings• Left‐justified stringsprintf("%-20s\n", president);

Figure 9.3

Execution of scanf ("%s" dept);Execution of scanf ( %s , dept);

#define NUM_LENGTH 10

#include <stdio.h>

int main(void){

char inp_numstr[NUM_LENGTH];

int inp_num;

printf("Enter integer only up 10 digit in length \n");

scanf("%s", inp_numstr);

printf("Input number is : %s\n", inp_numstr);

inp num = atoi(inp numstr);    /* convert string to int*/p_ ( p_ ); / g /

printf("Converted number is %d\n", inp_num);

}

Input and Output f f ifor an Array of Strings

#define NUM_PEOPLE 30#define NAME LEN 25_

. . .char names[NUM_PEOPLE][NAME_LEN];

for (i = 0; i < NUM_PEOPLE; ++i) {scanf(“%s%d”, names[i]);printf(“%-35s\n”,names[i]);

}

Functions in string.hFunctions in string.h

• Copy one string to • Compare stringsCopy one string to another– strcpy

Compare strings– strcmp

strncmp– strcpy 

– strncpy

C t t t i

– strncmp

• Learn string length• Concatenate strings

– strcat– strlen

• Separate a string – strncat using a delimiter

– strtok

String AssignmentString Assignment

• Cannot use standard assignment exceptCannot use standard assignment except during initializationchar one str[20];char one_str[20];one_str = "Test string" /*illegal*/

• Use strcpy or strncpy instead• Use strcpy or strncpy insteadchar one_str[20];strcpy(one str "Test String");strcpy(one_str, Test String );strncpy(one_str, "Test String", 20););

Copying SubstringsCopying Substrings

• Use strncpy to identify the number of characters to copycharacters to copy.char month[5]; h 1[15] 30 1996char s1[15] = "Jan. 30, 1996";

strncpy(month, s1, 4);month[4] = '\0';

Copying a Substring from the MiddleCopying a Substring from the Middle

• Pass a pointer to the element where the copy should start.char day[3]; y[ ]char s1[15] = "Jan. 30, 1996";strncpy(day &s1[5] 2);strncpy(day, &s1[5], 2);Day[2] = '\0';

Concatenating Strings ‐ strcatConcatenating Strings  strcat

• Use strcat to concatenate one entireUse strcat to concatenate one entire string onto another.#define STRSIZ 10#define STRSIZ 10char first[STRSIZ] = “Georg“;char last[STRSIZ] = “Ohm";char last[STRSIZ] Ohm ;strcat(first, last); //“GeorgOhm"

Concatenating Strings ‐ strncatConcatenating Strings  strncat

• Avoid overflowAvoid overflow.#define STRSIZ 12char first[STRSIZ] = "Alessandro“;char first[STRSIZ] Alessandro ;char last[STRSIZ] = “Volta";AlessandroVolta is > than 12!strncat(first, last, 1); /* ”AlessandroV"*/

ComparisonComparison• char str1[]=“Amp”, str2[]=“Volt”;• if (str1==str2) // this does not work!!!• if (str1==str2)  // this does not work!!!• if (strcmp(str1,str2)==0) //does work!!!

Finding the String's LengthFinding the String s Length

• Use strlen to determine the number of Use st e to dete e t e u be ocharacters in a string  ‐ \0 not counted.char s1[] = "Charles Coulomb";

for (i=0; i<strlen(s1) ;i++)if (strcmp(s1[i], ‘ ‘)==0

printf(“Found space\n”);printf( Found space\n );

• strtok is a special function that will return portions of a string based upon a token. i.e.portions of a string based upon a token.  i.e. a comma or dash or space 

Character vs. StringCharacter vs. String

Character Input & OutputCharacter Input & Output

• ctype h Library• ctype.h Library

• Get a single character from standard input:int ch;ch = getchar();

• O tp t a character to standard o t• Output a character to standard out:putchar(ch);

Figure 9.15

Implementation of scanline Function Using getcharImplementation of scanline Function Using getchar

Character Analysis and ConversionCharacter Analysis and Conversion

• isalpha • isspacesa p a– is character A‐Z or a‐z

• isdigit

sspace– is character a whitespace character ( t b li )

g– is character 0‐9

• islower

(space, tab, newline)

• tolowerConvert to lower case

– is character lower case

• isupper

– Convert to lower case

• toupperConvert to upper case

– is character upper case

• ispunct

– Convert to upper case

** Note ctype h library– is character punctuation mark

 Note ctype.h library needed for all the functions

Figure 10.5

Trace of Function multiplyp y

Recursive AlgorithmRecursive Algorithm• if this is a simple case (or terminating case)

– solve it

• elseelse– redefine the problem using recursion

type RecursiveFunction(parameters){if (terminating condition is true)

return answer;return answer;else

answer = answer – RecursiveFunction(parameters);}}

Figure 10.1

Splitting a Problem into Smaller Problems

Newline and EOFNewline and EOF

• NewlineNewline– Represented by '\n'– Added from the keyboard by using a carriage y y g greturn

• EOF– Represents the end of a file

• ExamplepThis is a text file!<newline>It has two lines.<newline><eof>

EOF Sample Code ‐1EOF Sample Code  1

Figure 5.11  Batch Version of Sum of Exam Scores Program

/*

*  Compute the sum of the list of exam scores stored in the file scores.dat

*//

#include <stdio.h>       /* defines fopen, fclose, fscanf, fprintf, and EOF */

Int main(void)

{{

FILE *inp;             /* input file pointer    */

int   sum = 0,       /* sum of scores input so far */

score,               /* current score  */

input_status;  /* status value returned by fscanf */

inp = fopen("scores dat" "r"); /* inp will be equal to NULL if file open failed */inp   fopen( scores.dat ,  r );  /  inp will be equal to NULL  if file open failed  /

EOF Sample Code ‐2EOF Sample Code  2

(continued)

printf("Scores\n");

input_status = fscanf(inp, "%d", &score);

while (input status != EOF) {while (input_status != EOF) {

printf("%5d\n", score);

sum += score;

i f f(i "%d" & )input_status = fscanf(inp, "%d", &score);

}

printf("\nSum of exam scores is %d\n", sum);

fclose(inp);

return (0);

}}

StreamsStreams

• Input streamput st ea– Can receive from text input device or file– stdin normally represents input from the keyboard

• Output stream– Sends text to the display, a printer, or a file

td t ll t t t t th di l– stdout normally represents output to the display

• Error streamReferenced as stderr– Referenced as stderr

– Sends error information in a text stream– Output on the display in an interactive program

Escape SequencesEscape Sequences

Table 12.1

Escape Sequence ExampleEscape Sequence Example

• Output:

Final Report

• Using the code:Using the code:printf(“\f\t\t\tFinal Report\r\t\t\t \n“epo t\ \t\t\t____________\);

Placeholders for printf Format StringsPlaceholders for printf Format Strings

Table 12 2Table 12.2

Field Width, Justification, and PrecisionField Width, Justification, and Precision

Standard I/O vs File Pointer I/OStandard I/O vs. File Pointer I/O

Table 12.4

Binary FilesBinary Files

Advantages DisadvantagesAdvantages

• More optimal for storing structured data

Disadvantages

• Cannot create files with a text editorstoring structured data

• Smaller file size

• Read and write directly

a text editor

• Cannot view files with a text editor• Read and write directly, 

not conversion to text stream

text editor

• File format proprietary to applicationpp

Binary File FunctionsBinary File Functions

• fopenfopen– Use "wb" or "rb" as last parameter

• fwrite• fwritefwrite(&i, sizeof(int), 1, binaryp);fwrite(score, sizeof(int), 10, binaryp);fwrite(score, sizeof(int), 10, binaryp);

• freadfread(&i, sizeof(int), 1, binaryp);fread(&i, sizeof(int), 1, binaryp);fread(score, sizeof(int), 10, binaryp);

– Returns number of elements successfully read

Figure 12.3

Creating a Binary File of IntegersCreating a Binary File of Integers

Text Files vs. Binary Files ExampleText Files vs. Binary Files Example#define STRSIZ 10#define MAX 40typedef struct {

char name[STRSIZ];double diameter;double diameter;int moons;double orbit_time, rotation_time;

} planet t;} planet_t;double nums[MAX], data;planet_t a_planet;int I, n, status;, , ;FILE *plan_bin_inp, *plan_bin_outp, *plan_txt_inp,

*plan_txt_outp;FILE *doub_bin_inp, *doub_bin_outp, *doub_txt_inp,

*doub txt outp*doub_txt_outp

Opening the FilesOpening the Files

Text BinaryTextplan_txt_inp =

fopen("planets.txt", "r");

Binaryplan_bin_inp =

fopen("planets.bin", "rb");"r");

doub_txt_inp = fopen("nums.txt", "r");

"rb");doub_bin_inp =

fopen("nums.bin", "rb");"r");

plan_txt_outp = fopen("pl_out.txt", "w");

"rb");plan_bin_outp =

fopen("pl_out.bin", "wb");"w");

doub_txt_inp = fopen("nm_out.txt", "w");

"wb");doub_bin_inp =

fopen("nm_out.bin", "wb");w ); wb );

Copy One Planet Structure to MemoryCopy One Planet Structure to Memory

• TextTextfscanf(plan_txt_inp, "%s%lf%d%lf%lf", a_planet.name, &a_planet.diameter, &a_planet.moons, &a planet orbit time&a_planet.orbit_time, &a_planet.rotation_time

• BinaryBinaryfread(&a_planet, sizeof (planet_t), 1, plan_bin_inp);

Write One Planet Structure h ilto the Output File

• TextTextfprintf(plan_txt_outp, "%s %e %d %e %e", a planet.name,%e , a_planet.name, a_planet.diameter, a_planet.moons, a_planet.orbit_time, a_planet.rotation_time

• Binaryyfwrite(&a_planet, sizeof(planet_t), 1, plan_bin_outp);

Copy an Array of Numbers to MemoryCopy an Array of Numbers to Memory

• TextTextfor (i=0; i<MAX; ++i) {fscanf(doub txt inp "%lf"fscanf(doub_txt_inp, %lf , &nums[i];

}}

• Binaryf d( i f (d bl ) MAXfread(nums, sizeof (double), MAX, doub_bin_inp);

Write an Array of Numbers to MemoryWrite an Array of Numbers to Memory

• TextTextfor (i=0; i<MAX; ++i) {fprintf(doub txt outp "%e\n"fprintf(doub_txt_outp, %e\n , nums[i];

}}

• Binaryf it ( i f (d bl ) MAXfwrite(nums, sizeof (double), MAX, doub_bin_outp);

Fill nums with data il i h duntil EOF is reached

• Texte tfor (status=fscanf(doub_txt_inp, "%lf", &data);status != EOF && n < MAX; status=fscanf(doub_txt_inp, "%lf",

&data))&data))nums[n++] = data;

• BinaryBinaryn = fread(nums, sizeof (double), MAX, doub_bin_outp);

Recommended