You are on page 1of 46

Lecture IX

File I/O in C
Files in C
 In C, each file is simply a sequential stream of bytes. C
imposes no structure on a file.

 A file must first be opened properly before it can be accessed for


reading or writing. When a file is opened, a stream is
associated with the file.

 Successfully opening a file returns a pointer to (i.e., the address


of) a file structure, which contains a file descriptor and a file
control block.
Files in C
 The statement:
FILE *fptr1, *fptr2 ;
declares that fptr1 and fptr2 are pointer variables of type FILE.
They will be assigned the address of a file descriptor, that is, an
area of memory that will be associated with an input or output
stream.

 Whenever you are to read from or write to the file, you must first
open the file and assign the address of its file descriptor (or
structure) to the file pointer variable.
Algorithms
Example 1

 Consider an algorithm called “Wake up algorithm” followed by one


junior executive for getting out of bed and going to work:

 (1) Get out of bed,


 (2) take off pajamas,
 (3) take a shower,
 (4) get dressed,
 (5) eat breakfast,
 (6) drive to work. This routine gets the executive to work well
prepared to make critical decision
Example 2

 Suppose that the same steps are performed in a slightly different


order:

 (1) Get out of bed,


 (2) take off pajamas,
 (3) get dressed,
 (4) take a shower,
 (5) eat breakfast,
 (6) drive to work. In this case, our junior executive shows up for work
soaking wet.
Pseudocode

 Pseudocode is an artificial and informal language that helps you


develop algorithms. The pseudocode we present here is particularly
useful for developing algorithms that will be converted to structured
C programs. Pseudocode is similar to everyday English; it’s
convenient and user friendly although it’s not an actual computer
programming language.
 Pseudocode programs are not executed on computers. Rather, they
merely help you “think out” a program before attempting to write it in
a programming language such as C. In this chapter, we give several
examples of how pseudocode may be used effectively in developing
structured C programs.
The Decision Control Structure

 Normally, statements in a program are executed one after the other


in the order in which they’re written. This is called sequential
execution. Various C statements we’ll soon discuss enable you to
specify that the next statement to be executed may be other than
the next one in sequence. This is called transfer of control.
The if Selection Statement
 Selection structures are used to choose among alternative courses
of action. For example, suppose the passing grade on an exam is
60. The pseudocode statement
If student’s grade is greater than or equal to 60
Print “Passed”
 determines if the condition “student’s grade is greater
than or equal to 60” is true or false.If the condition is
true, then “Passed” is printed, and the next pseudocode
statement in order is “performed” (remember that
pseudocode is not a real programming language). If
the condition is false, the printing is ignored
The preceding pseudocode If statement may be written in
C as

if ( grade >= 60 )
{
printf( "Passed\n" );
}
 Notice that the C code corresponds closely to the
pseudocode. This is one of the properties of pseudocode
that makes it such a useful program development tool.
Flowcharting the single-selection if
statement.
The generic form of if…else

if ( this condition is true )


execute this statement ;
Exercise 1

 While purchasing certain items, a discount of 10% is


offered if the quantity purchased is more than 1000. If
quantity and price per item are input through the
keyboard, write a program to calculate the total
expenses.
Execise 2

 The current year and the year in which the employee joined the
organization are entered through the keyboard. If the number of
years for which the employee has served the organization is greater
than 3 then a bonus of $2500 is given to the employee. If the years
of service are not greater than 3, then the program should do
nothing.
The if…else Selection Statement

 The if selection statement performs an indicated action only when


the condition is true; otherwise the action is skipped. The if…else
selection statement allows you to specify that different actions are to
be performed when the condition is true than when the condition

is false. For example, the pseudocode statement


If student’s grade is greater than or equal to 60
Print “Passed”
else
Print “Failed”
The preceding pseudocode If…else statement may be
written in C as

if ( grade >= 60 )
{
printf( "Passed\n" );
} /* end if */
else
{
printf( "Failed\n" );
} /* end else */
The flowchart of if…else
Nested if…else statements

 test for multiple cases by placing if…else statements


inside if…else statements. For example, the following
pseudocode statement will print A for exam grades
greater than or equal to 90, B for grades greater than or
equal to 80, C for grades greater than or equal to 70, D
for grades greater than or equal to 60, and F for all other
grades.
Pseudocode for nested if…else
If student’s grade is greater than or equal to 90
Print “A”
else
If student’s grade is greater than or equal to 80
Print “B”
else
If student’s grade is greater than or equal to 70
Print “C”
else
If student’s grade is greater than or equal to 60
Print “D”
else
 Print “F”
This pseudocode may be written in C as

if ( grade >= 90 )
printf( "A\n" );
else
if ( grade >= 80 )
printf("B\n");
else
if ( grade >= 70 )
printf("C\n");
else
if ( grade >= 60 )
printf( "D\n" );
else
printf( "F\n" );
Forms of if
The if statement can take any of the following forms:

 (a) if ( condition ) (d) if ( condition ) {


do this ; do this ;
and this ;
 (b) if ( condition )
}
{ else
do this ; {
do this ;
and this ;
and this ;
} }
 (c) if ( condition )
do this ;
else
do this ;
 (e) if ( condition ) (f) If( condition )
do this ; {
else if ( condition )
do this ;
{ else
if ( condition ) {
do this ; do this ;
and this ;
else }
{ }
do this ; else
do this
and this ;
}
}
Exercise 3

A- If cost price and selling price of an item is input through the


keyboard, write a program to determine whether the seller has made
profit or incurred loss. Also determine how much profit he made or
loss he incurred.

B - Any integer is input through the keyboard. Write a program to find


out whether it is an odd number or even number.
C- Any year is input through the keyboard. Write a program to
determine whether the year is a leap year or not.

Note: A leap year has 366 days, as opposed to a common year, which
has 365. Nearly every 4 years is a Leap Year, and we add a Leap
Day, an extra – or intercalary – day on February 29
Loops

The versatility of the computer lies in its ability to perform


a set of instructions repeatedly. This involves repeating
some portion of the program either a specified number of
times or until a particular condition is being satisfied.This
repetitive operation is done through a loop control
instruction.
There are three methods by way of which
we can repeat a part of a program

 (a) Using a for loop


 (b) Using a while loop
 (c) Using a do-while loop
The while loop

 A repetition statement allows you to specify that an


action is to be repeated while some condition remains
true.

 The pseudocode statement


While there are more items on my shopping list
Purchase next item and cross it off my list
Example to print numbers 1 to 10

int i=1;
while(i<=10)
{
printf("%d\n",i);
i++;
}
Formulating Algorithms: Counter-
Controlled Repetition

 A class of ten students took a quiz. The grades


(integers in the range 0 to 100) for this quiz are
available to you. Determine the class average
on the quiz.
Understanding The Problem

 The class average is equal to the sum of the grades


divided by the number of students. The algorithm for
solving this problem on a computer must input each of
the grades, perform the averaging calculation, and print
the result.
Pseudocode to solve the problem
 1 Set total to zero
 2 Set grade counter to one
 3While grade counter is less than or equal to ten
 4 Input the next grade
 5 Add the grade into the total
 6 Add one to the grade counter
 7 Set the class average to the total divided by
ten
 8 Print the class average
Code in C language

total=0; // intialize total


counter=1; // initialize counter
while(counter<=10) // loop 10 times
{
printf("Enter Grade:"); //prompt for input
scanf("%d",&grade); // read grades from user
total=total+grade; // add grade to total
counter=counter+1; // increment counter
}
average=total/10; // integer division
printf("class average is %d\n",average); // display the average
The For loop

 The general form of for statement is as under:


for(initialise counter; test counter; increment counter)
{
do this;
and this;
a this;
}
Structure of for loop
Example

 main()
{
inti;
for(i=1;i<=10;i++)
printf(“%d\n”,i);
}
All the following increment can be used:
i=i+1
i++
i+=1
Do- while loop

do
statement
while ( condition );
Example

main()
{
int counter=1;
do{
printf(“%d”,counter);
} while(++counter<=10);

Note: The code is tested at the end


The Break statement

 We often come across situations where we want to jump out of a


loop instantly, without waiting to get back to the conditional test. The
keyword break allows us to do this. When break is encountered
inside any loop, control automatically passes to the first statement
after the loop. A break is usually associated with an if. As an
example, let’s consider the following example.
Example Break statement

for(x=1;x<=10;x++)
{

if(i==5)
{
break;
}
printf ("%d\n",x);

}
The continue Statement

 In some programming situations we want to take the control to the


beginning of the loop, bypassing the statements inside the loop,
which have not yet been executed. The keyword continue allows us
to do this. When continue is encountered inside any loop, control
automatically passes to the beginning of the loop.

 A continue is usually associated with an if. As an example, let's


consider the following program.
How works

Exercise 1

Write a C statement to accomplish each of the following tasks.


a) Define variables sum and x to be of type int.
b) Initialize variable x to 1.
c) Initialize variable sum to 0.
d) Add variable x to variable sum and assign the result to variable sum.
e) Print "The sum is: " followed by the value of variable sum
Exercise 2

What is wrong with the following while repetition statement (assume z


has value 100),which is supposed to calculate the sum of the integers
from 100 down to 1:
while ( z >= 0 )
sum += z;
Exercise 3
 Formulate a pseudocode algorithm for each of the following:

a) Obtain two numbers from the keyboard, compute their sum and
display the result.
b) Obtain two numbers from the keyboard, and determine and display
which (if either) is the larger of the two numbers.
c) Obtain a series of positive numbers from the keyboard, and
determine and display their sum. Assume that the user types the
sentinel value -1 to indicate “end of data entry.”
Q &A

You might also like