Download as pdf or txt
Download as pdf or txt
You are on page 1of 94

COMPUTER

PROGRAMMING 2
COMP 20033

Compiled by:

Rosita E. Canlas
Lydinar D. Dastas
Aleta C. Fabregas
1
Computer Programming 2

Overview:
This Instructional Material is a continuation of programming 1 using C language. It gives
an experience on how to divide and simplify the code by utilizing the function, which
performs a specific task. Variables will be presented in its dynamic use, like grouping
them under one name which is called array, or they may be collected and grouped with
different data type under one record which is called structure. Address of variable is
determined as well using operator ampersand(&) and how its value can be accessed by
a pointer variable. Lastly the module shows how programs store results, and other data
of the program to a file using file handling.

Course Information:

Course Code: COMP 20033


Course Title: Programming 2
No. of Units: 3
No. of Hours: 5

Course Outcomes:
After successful completion of this instructional material, you should be able to:

• Demonstrate an understanding of basic data structures (such as an array-based


list, linked list, stack, queue, binary search tree) and algorithms
• Demonstrate the ability to analyze, design, apply, and use data structures and
algorithms to solve engineering problems and evaluate their solutions.
• Demonstrate an understanding of analysis of algorithms through the idea of
trade-offs and measurement of effectiveness.

Course Contents:
Unit 1 - Array is a sequence of data items that are of the same type, that are indexible,
and that are stored contiguously.

Unit 2 - Function is a section of a program which performs a specific task.

2
Unit 3 - Pointers is a variable that represents the location (rather than the value) of a
data item, such as a variable of an array element.

Unit 4 - Structures is a collection of variables that are referenced under one name,
providing a convenient means of keeping related information together

Unit 5 - Linear Linked List is a group of nodes or records set which are linked
together through the use of pointers.

Unit 6 - File Handling is a built-in structure definition that holds value into a storage
device.

References:

• C++ Programming 8th ed, Malik, D.S.,2018


• C++ how to Program, Deitel, Paul J.,2017
• Introduction to Programming C++, Zak, Dianne,2016
• Programming Logic and Design, 8 th ed/ 3rd edition, Joyce Farrel,2015
• Beginning Programming with C++ for Dummies, Davis, Stephen R.,2015

Grading System:

Class Standing 70%


• Assignments
• Unit Activities
• Programming Problems

Examination 30%

TOTAL 100%

There will be review quizzes but these are not graded and are not recorded. The review
quizzes will help you to prepare for the term examinations.

Final Grade = 50% of MidTerm Grade + 50% of FinalTerm Grade

3
Table of Contents
Unit 1 - Array …………………………………………………………………………… 4
Overview…………………………………………………………………………… 4
Unit Objectives………………………………………………………………………… 4
Course Materials……………………………………………………………………… 4
Activities/Assessment………………………………………………………………… 14
Unit 2 - Function……………………………………………………………………….. 16
Overview……………………………………………………………………………….. 16
Unit Objectives………………………………………………………………………… 16
Course Materials……………………………………………………………………… 16
Activities/Assessment………………………………………………………………… 27
Unit 3 - Pointers………………………………………………………………………... 31
Overview……………………………………………………………………………….. 31
Unit Objectives………………………………………………………………………… 31
Course Materials……………………………………………………………………… 31
Activities/Assessment………………………………………………………………… 43
Unit 4 - Structure………………………………………………………………………. 45
Overview……………………………………………………………………………….. 45
Unit Objectives………………………………………………………………………… 45
Course Materials……………………………………………………………………… 45
Activities/Assessment………………………………………………………………… 53
Activities/Assessment Part 2………………………………………………………… 61
Unit 5 - Linear Linked List……………………………………………………………. 63
Overview……………………………………………………………………………….. 63
Unit Objectives………………………………………………………………………… 63
Course Materials……………………………………………………………………… 63
Activities/Assessment………………………………………………………………… 70
Unit 6 - File Handling………………………………………………………………….. 75
Overview……………………………………………………………………………….. 75
Unit Objectives………………………………………………………………………… 75
Course Materials……………………………………………………………………… 75
Activities/Assessment………………………………………………………………… 90

4
Unit 1 - Array

Overview:

In this unit, you will learn to work with arrays. You will learn to declare, initialize and access
elements of an array with the help of examples. An array is a collection of data items, all
of the same type, accessed using a common name. A one-dimensional array is like a list;
A two dimensional array is like a table; The C language places no limits on the number of
dimensions in an array, though specific implementations may.

Unit Objectives:

After successful Completion of this unit, you should be able to:

• know in details the basic concepts of Arrays.


• be more familiar with the different uses of Arrays.
• be able to apply the use of Arrays in some complicated applications.
• make the student develop good programming techniques using Arrays.

Course Materials:

ARRAY CONCEPTS

Imagine we have a problem that requires 20 integers to be processed. We need


to read them, process them, and print them. We must also keep these 20 integers in
memory for the duration of the program. We can declare and define 20 variables, each
with a different name, as shown in the figure below.

Number0

Number1

Number2

. .
. .
. .
Number19

Illustration: Twenty variables

5
But having 20 different names creates another problem. How can we read 20
integers from the keyboard and store them? To read 20 integers from the keyboard, we
need twenty references, each to one variable. Furthermore, once we have them in
memory, how can we print them? To print them, we need another twenty references.

Although this may be acceptable for 20 integers, it is definitely not acceptable for
200 or 2000 or 20000 integers. To process large amounts of data we need a powerful
data structure, such as array.

Characteristics of an Array
An array is a fixed-size, sequenced collection of elements of the same data type.

An array is a sequence of data items that are of the same type, that are indexible, and that
are stored contiguously.

Arrays are data type that is used to represent a large number of homogenous values.
Since an array is a sequenced collection, we can refer to the elements in the array as the
first element, the second element, and so forth until we get to the last element. If we were
to put our twenty numbers into an array, we could designate the first element as shown
below.

Number0

In similar fashion, we could refer to the second number as Number1, and the third number
as Number2. Continuing the series, the last number would be Number19.

Process twenty variables

Number0 Number1 … Numbern-1

What we have seen is that the elements of the array are individually addressed through
their subscripts. This concept is graphically shown in the next figure to be presented. The
array as a whole has a name, numbers, but each member can be accessed individually
using its subscript.

The advantages of the array would be limited if we didn’t also have programming
constructs that would allow us to process the data more conveniently. Fortunately, there
is a powerful set of programming constructs – loops- that makes array processing easy.

Number0 Number[0]

Number1 Number[1]

. .
. .
. .
.Number19 .
Number[19]

a. Subscript form b. Index from

6
An array of numbers

We can use loops to read and write the elements in an array. We can use oops to
add, subtract, multiply, and divide the elements. We can also use loops for more complex
processing such as calculating averages.

But one question still remains. How can we write an instruction so that at one time it refers
to the first element of an array, and the next time it refers to another element. IT is really
quite simple: we simply borrow from the subscript concept we have been using.

Rather than using subscripts, however, we will place the subscript value in square
brackets. Using this notation, we would refer to Number 0 as : Number[0]

Following the convention, Number 1 becomes Number[1] and Number 19 becomes


Number[19]. This is known as indexing. Using reference, we now refer to our array using
the variable i : Number[i]

USING ARRAYS IN C

We will first show how to declare and define arrays. Then we will look at several typical
applications using arrays including reading values into arrays, accessing and exchanging
elements in arrays, and printing arrays.

Declaration and Definition

An array must be declared and defined before it can be used. Declaration and definition
tell the compiler the name of the array, the type of each element, and the size or number
of elements in the array. The size of the array is a constant and must have a value at
compilation time.

#include<stdio.h>
#include<conio.h>
int scores[20], i, sum=0;

void main()
array declaration

{
clrscr();
printf(“please enter 20 scores:\n”);
for(i=0; i<20; i++)
{ scanf(“%d”, &scores[i]);
sum=sum + scores[i];
}
getch();
}

7
Declaring and Defining Arrays

An array is defined in much the same manner as ordinary variables, except that each array
name must be accompanied by a size specification (the number of elements). For one
dimensional array, the size is specified by a positive integer expression enclosed in square
brackets. The expression is usually written as a positive integer constant.

The General Form – One-dimensional array

storage class data-type array[expression];

where storage class refers to storage class of the array, data-type is the data type, array
is the array name and expression is positive-valued integer expression that indicates the
number of array elements. Storage class is optional.

Example of one-dimensional array definition or array declaration:

int ccmit[5];
char bscs[30];
float bsit[20];
double ITCS[12];

the first line indicates that ccmit is a 5 element integer array, the second line describes
that bscs is a 30 element character array. In line 3, bsit is defined as 20 element floating
point array and the last line, ITCS is a 12 element double array.

Consider the following array definition:

int x[4] = {1, 2, 3};


float y[5] = {1.0, 1.25, 1.5};

The results on an element by element basis are:

x[0] = 1 y[0] = 1.0

x[1] = 2 y[1] = 1.25

x[2] = 3 y[2] = 1.5

x[3] = 0 y[3] = 0

y[4] = 0

In each case, all of the array elements are automatically set to zero except those that have
been explicitly initialized within the array definition.

One dimensional array string data type – a character in a string can be accessed either
as an element in an array by making use of a pointer to character. The flexibility it provides
makes C especially useful in writing string processing programs. The standard library
provides many useful string handling functions.

8
Strings are handled somewhat differently. In particular, when a string constant is assigned
to an external or a static character array as part of the array definition, the array size
specification is usually omitted. The proper array size will be assigned automatically. This
will include a provision for the null character which is ‘\0’ and automatically added at the
end of every string.

Example:

Consider the character array definition. It includes an initial assignment of the string
constant “CCMIT”.

char college[6] = “CCMIT”;

It defines the following five element character array:

college[0] = ‘C’;
college[1] = ‘C’;
college[2] = ‘M’;
college[3] = ‘I’;
college[4] = ‘T’;
college[5] = ‘\0’;

The array definition could have been written as :

char college[] = “CCMIT”;

Accessing Elements in Arrays

C uses an index to access individual elements in an array. The index must be an integral
value or an expression that evaluates to an integral value. The simplest form for accessing
an element is a numeric constant. For example, given an array scores[20], we could
access the first element as follows:

scores[0]

Typically, however, the index is a variable or an expression. To process all the elements
in scores, a loop similar to the following code is used:

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


scores[i]…..;

You might be wondering how C know where an individual element is located in memory.
In scores, for example, there are ten elements. How does it find just one? The answer is
simple. The array’s name is a symbolic reference for the address to the first byte of the
array. Whenever we use the array’s name, therefore, we are actually referring to the first
byte of the array. The index represents an offset from the beginning of the array to the
element being referred to. With these two pieces of data, C can calculate the address of
any element in the array using the following simple formula:

element address = array address + (sizeof(element) * index

9
For example, assume that scores is stored in memory at location 10,000. Since scores is
an integer, the size of one element is the size of an integer. Assuming an integer size of
two, the address of the element at index 3 is:

element address = 10,000 + 2 * 3 + 10,006

Storing Values in Array


Declaration and definition only reserve space for the elements in the array. No values will
be stored. If we want to store values in the array, we must either initialize the elements,
read values from the keyboard, or assign values to each individual element.

Initialization
Initialization of all elements in an array can be done at the time of declaration and
definition, just as with variables. For each element in the array we provide a value. The
only difference is that the values must be enclosed in braces and, if there are more than
one, separated by commas. It is a compile error to specify more values than there are
elements n the array. The initial values must appear on the order in which they will be
assigned to the individual array elements, enclosed in braces and separated by commas.

The general form is:

Storage class data-type arrayname[expression]={value1,


value2,..value n};

Where value1 refers to the value of the first array element, value 2 refers to the value of
the second element and so on. The appearance of the expression which indicates the
number of array elements is optional when initial values are present.
Examples of array initialization:

int first_array[5] ={5, 3, 2, 7, 9};


int second_array[] ={11, 21, 75, 24, 5};
int third_array[15]={3, 7, 4, 6, 1};

The first example is a simple array declaration of five integers. It is typically the way array
initialization is coded. When the array is completely initialized, it is not necessary to
specify the size of the array. This case is seen in the second example. It is a good idea,
however to define the size explicitly because it allows the compiler to do some checking
and it is also good documentation.

If the number of value provided is less than the number of elements in the array, the
unassigned elements are filled with zeros. This case is seen in the third example. We
can use this rule to easily initialize a array to all zeros by supplying just the first zero value
of the first element.

Inputting Values
Another way to fill the array is to read the values from the keyboard or a file. This can be
done using a loop when the array I going to be completely filled, the most appropriate loop
is the for because the number of element are fixed and known.

10
Example:
int scores[10];


for(i=0; i<10; i++)
scanf(“%d”, scores[i]);

Several concepts need to be studied in this simple statement. First, we start the index, i,
at zero. Since there are ten elements in the array, we must load the values from index
locations zero through nine. The limit test, therefore, is set at i<10, which conveniently is
the number of elements in the array. Then, even though we are dealing with array
elements, the address operator (&) is still necessary in the scanf call.

Finally, when there is a possibility that all the elements are not going to be filled, then one
of the event-controlled loops (while or do-while) should be used. Which one you use would
depend on the application.

Individual elements can be assigned values using the assignment operator. Any value
that reduces to the proper type can be assigned to an individual array element.

Example:
scores[4] = 23;

On the other hand, you cannot assign one array to another array, even if they match full
in type and size. You have to copy arrays at the individual element level. For example,
to copy an array of 25 integers to a second array of 25 integers, you could use a loop as
shown below:

for(i=0l i<25; i++)


second[i] = first[i];

If the values of an array follow a pattern, we can use a loop to assign values. For example,
the following loop assigns a value that is twice the index number to array scores.

for(i=0l i<25; i++)


scores[i] = I * 2;

Sample program 1:

This is a program that sorts the values of the array num.

#include<stdio.h>
#include<conio.h>

void main()
{
clrscr();
int num[3] = {5, 3, 7};
int h, i, temp;

for(h=0; h<3; ++h)

11
for(i=0; i<h; ++i)
{
if(num[i] > num[I + 1])
{
temp = num[i];
num[i] = num[I + 1];
num[i+ 1] = temp;
}
}
for(i=0; i<3; i++)
printf(“%d\n”, num[i]);
getch();
}

sample run:

Output:
3
5
7

Sample program 2:
/* Program to count the number of positive and negative numbers*/

#include<stdio.h>
#include<conio.h>

void main()
{
int a[50], n, count_neg = 0, count_pos = 0, i;
clrscr();
printf(“Enter the size of the array”);
scanf(“%d”,&n);
printf(“Enter the elements of the array ”);
for(i=0; i<n; i++)
scanf(“%d”, &a[i]);
for(i=0; i<n; i++)
{
if(a[i] < 0)
count_neg++;
else
count_pos++;
}
printf(“There are %d negative numbers in the array\n”, count_neg);
printf(“There are %d positive numbers in the array\n”, count_pos);
getch();
}

12
Multidimensional Arrays

Multidimensional arrays are defined in much the same manner as one-


dimensional. A two-dimensional array requires two pairs of square brackets.

In general term, a multidimensional array definition can be written as:

storage-class data-type arrayname[expression1][expression2];

where storage-class refers to the storage-class of the array, data-type is its data-type,
arrayname is the name of the array and expression1, expression2 are positive-values
integer expression that indicate the number of array elements associated with each
subscript. Remember that storage-class is optional; the default is automatic for arrays
that are defined inside of a function and external for arrays, defined outside of a function.

Several multidimensional array definitions are shown below:

float IT[5][3];
int CS[3][3];

The first line defines array IT as floating-point array having 5 rows and 3 columns while
the second line indicates that array name CS has 3 row and 3 column integer array
elements.

Multidimensional array definition includes the assignment of initial values, the care
must be given to the order in which the initial values are assigned to the array elements.

Consider the following two-dimensional array definition:

int ccmit[3][3] ={1,2,3,4,5,6,7,8,9};

Note that the values can be thought of as a table having 3 rows and 3 columns. Since the
initial values are assigned by rows (last subscript increasing most rapidly), the result of
this initial assignment are as follows;
ccmit[0][0] = 1 ccmit[0][1] = 2 ccmit[0][2] = 3
ccmit[1][0] = 4 ccmit[1][1] = 5 ccmit[1][2] = 6
ccmit[2][0] = 7 ccmit[2][1] = 8 ccmit[2][2] = 9

The natural order in which the initial values are assigned can be altered by forming groups
of initial values enclosed within braces. The values within each innermost pair of braces
will be assigned to those array elements whose last subscript changes most rapidly. In a
two-dimensional array, for example, the value within an inner part of braces will be
assigned to the elements of a row, since the second subscript increases most rapidly. If
there are few values within the pair of braces, the remaining elements of that row will be
assigned zeros.

Remember: On the other hand, the number of values within each part of braces cannot
exceed the defined row size.

13
Example: Here is a variation of the two-dimensional array definition presented in the last
example:

int ccmit[3][3] = {{1,2,3},{4,5,6},{7,8,9}};

This definition results in the same initial assignment as in the last example. Thus the three
values in the first inner pair of braces are assigned to the array elements in the first row,
the values in the second inner part of braces are assigned to the array elements in the
second row, and so on. Note that an outer pair of braces is required.
Now consider the following two-dimensional array definition

int ccmit[3][4] = {{1,2,3},{4,5,6},{7,8,9}};

This definition assigns values only to the first three elements in each row. Therefore, the
array elements will have the following initial values:

ccmit[0][0]=1 ccmit[0][1]=2 ccmit[0][2]=3 ccmit[0][3]=0


ccmit[1][0]=4 ccmit[1][1]=5 ccmit[1][2]=6 ccmit[1][3]=0
ccmit[2][0]=7 ccmit[2][1]=8 ccmit[2][2]=9 ccmit[2][3]=0

Notice that the last character in each row is assigned a value zero.
If the preceding array definition is written as

int ccmit[3][4] = {1,2,3,4,5,6,7,8,9};

then three of the array elements will again be assigned a value of zero, though the order
of the assignment will be different. In particular, the array elements will have the following
initial order:

ccmit[0][0]=1 ccmit[0][1]=2 ccmit[0][2]=3 ccmit[0][3]=4


ccmit[1][0]=5 ccmit[1][1]=6 ccmit[1][2]=7 ccmit[1][3]=8
ccmit[2][0]=9 ccmit[2][1]=0 ccmit[2][2]=0 ccmit[2][3]=0

Finally, consider the array definition below:

int ccmit[3][3]={{1,2,3,4},{5,6,7,8},{9,10,11,12}};

This will result in a compilation error since the number of values in each inner pair of
braces exceeds the defined array size.

Sample Program 3
/* example program to add two matrices and store the results in the 3 rd matrix*/
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10]10], b[10][10], c[10][10], i, j, m=0,n=0,p=0,q=0;
clrscr();
printf(“enter the order of the matrix\n”);
scanf(“%d%d”, &p, &q);
if(m==p && n==q)

14
{
printf(“matrix can be added\n”);
printf(“enter the elements of the matrix a”);
}
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf(“%d”, &a[i][j]);
printf(“enter the elements of the matrix b”);
for(i=0;i<p;i++)
for(j=0;j<q;j++)
scanf(“%d”, &b[i][j]);
printf(“the sum of the matrix a and b is”);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
c[i][j] = a[i][j] + b[i][j];
for(i=0;i<m;i++)
for(j=0;j<n;j++)
printf(“d\t”,a[i][j]);
printf(“\n”);
getch();
return;
}}

Watch:

https://www.youtube.com/watch?v=AT14lCXuMKI
https://www.youtube.com/watch?v=KDQXUysHLL8

Read:

• Programming Logic and Design, 8 th ed/ 3rd edition, Joyce Farrel,2015

Review:

1. What is array?
2. What are the types of array? Differentiate each.

Activities/Assessments: Unit 1 Array

1. Write an appropriate array definition for each of the following problem situations:

a. Define a one-dimensional, 12-element integer array called C. Assign the


values 1, 4, 7, 10, …, 34 to the array elements.
b. Define a one-dimensional character array called point. Assign the string
“NORTH” to the array elements. End the string with the null character.
c. Define a one-dimensional, four-character array called letters, assign the
characters ‘N’, ‘S’, ‘E’, and ‘W’ to the array elements.

15
2. Write the final output inside the box generated by each of the following programs:
a. #include<stdio.h>
#include<conio.h>
main()
{ int a, b=0;
static int c[10]= {1,2,3,4,5,6,7,8,9,10};
clrscr();
for(a=0; a<10; a++)
if((c[a] % 2)== 0)
b+=c[a];
printf(“%d”,b);
getc();
return 1;
}

b. #include<stdio.h>
#include<conio.h>
void main()
{ int a, b=0;
static int c[10]= {1,2,3,4,5,6,7,8,9,10};
clrscr();
for(a=0; a<10; a++)
if(a % 2)== 0)
b+=c[a];
printf(“%d”,b);
getc(); }

c. #include<stdio.h>
#include<conio.h>
#define r 3
#define c 4
int z[r][c] = {1,2,3,4,5,6,7,8,9,10,11,12};
main()
{
int a, b, c = 999;
clrscr();
for(a=0;a<r;++a)
for(b=0;b<c;++b
if(z[a][b]<c)
c=z[a][b];
printf(“%d”,c);
getch();
return 1;
)

16
Unit 2 – Function

Overview:

In this unit you will learn to write functions, declare and define a group of statements as
the body of function, and it can be called and used whenever required. A function is a
block of code that performs a particular task.

Unit Objectives:

After successful Completion of this unit, you should be able to:

• know the advantages of using function;


• differentiate the storage classes; and
• differentiate the call by value and call by reference.

Course Materials:

STORAGE CLASSES
There are two different ways to characterize variables:

By data type – refers to the type of information represented by a variable

By storage class – refers to the permanence of a variable and its scope within the
program, that is, the portion of the program over which the variable is recognized.

There are four storage-class specifications in C:


1. Automatic variables or Auto
2. External variables or Extern
3. Static variables
4. Registers

AUTOMATIC VARIABLES

Automatic variables are always declared within a function and are local to the
function in which they are declared; that is their scope is confined to that function.
Automatic variables defined in different functions will therefore be independent of another,
even though they may have the same name.

17
Any variable declared within a function is interpreted as an automatic variable
unless a different storage class specification is included within the declaration. Since the
location of the variable declarations within the program determine the automatic storage
class, the keyword AUTO is not required at the beginning of each variable declaration.
There is no harm in including an auto specification within a declaration if the programmer
wishes, though this is normally not done.

An automatic variable does not retain its value once the control is transferred out
of its defining function. Therefore, any value assigned to an automatic variable within a
function will be lost once the function is exited. If the program logic requires that an
automatic variable be assigned a particular value each time the function is executed, that
the value will have to be reset whenever the function is re-entered.

EXTERNAL VARIABLES

External variables, in contrast to automatic variables, are not confined to single


functions. Their scope extends from the point of definition through the remainder of the
program. Hence, they usually span two or more functions, and often an entire program.

Since external variables are recognized globally, they can be accessed from any
function that falls within their scope. They retain their assigned values within this scope.
Therefore, an external variable can be assigned a value within one function and this value
can be used within another function.

A declaration for an external variable can look identical to a declaration for a


variable that occurs inside a function or block. Such a variable is considered to be global
to all functions declared after it, and upon exit from the block or function, the external
variable remain in existence.

The use of extern will cause some traditional C compilers to compile. Although
this is allowable in ANSI C, it is not required. Variables defined outside of a function have
external storage class, even if the keyword extern is not used. Such variables cannot
have automatic or register storage class.

STATIC VARIABLES

Static variables have two important and distinct uses:


a. To allow local variable to retain its previous value when the block is re-entered.
b. Use in connection with external declarations. Static variables can be utilized
within the function in the same manner as other variables. They cannot however
be accessed outside of their defining function.

REGISTER VARIABLES

The storage class register tells the compiler that the associated variables should
be stored in high-speed memory registers, provided it is physically and semantically
possible. Since resource limitations and semantic constraints sometimes make this
possible, this storage class defaults to automatic whenever the compiler cannot allocate
an appropriate physical register. Typically, the compiler has only a few such register
available; many are required for system use and cannot be allocated otherwise.

18
Basically, the use of storage class register is an attempt to improve execution
speed. When speed is concern, the programmer may choose a few variables that are
most frequently accessed and declared them to be of storage class register.
Sample program. Extern and Auto

#include<stdio.h>
#include<conio.h>
int a=3; external variable
main()
{
int count;
automatic variable
int funct1(int b);
clrscr();
for(count=1; count<=5; ++count)
{ a = funct1(count);
printf(“%d\t”,a);
}
getch();
return 1;
}
int funct1(int b)
{ int count;
count = b + a++;
automatic variable
return count;
}

OUTPUT
4 6 9 13 18

Sample program. Static


#include<stdio.h>
#include<conio.h>
int a = 100, b = 200;
funct1(int y)
{
int c, d;
int funct2(int x);
c = funct2(y);
d = (c < 100) ? (a + c) : b;
return d;
}
funct2(int x)
{
static int prod = 1; static variable
prod *= x;
return prod;
}
main()

19
{
int count;
int funct1(int y);
clrscr();
for(count = 1; count <= 5; ++count)
printf(“%d”, funct1(count));
getch();
return 1;
}

101 102 106 124 200

FUNCTION IN C

The heart of effective problem solving is problem decomposition. Taking a problem and
breaking it into small, manageable pieces is critical to writing large programs. In C, the
function construct is used to implement this “top-down” method of programming.

A function is a section of a program which performs a specific task. The task


assigned to a function is performed whenever C encounters the function name. A function
is actually a subprogram that is, a function performs a task within a program and is written
in a form similar to C main program.

The advantages using FUNCTION


1. Using function fits naturally with a top-down design approach. Use of function helps to
streamline the design of a program and prevents small details from obscuring the program
logic.

2. Functions can often be used more than once in a program and in several different
programs, thereby sharing programming time. A function can be viewed as a blank box
which performs a particular task within a program. It accepts input and produces certain
output. When programming with function, you are plugging various block boxes into your
program to accomplish various necessary tasks. Certain common task appears regularly
in totally unrelated programs. In such cases, the same function can be used repeatedly.

3. Using function provides a natural method for dividing a programming task among a
team of programmers. By defining a function as a block box which accepts certain inputs
and produces certain output, the function can be programmed as an independent entity.

4. Function can be tested individually. By testing functions at a time, the process of


debugging an entire program is organized and simplified.

FUNCTION DECLARATIONS
The function declaration has a name of a function, the type of the value to be
returned (if there are any) and the number and types of the arguments that must be
supplied in a call of the function. A function declaration may contain argument names.

20
syntax:
data_type_return function_name (parameter list)

Example:
int ccmit (int bsit, int bscs);
void ccmit ();
float ccmit (float x, float y);

FUNCTION DEFINITION
The code that describes what a function does is called a function definition. It must
not be confused with the function declaration. The function definition must have the
following general form:

data_type_return function_name (parameter list)


{ declaraction local variables
statement;
}

Everything before the first brace comprises the header of the function definition,
and everything between the braces comprises the body of the function definition. The
parameter-list is a comma-separated list of declaration.

A function definition starts with the type of the function. If no value is returned, then
the type is void. If the type is something other than void, then the value is returned by the
function will be converted, if necessary, to this type. The name of the function is followed
by a parenthesized list of parameter declarations. The parameter acts as a placeholder
for values that are passed when the function is invoked. Sometimes, to emphasize their
role as placeholders, these parameters are called the formal parameters of the function.
The function body is a block, or compound statement, and it too may contain declarations.

Example:
double twice(double x) /*function definition*/
{
return(2.0*x)’
}

int all_add(int a, int b) /*function definition*/


{ int c;
:
return(a+b+c);}

LOCAL VARIABLES TO A FUNCTION


Any variables declared in the body of function are said to be “local” to that function.
Other variables ay be declared external to the function. These are called “global” variables.

• Variables that are declared inside the function are called “local variables”. In C,
they are referred to as AUTOMATIC VARIABLES or the keyword auto.

• Local variables can be reference only by statements that are inside the block in
which the variables are declared.

21
• Local variables are not known outside their own code. You should remember that
a block of code is begun when an opening curly brace is encountered and
terminated when a closing curly brace is found.

• One of the most important things to remember about local variable is that they
EXIST only while the block code in which they are declared is executing that is,
local variable is created upon entry into its block and destroyed upon exit.

• The most common code block in which local variables are declared is in function.

Sample Program
#include<stdio.h>
#include<conio.h>
int a=33;

main()
{
int b = 77; /*b is local variable to main()*/
printf(“a = %d\n”,a); /*a is global variable to main()*/
printf(“b=%d\n”,b);
return 0;
getch();
}

GLOBAL VARIABLE TO A FUNCTION

• Known throughout the entire program and maybe used by any piece of code. Also,
they hold their values during the entire execution of the program.
• Global variables are created by declaring them outside of any function. They may
be accessed by any expression regardless of what function that expression is in.
• Storage for global variables is in fixed region of memory set aside for this purpose
by the compiler.
• Global variables are very helpful when the same amount of data is used in many
functions in your program.
• You should avoid using unnecessary global variables, however, three(3) reasons:
1. They take-up memory the entire time your program is executing not just when
they are needed.
2. Using global variables when local variable will do makes a function less general
because it relies on something that must be defined outside function.
3. Using a large number of global variables can lead to program error because of
unknown and unwanted, side effects.

THE return STATEMENT


The return statement may or may not include an expression.

syntax:
return; return(expression);

The expression being returned can be enclosed in parenthesis, but this is not
required. When a return statement is encountered, execution of the function is terminated

22
and control is passed back to the calling environment. If the return statement contains an
expression, then the value of the expression is passed back to the calling environment as
well. Moreover, this value will be converted, if necessary to the type of the function as
specified in the function definition.

Example:
float f(char a, char b, char c)
{
int i;
:
:
return i; /*the value returned will be converted to a float*/
}

There can be zero or more return statements in a function. If there is no return statement,
then control variable is passed back to the calling environment when the closing brace of
the body is encountered. This is called “falling off the end”.

Program segment
double absolute_value( double x)
{ if(x >= 0.0)
return x;
else
return –x;
}

FUNCTION PROTOTYPES
• Functions should be declared before they are used. ANSI C provides for a new
function declaration syntax called the functional prototype.
• A function prototype tells the compiler the number and the type of arguments that
are to be passed to the function and the type of the value that is to be returned by
the function.

Example:
double sqrt(double);

this tells the compiler that sqrt() is a function that takes a single argument of type double
and returns a double.

syntax:
type function_name(parameter type list);

• The parameter type list is typically a comma-separated list of types. Identifiers are
optional.

Example of function prototype:

void funct1(char c, int i);is equivalent to


void funct1(char, int);

23
• Function prototype allows the compiler to check the code more thoroughly.
• Also, values passed to function are properly coerced.

Note: Function Prototype in C++


In C++, function prototypes are required and the use of void in the parameter type list in
both function prototypes and the function definition is optional.

Example:
void funct1() is equivalent to void funct1(void)

GIVING NAMES TO PARAMETER/PARAMETER LISTS


A function header identifies the parameters which are to be passed to the function.
In the header and in the actual body of the function, the parameters used are FORMAL
parameters which are replaced by the ACTUAL parameter when the function is called.
Since the FORMAL parameters are eventually replaced, they are not program variable. In
particular, you can assign to FORMAL parameters the names of program variable which
will eventually replace them.

FUNCTION INVOCATION AND CALL BY VALUE


A program is made up of one or more function definitions, with one of these being
main(). Program execution always begin with main(). When program control encounters a
function name, the function is called, or invoked. This means that the program control
passes to that function. After the function does its work, program control is passed back
to the calling environment, which then continues with its work.

Functions are invoked by writing their names and an appropriate list of arguments
within parenthesis. Typically, these arguments match in number and type(or compatible
type) the parameters in the parameter list in the function definition. The compiler enforces
type compatibility when function prototypes are used. All arguments are passed “call by
value”. This means that each argument is evaluated and its value is used locally in place
of the corresponding formal parameter.

A function call comes from either the main program or within a function. The
function originating a function call is referred to as the calling function or calling
environment.

HOW VALUE PARAMETER/CALL BY VALUE WORKS


A value parameter is a copy of a variable which is private to the function. The
function is given a copy of the actual parameter to manipulate. However, the manipulation
does not affect any of the variables in the calling program.

Sample Program:
#include<stdio.h>
#include<conio.h>
int sum; /*global declaration*/
void funct_sample ( int y);
void main()
{
int n =5;
clrscr();
printf(“The value of n here is %d”,n);

24
funct_sample(n);
printf(“\nValue of n is %d”,n);
getch();
}
funct_sample( int y)
{
/* Sample function using call by value */
y*= 3;
printf(“The new value of y is %d”, y);
}

OUTPUT:
The value of n here is 5
The new value of y is 15
Value of n here is 5

Even though n is passed to funct_sample() and received by formal parameter y, the value
n which y in the body of that function is changed, the value of n in the calling environment
remains unchanged. It is the value of n that is being passed, not n itself.

CALL BY REFERENCE OR VARIABLE PARAMETERS


• To change the value of variable in the calling environment, other languages
provide the “call by reference” mechanism.
• The use of addresses of variables as argument to function can produce the effect
of “call by reference”
• For the function to effect “call by reference”, pointers must be used in the
parameter list in the function definition. When the function is called, address of the
variables must be passed as argument.
• In passing a variable parameter to a function, C does not pass the actual value.
Instead, it passes a pointer to a variable being passed, that is, we pass the address
of the memory location holding the value of the variable being passed.
• & is used as address operator means “the address of…”
• * is called as indirection operator means the “content of address…”

Illustration
Address of the parameter value of parameter

16825 *50126

address of parameter is being passed to the function

Sample program 1
#include<stdio.h>
#include<conio.h>

compute_rating(float midterm, float final, float *rating)


{
/* Function that will compute the final rating */
*rating = (midterm + final)/2;
}

25
main()
{
char name[25];
float mid,fin,fin_grd;
clrscr();
putsf(“Please enter you name”);
gets(name);
printf(“Enter your midterm grade”);
scanf(“%f”,&mid);
printf(“\nEnter you final grade”);
scanf(“%f”,&fin);
compute_rating(mid,fin, &fin_grd);
printf(“%s got a final rating of %f”, name,fin_grd);
getch();
return 0;
}

Sample Program 2

void swap_ref(int &a, int &b);


void swap_val(int a, int b);
int main()
{
int a=3, b=6;
printf(“\\na=%d b=%d”, a, b);
swap_val(a,b);
printf(“\\na=%d b=%d”, a, b);
swap_ref(&a, &b);
printf(“\\na=%d b=%d”, a, b);
return 1;
}
void swap-rer(int *a, int *b)
{
//function accepts a reference
*a=*a + b;
//to original parameter variable
b=*a – b;
*a=*a – b;
}
void swap_val(int a, int b)
{
a=a + b;
b=a – b;
a=a – b;
}
OUTPUT:
a=3 b=6
a=3 b=6
a=6 b=3

26
Swapping is an important technique in solving many programming problems, and is often
not well understood. The principle is simple enough: we want to assign the value of
variable a to the value of variable b and vice versa. This is, however, an often complex 3-
stage process:

1. put the value of variable a into variable temp


2. put the value of variable b into variable a
3. put the value of variable temp into variable b

Sample Program 3

void swap (int *x int *y);


void main()
{
int a=3, b=5;
puts(“before”);
printf(“ a is %d and b is %d”, a, b);
swap(&a, &b);
puts(“after”);
printf(“ a is %d and b is %d”, a, b);
getch();
return;
}
void swap(int *x, int *y)
{
int z;
z = *x;
*x = *y;
*y = z;
}

27
Watch:

https://www.youtube.com/watch?v=AMU3xDnECsU
https://www.youtube.com/watch?v=tv_9doDQJU0

Read:

• Programming Logic and Design, 8 th ed/ 3rd edition, Joyce Farrel,2015

Review:

1. What is a function? What is the syntax of a function?


2. What is the use of the data type void?
3. Explain a function that is called by value?
4. What is an address? A pointer? Explain a function that is called by reference?
5. Explain a function that returns a value?

Activities/Assessment: Unit 2 Function

TRACING

1. Trace the following programs:

(a)
void trace1(int x, int *y)
{
x = 5; *y =2;
printf(“%2d %2d\n”, x, *y);
}

main( )
{
int x, y;
clrscr( );
x = y = 3;
trace1(x, &y);
printf(“%2d %2d\n”, x, y);
getch( );
return 0;
}

(b)
void trace(int x, int *y, int z)
{
x = 1; *y=2; z=4;

28
printf("%2d %2d %2d\n",x, *y, z);
}

main()
{
int x=1, y=3,z=4;
clrscr();
printf("%2d %2d %2d\n",x,y,z);
trace(y,&x,z);
printf("%2d %2d %2d\n",x,y,z);
trace(x,&z,y);
printf("%2d %2d %2d\n",x,y,z);
trace(z,&y,x);
printf("%2d %2d %2d\n",x,y,z);
getch();
return 0;
}

(c)
#include<stdio.h>
#include<conio.h>
void kar1(char *c, char b, char *a)
{
*a = 'c'; b = 'a'; *c = 'b';
printf("%c %c %c\n", *a, b, *c);
}
void kar2(char *b, char *a, char *c)
{
*a = 'b'; *b='c'; *c ='a';
printf("%c %c %c\n", *a, *b, *c);
}

main()
{
char a = 'a', b = 'b', c = 'c';
clrscr();
printf("%c %c %c\n", a, b, c);
kar1(&a,b,&c);
printf("%c %c %c\n", a, b, c);
kar2(&a,&b,&c);
printf("%c %c %c\n", a, b, c);
kar1(&c,b,&a);
printf("%c %c %c\n", a, b, c);
kar2(&c,&a,&b);
printf("%c %c %c\n", a, b, c);
getch();
return 0;
}

29
(d)
#include<stdio.h>
#include<conio.h>

void kar1(char *a, char *b, char *c)


{
*a = 'c'; *b='a'; *c ='b';
printf("%c %c %c\n", *a, *b, *c);
}
main()
{
char a = 'c', b = 'b', c = 'a';
clrscr();
printf("%c %c %c\n", a, b, c);
kar1(&a,&b,&c);
printf("%c %c %c\n", a, b, c);
kar1(&c,&b,&a);
printf("%c %c %c\n", a, b, c);
kar1(&b,&a,&c);
printf("%c %c %c\n", a, b, c);
getch();
return 0;
}

(e)
void main()
{
int x, y;
x = 20;
y = 30;
clrscr();
printf(“\n Value of a and b before function call = %d %d”,x,y);
fncn(&x,&y);
printf(“\n Value of a and b after function call = %d %d”,x,y);
getch();
return;
}
fncn(int *p, int *q)
{
*p = *p + *p;
*q = *q + *q;
}

(f)
#include<stdio.h>
#include<conio.h>
#define r 3
#define c 4
main()
{
static int z[r][c] = {1,2,3,4,5,6,7,8,9,10,11,12};

30
void sub1(int x[][4]);
clrscr();
sub1(z);
getch();
return 1;
}
void sub1(int x[][4])
{
int a, b, y;
for(b=0;b<c;++b)
for(a=0;a<r;++a)
if(x[a][b] > c)
y = x[a][b];
printf(“%d”, y);
}

31
Unit 3 - POINTERS

Overview:

In this unit, you will learn to access the address of another variable and at the same time
access its value using pointer variable. Every variable is a memory location and every
memory location has its address defined which can be accessed using ampersand (&)
operator, which denotes an address in memory and a pointer is a variable that stores the
address of another variable. Unlike other variables that hold values of a certain
type, pointer holds the address of a variable.

Unit Objectives:

After successful completion of this unit, you should be able to:

• know in details the basic concepts of Pointers.


• be more familiar with the importance uses of Pointers.
• determine the difference between Pointers and Arrays.
• be able to apply the use of Pointers in advance topics of C.
• make the student develop good programming techniques using Pointers.

Course Materials:

Pointers: Brief Overview

A pointer is a variable that represents the location (rather than the value) of a data
item, such as a variable of an array element. Pointers are used frequently in C, as they
have a number of useful applications.

1. Pointers can be used to pass information back and fort between a function and its
reference point. In particular, pointers provide a way to return multiple data items
from a function via function arguments.
2. Pointers also permit references to other functions to be specified as arguments to
a given function. This has effect of passing functions as arguments the given
function.
3. Pointers are also closely associated with arrays and therefore provide an alternate
way to access individual array elements.
4. Pointers provide a convenient way to represent multidimensional arrays, allowing
a single multidimensional array to be replaced by a lower-dimensional array of
pointers. This feature permits a collection of strings to be represented within a
single array, even though the individual strings may differ in length.

32
Fundamentals

Suppose v is a variable that represents some particular data item. The compiler
will automatically assign memory cells for this data item. The data item can be accessed
if we know the location (the address) of the first memory cell. The address of v’s memory
location can be determined by the expression &v. where & is a unary operator, called the
address operator, that evaluates the address of its operand.

Now let us assign the address of v to another variable, pv. Thus, pv = &v. This
new variable is called a pointer to v, since it points to the location where v is stored in
memory. Remember, however, that pv represents v’s address, not its value. Thus, pv is
referenced to a pointer variable.

The data item represented by v can be accessed by the expression *pv, where *
is a unary operator, called indirection operator (also known as dereference), that
operates only on a pointer variable. Therefore, *pv and v both represent the same data
item. Furthermore, if we write pv - &v and u = *pv, then u and v will both represent the
same value, the value of v will indirectly be assigned to u.

Sample 3.1 Shown below is a simple program that illustrates the relationship between two
integer variable, their corresponding addresses and their associated pointers.

#include<stdio.h>
#include<conio.h>
main()
{
int u = 2;
int v;
int *pu; /*pointer to an integer*/
int *pv; /*pointer to an integer*/
clrscr();
pu = &u; /*assign address of u to pu*/
v = *pu; /*assign address of u to v*/
pv = &v; /*assign address of v to pv*/
printf(“\nu = %d &u = %x pu = %x *pu = %d”, u, &u, pu, *pu);
printf(“\n\nv = %d &v = %x pv = %x *pv = %d”, v, &v, pv, *pv);
getch();
return 1;
}

Note that pu is pointer to u, and pv is a pointer to v. Therefore, pu represents the address


of u and pv, represents the address of v. Executing this program results in the following
output:

u=2 &u = fff4 pu = fff4 *pu = 2


v=2 &v = fff2 pv = fff2 *pv = 2

The unary operators & and * are members of the same precedence group as the
other unary operators, (-, ++, --, !, sizeof and (type)). The address operator (&) must act

33
upon operands associated with unique address, such as ordinary variables or single array
elements. Thus, the address operator cannot act upon arithmetic expression such as 2 *
(u + v).

The indirection operator (*) can only upon operands that are pointers. However, if
pv points to v, then an expression such as *pv can be used interchangeably with its
corresponding variable v. Thus, an indirect reference can appear in place of an ordinary
variable within a more complicated expression.

Sample 3.2 Assigning value

int q = 25, *x;


x = &q;

what is the value of q?


25
what is the value of x?
address of q (address being pointed)
What is the value of &q:
Address of q
What is the value of *x?
25 (value of the address being pointed)

*x = 7;

What is the value of *x?


7

what is the value of q?


7

Sample 3.3 Consider the simple C program shown below.

#include<stdio.h>
#include<conio.h>
main()
{
int u1 = u2;
int v = 3;
int *pv; /*pointer to an integer*/
clrscr();
u1 = 2 * (v + 5);
pv = &v; /*assign address of v to pv*/
u2 = 2 * (*pv + 5);
printf(“\nu1 = %d u2 = %d”, u1, u2);
getch();
return 1;
}

34
This program involves the use of two integer expressions. The first 2 * (v + 5), is an
ordinary arithmetic expression, whereas the second 2 * (*pv + 5), involves the use of a
pointer. The expressions are equivalent, since v and pv each represent the same integer
value.
The following output is generated when the program is executed:

u1 = 16 u2 = 16

An indirect reference can also appear on the left side of an assignment statement. This
provides another method for assigning a value to a variable or an array element.

Sample 3.4
#include<stdio.h>
#include<conio.h>
main()
{
int a = 3;
int *pa; /*pointer to an integer*/
clrscr();
pa = &a; /*assign address of a to pa*/
printf(“\n *pa = %5d a = %5d”, *pa, a);
*pa = 5;
printf(“\n *pa = %5d a = %5d”, *pa, a);
getch();
return 1;
}

The program begins by assigning an initial value 3 to the integer variable a, and assigns
the address of a to the pointer variable pa. Thus, pa becomes a pointer to a. The
expression *pa therefore represents the value 3. The first printf statement is intended to
illustrate the current values of *pa and a.

Following the first printf statement, the value *pa is reset to 5. Therefore, a will
be assigned the value 5. This is illustrated by the second printf statement, which causes
the values of *pa and a be displayed.

When the program is executed, the following output is generated.

*pa = 3a = 3
*pa = 5a = 5

Thus, the value of a has been altered by assigning a new value to *pa.

Pointer Declarations

Pointer variables, like all other variables must be declared before they may be used in a
C program. The interpretation of a pointer declaration is somewhat different, however,
that the interpretation of other variable declarations. When a pointer variable is declared,
the variable name must be preceded by an asterisk(*). This identifies the fact that the
variable is a pointer. The data type that appears in the declaration refers to the object of

35
the pointer, that is the data item that is stored in the address represented by the pointer,
rather than the pointer itself.

Thus, a pointer declaration may be written in general term as:

data-type *ptvar;

where ptvar is the name of the pointer variable, and data-type refers to the data type of
the pointer’s object.

Remember:

You have to be reminded that this group of operators has a higher precedence
than the group containing the arithmetic operators and that the associativity of the unary
operators is right-to-left.(that an asterisk must precede ptvar)

Example 3.5 A C program contains the following declarations:

float u, v;
float *pv;

Example 3.6 A C program contains the following declarations:

float u, v;
float *pv = &v;

The variables u and v are declared to be floating-point variables and pv is declared as a


pointer variable that points to a floating-point quantity. In addition, the address of v is
initially assigned to pv.

Pointers and One-Dimensional Arrays

Recall that an array name is really a pointer to the first element in that array.
Therefore, if x is a one-dimensional array, then the address of the first array element can
be expressed as either &x[0] or simply as x. Moreover, the address of the second array
element can be written as either &x[1] or as (x + 1), and son on. In general, the address
of the (i + 1)st array element can be expressed as either &x[i] or as (x + i).

Thus, we have two different ways to write the address of any array element:

• We can write the actual array element, preceded by an ampersand;


• We can write an expression in which the subscript is added
• to the array name.

In the expression (x + I), for example, x represents an address, where I represent an


integer quantity. Moreover, x is the name of the array whose elements may be characters,
integers, floating-point quantities, and so on. Thus, we are not simply adding numerical
values. Rather, we are specifying an address that is a certain number of memory cells
beyond the address of the first array element.

36
Since &x[i] and (x + i) both represent the address of the ith element of x, it would
seem reasonable that x[i] and *(x + i) both represent the contents of that address, the
value of the ith element of x. This is indeed the case. The two terms are interchangeable.
Hence, either term can be used in any particular application. The choice depends upon
the programmer’s individual preferences.

Sample 3.5 Here is a simple program that illustrates the relationship between array
elements and their address.

#include<stdio.h>
#include<conio.h>
main()
{
int x[10] = {10,11,12, 13, 14, 15, 16, 17, 18, 19};
int i;
clrscr();
for(i =0; i < = 9; ++i)

printf(“\ni = %5d x[i] = %5d *(x + i) = %5d &(x + i) = %5x x + i = %5x”,


i, x[i], *(x + i), &x[i], x + i);
getch();
return 0;
}

This program defines one-dimensional, 10-element integer array, x whose elements are
assigned the values 10, 11…19. The action portion of the program consists of a loop that
displays the value and the corresponding address of each array element. Note that the
value of each array element is specified in two different ways, as x[i] as *(x + i), in order
to illustrate their equivalence. Similarly, the address of each array element is specified in
two different ways, as &x[i] and as *(x + i), for the same reason. Therefore, the value and
the address of each array element should appear twice.

Executing this program results in the following output:

i=0 x[0] = 10 *(x + i) = 10 &x[i] = aa x + i = aa


i=1 x[1] = 11 *(x + i) = 11 &x[i] = ac x + i = ac
i=2 x[2] = 12 *(x + i) = 12 &x[i] = ae x + i = ae
i=3 x[3] = 13 *(x + i) = 13 &x[i] = b0 x + i = b0
i=4 x[4] = 14 *(x + i) = 14 &x[i] = b2 x + i = b2
i=5 x[5] = 15 *(x + i) = 15 &x[i] = b4 x + i = b4
i=6 x[6] = 16 *(x + i) = 16 &x[i] = b6 x + i = b6
i=7 x[7] = 17 *(x + i) = 17 &x[i] = b8 x + i = b8
i=8 x[8] = 18 *(x + i) = 18 &x[i] = ba x + i = ba
i=9 x[9] = 19 *(x + i) = 19 &x[i] = bc x + i = bc

The output clearly illustrates the distinction between x[ i ], which represents the value of
the ith element, and &x[ i ], which represents its address. Moreover, we see that the value
of the ith array element can be represented by either x[ i ] or *(x + i) and the address of
the ith element can be represented by either &x[ i ] or x + i. Thus, we see another
comparison, between *(x + i), which also represents the value of the ith element and x + i
which also represents the address.

37
In particular, notice the first array element corresponding to i = 0 has been
assigned a value of 10 and a hexadecimal address of “aa”. The second array element
has a value of 11 and an address of “ac”, etc. It should be understood that the
compiler automatically assigns these addresses.

Dynamic Memory Allocation

As a result, the use of a pointer variable to represent an array requires some sort
of initial memory assignment before the array elements are processed. Generally, such
initial memory allocations are accompanied by using the malloc library function, though
the exact method will vary from one application to another

Numerical elements cannot be assigned initial values if the array is defined as a


pointer variable. Therefore, a conventional array definition is required if initial values will
be assigned to the elements of a numerical array.

Example 3.8 Suppose that x is to be defined as a one-dimensional, 10-element array of


integers. It is possible to define x as a pointer variable rather than as an array. Thus, we
can:

int *x;
instead of
int x[10];
or instead of
*define size 10
int x[size];

However, x is not automatically assigned a memory block when it is defined as a pointer


variable, though a block of memory large enough to store 10 quantities will be reserved in
advance when x is defined as an array.

To assign sufficient memory for x, we can make use of library function malloc, as
follows:

x = malloc(x *sizeof(int));

This function reserves a block of memory whose size(in bytes) is equivalent to the size
of integer quantity. The function returns a pointer to the character. To be consistent with
the definition of x, we really want a pointer to an integer. However, characters and integers
are equivalent in C. Therefore, the statement is acceptable as shown above, though we
could include a type cast to be on the safe side, that is,

x = (int ) malloc(10sizeof(int));

The allocation of memory in this manner, as it is required, is known as dynamic memory


allocation.
If the declaration is to include the assignment of initial values, then x must be
defined as an array rather than as a pointer variable.

Example 3.9 Reordering a list of numbers. Consider the well-known problem of


rearranging a list of n integer quantities into a sequence of algebraically increasing values.

38
Shown below is a program that will carry out the rearrangement in such a manner that
unnecessary storage will not be used. Therefore, the program will contain only one array-
a one-dimensional, integer array called x which will be reordered one element at a time.

In order to find the smallest number within each pass, we sequentially compare
each number in the array, x[ i ], with the starting number, x[item], where item is an integer
variable that is used to identify a particular array element. If x[ i ] is smaller that x[item],
then we interchange the two numbers; otherwise we leave the two numbers in their original
position. Once this procedure has been applied to the entire array, the first number in the
array will be the smallest. We then repeat the entire procedure n-2 times, for a total of n-
1 passes.

Sample 3.6
#include<stdio.h>
#include<conio.h>
#define size 10
main()
{
int i, n, x[size];
void reorder(int n, int x[ ]);
clrscr();
printf(“how many numbers will be entered?\n”);
scanf(“%d”,&n)
printf(“\n”);
for(i=0; i < n; ++i)
{printf(“i = %d x = “, i + 1);
scanf)”%d”, &x[i]);}
reorder(n, x);
printf(“\n\nReordered list of numbers:\n\n”);
for(i=0; i < n; ++i)
printf(“i = %d x = %d\n “, i + 1, x[i]);
getch();
return 1;
}
void reorder(int n, int x[ ])
{int i, item, temp;
for(item=0; item < n - 1; ++item)
for(i=item + 1; i < n; ++i)
if(x[ i ] < x[item])
{temp = x[item];
x[item] = x[ i ];
x[ i ] = temp;}
return 0;
}

Example 3.10 Reordering A List of Numbers. To illustrate the use of the pointers, let
us consider the problem in Example 2.21, reordering a list of integers using arrays. Now,
however, we will utilize pointer expressions to access individual values rather than refer
explicitly to individual array elements. Here is the complete C program.

39
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
main()
{
int i, n, *x;
void reorder(int n, int *x);
clrscr();
printf(“how many numbers will be entered?\n”);
scanf(“%d”,&n)
printf(“\n”);
x = (int*)malloc(n *sizeof(int));
for(i=0; i < n; ++i)
{printf(“i = %d x = “, i + 1);
scanf(”%d”, x+ i);}
reorder(n, x);
printf(“\n\nReordered list of numbers:\n\n”);
for(i=0; i < n; ++i)
printf(“i = %d x = %d\n “, i + 1, *(x + i));
getch();
return 1;
}
void reorder(int n, int *x)
{int i, item, temp;
for(item=0; item < n - 1; ++item)
for(i=item + 1; i < n; ++i)
if(*(x + I) < *(x + item))
{temp = *(x + item);
*(x + item) = *(x + i);
*(x + i) = temp;}
return 0;}

In this program the integer array is defined as a pointer to an integer. Memory is initially
assigned to the pointer variable via the malloc library function. Elsewhere in the program,
pointer notation is used to process the individual array elements.

Within main, for example, the forward declaration of the function reorder now specifies
that the second argument is a pointer to an integer quantity rather than an integer array.
This pointer will identify the beginning of the integer array.

We also see the scanf function now specifies the address of the element as x + i
rather than &x[ i ]. Similarly, the printf function now represents the value of the ith element
as *(x + i) rather than as x[ i ]. The call to reorder, however, is the same in both programs,
namely, reorder(n,x);

Within the function reorder, we see that the second formal argument is now
defined as a pointer variable rather than as an integer array. This is consistent with the
function declaration in main. Even more pronounced, however, are the differences in the
if statement.

40
Sample 3.7 Here is a simple C program taken from Example 2.7 that modifies array to
pointer.

#include<stdio.h>
#include<conio.h>
#include<ctype.h>
/*pointer version*/
main()
{
char str[80], *p;
clrscr();
printf(“enter a string in uppercase”);
gets(str);
printf(“here’s the string in lowercase:”);
p = str;
while(*p)
printf(“%c“,tolower(*p++));
getch();
return 1;
}

Operations on Pointers

Pointer arithmetic is one of the most powerful features of C. If the variable p is a pointer
to a particular type, then the expression p + 1 yields the correct machine address for
storing or accessing the next variable of that type. Below are the summarized permissible
operations of the pointers.

• A pointer variable can be assigned the address of an ordinary variable.


Example: pv = &v;

• A pointer variable can be assigned the value of another pointer variable provided
both pointers points to objects of the same data type.
Example: pv = px;

• A pointer variable can be assigned a null(zero) value where null is a symbolic


constant that represents the value 0.

• An integer quantity can be added or subtracted from a pointer variable.


Example: pv + 3; ++pv;

• One pointer variable can be subtracted from another provided both pointers point
to elements of the same array.

• Two pointer variables can be compared provided both pointers point to objects of
the same data type.

41
• Other arithmetic operations on pointers are not allowed. Thus, a pointer variable
cannot be multiplied by a constant, two pointer variables cannot be added, and so
on.

Sample 3.8 Consider the simple C program shown below.

#include<stdio.h>
#include<conio.h>
main()
{
int *px;
int i = 1;
float f = 0.3;
double d = 0.005;
char c = ‘*’;
clrscr();
px = &i;
printf(“values: i = %d f = %f d = %f c = %c\n\n”,i,f,d,c);
printf(“addresses: &i = %x &f = %x &d = %x &c= %x\n\n”,&i,&f,&d,&c);
printf(“Poiner values:px = %x px+1 = %x px+2 = %x px+3 = %x”,
px,px+1,px+2,px+3);
getch();
return 1;
}

This program displays the values and addresses associated with four different types of
variables: i, an integer variable; f, a floating-point variable; d, a double-precision variable;
and c, a character variable. The program also makes use of a pointer variable, px that
represents the address of i. The values of px, px + 1, px +2, px + 3 are also displayed, so
that they may be compared with the addresses f the different variables.

Execution of the program results in the following output:

values: i=1 f = 0.300000 d = 0.00500 c=*


address: &i = fff4 &f = fff0 &d = ffe8 &c = ffe7
Pointer values: px = fff4 px + 1 = fff6 px + 2 = fff8 px + 3 = fffa

One pointer variable can be subtracted from another provided both variables point to
elements of the same array. The resulting value indicates the number of words or bytes
separating the corresponding array elements.

Sample 3.9 In the program shown below, two different pointer variables point to the first
and the last element of an integer array.

#include<stdio.h>
#include<conio.h>
main()
{
int *px, *py;

42
static int a[6] = {1,2,3,4,5,6};
clrscr();
px = &a[0];
py = &a[5];
printf(“px = %x py = %x”, px, py);
printf(“\n\npy - px = %x”, py - px);
getch();
return 1;
}

In particular, the pointer variable px points to a[0], and py points to a[5]. The difference
py – px, should be 5, since a[5] is the fifth element beyond a[0].

Executing this program results in the following output:

px = aa py = b4

py – px = 5

Pointer variables can be compared provided both variables point to objects of the same
data type. Such comparisons can be useful when both pointer variables point to elements
of the same array. The comparisons can test for equality or inequality.

Sample 3.9 Suppose px and py are pointer variables that points to elements of the same
array. Several logic expressions involving these two variables are shown below. All of
the expressions are syntactically correct.

(px < py)


(px > = py)
(px = = py)
(px ! = py)
(px = = NULL)

These expressions can e used in the same manner as any other local expression. For
example,

if (px < py)


printf(“px < py”);
else
printf(“px > = py”);

Moreover, expressions such as (px < py) indicate whether or not the element associated
with px is ranked ahead of the element associated with py.

43
Watch:

https://www.youtube.com/watch?v=4Rll-_e9-0M
https://www.youtube.com/watch?v=tw-qWGG8y5g

Read:

• Programming Logic and Design, 8 th ed/ 3rd edition, Joyce Farrel,2015

Review:

1. In what way does an array differ from an ordinary variable?


2. What condition must be satisfied by all of the elements of any given array?
3. What are subscripts? How are they written?
4. How does an array definition differ from that of an ordinary variable?
5. When passing an array to a function, how must the array argument be written?
How is the corresponding formal argument written?
6. What kind of information does a pointer variable represent?
7. What is the purpose of the indirection operator?
8. What is the relationship between an array name and a pointer?
9. How is a pointer variable declared? What is the purpose of the data-type included
in the declaration?
10. What kind of objects can be associated with pointer variables?

Activities/Assessment: Unit 3 Pointer

1. Logic trace the program and write the final output inside the box.

#include <stdio.h>

int array[] = {4, 5, 8, 9, 8, 1, 0, 1, 9, 3};


int index;

int main()
{
index = 0;
while (array[index] != 0)
++index;

printf("Number of elements before zero %d\n",index);


getch();
return (0);
}

44
2. Write the appropriate declaration for each of the following situations:

a. Declare two pointers whose objects are the integer variables a and b.
b. Declare a pointer to a floating-point quantity and a pointer to a double-precision
quantity.

3. Write the appropriate function definition for each of the following situations:

a) Write a function that separately sums the even indexed elements and old
indexed elements of an array of doubles. Each element of the array
contributes to one of the two sums, depending on whether the index of the
element is even or odd. Your function definition must have a heading like
this:
void sum(double b[ ])
{ int n;
double *sum_even;
double *sum_odd;
:
:
}

b) Write a function that computes two sums from the elements of an array of
integers. Each element of the array contributes to one of the two sums,
depending on whether the element itself is even or odd. Your function
definition should look like this:
void sum(int x[ ])
{ int n;
int sum_even;
int sum_odd;
:
:
}

Problem Solving

1. Write a program that uses the reorder( ) function to sort an array of integers.
2. Write another version of your program, modifying reorder( ) so that it terminates after
the first pass, in which two elements are interchanged.
3. Write a program that finds the maximum and minimum elements of a two-dimensional
array. Use an array version and a pointer version.

45
Unit 4 - STRUCTURES

Overview:

In this unit, you will learn to combine data of different types together. Structure helps to
construct a complex data type which is more meaningful. It is somewhat similar to an
Array, but an array holds data of similar type only. In structure, data is stored in form of
records.

Unit Objectives:

After successful completion of this unit, you should be able to:

• create a structure “template” or “definition”.


• declare a structure variable.
• gain access to the individual components of a structure variable.
• declare and use arrays of structures.
• access and manipulate array within a structure.
• use structure within a structure.
• apply all these concepts in advance programming.

Course Materials:

STRUCTURE: DEFINED

• A collection of variables that are referenced under one name, providing a


convenient means of keeping related information together;

• Gives a way to regard a diverse collection of objects as a single entity;

• Means of aggregating a collection of data items of possibly different types;

• Allows grouping of variables together under one name and is sometimes.

46
DEFINING/CREATING STRUCTURE

To define a structure means to form a template that may be used to create structure
variables. It creates the type of the structure but no storage is allocated.

Example:

Structure tag name( a user-defined identifier)

struct record
{
Keyword char name[30]; Members or elements of the structure
int age;
};

Semicolon is an important part to terminate


structure definition.

• This template describes a structure made up of one integer variable and one array
of character.

• The keyword struct tells the compiler that a structure is being defined.

• A semicolon terminates the definition because the definition itself is considered as


a valid C statement.

• A structure cannot contain a member with incomplete type. An example of an


incomplete type is an array declaration with no size specified.

Example:
struct record
{
char name[ ]; /*error*/
int age;
};

An incomplete type does not provide the compiler with enough information to determine
the size of the structure.

• You cannot write a function inside a structure.

• A structure is considered incomplete until the closing curly brace with semicolon }; is
encountered.

47
DECLARING STRUCTURE VARIABLE

Recall that we made use of the structure template

struct record
{
char name[30];
int age;
};

To use this template in declaring structure is best illustrated below:

Structure tag name( a user-defined identifier)

struct record mypal, hispal;

Keyword Structure variables

Which declares mypal and hispal to be structures of record type and causes structure
variables to be created. Upon receiving this instruction, the computer creates the variables
mypal and hispal. Referencing the template record, it allots space for an int variable age
and char array of name.

As far as the computer is concerned:

struct record
{
char name[30];
int age;
};
struct record mypal, hispal;

is short for

struct record
{
char name[30];
int age;
}mypal, hispal; //tack on variable name to template

You can also combine the template and the variable definitions in which case, the
tag name need not be used. However variable definition is for one circumstance only.

48
struct //no tag name
{
char name[30];
int age;
}mypal; //tack on variable name to template

struct //no tag name


{
char name[30];
int age;
}hispal; //tack on variable name to template

Note: The tag name is much handier if you use a structure template more than once.

INITIALIZING A STRUCTURE VARIABLE

Structure variable can be initialized.

Example:

struct record
{
char name[30];
int age;
};
struct record mypal = {“John”, 21};
struct record beatles[3] = {{“John”, 21}, {“Paul”, 22}, {“Ringo”, 23}};

REFERENCING STRUCTURE ELEMENTS

Just like arrays, structure members can be referenced or accessed. This is by using the
structure member operator “.” to get at the individual members of a structure. For
example, mypal.age is the age member of the struct mypal. You can use mypal.age
exactly as you would use any other integer variable. Similarly, you can use mypal.name
exactly as you would use for an array of character. Thus, we could use expression like:

Using input function:

gets(mypal.name); or scanf(“%s”, mypal.name);


scanf(“%d”, &mypal.age);

Using assignment operator:

strcpy(“John”, mypal.name);
mypal.age = 21;

The .name refers to the first member of mypal structure, and .name refers to the second
member of the struct mypal.

49
Sample 4.1 A program that would simply read and display student’s name and age as
structure members.

#include<stdio.h>
#include<conio.h>
void main( )
{
struct record //structure definition
{
char name[30];
int age;};
struct record mypal; //declaration of struct variable mypal
printf(“Enter name:”);
gets(mypal.name);
printf(“Enter age:”);
scanf(“%d”,&mypal.age);
printf(“%s is %d years old.”, mypal.name, mypal.age);
getch( );
}
Sample Run:

Enter name: Loyda


Enter age: 24
Loyda is 24 years old

Sample 4.2

#include<stdio.h>
#include<conio.h>
void main( )
{
struct book //structure template, tag name is book
{
char title[40]; //struct member, string array for title
char author[40]; //struct member, string array for author
float value; //struct member, float variable to store value of book
}; //end of structure template
clrscr( );
struct book libry; //declaration of variable of book type
printf(“Please enter the book title:\t”);
gets(libry.title); //access to the member title
printf(“Please enter the author’s name:\t”);
gets(libry.author); //access to the member author
printf(“Enter the value:\t”);
scanf(“%f”, &libry.value); //access to the member value
//displaying contents of struct book libry
printf(“%s by %s:\t%f”, libry.title, libry.author, libry.value);
getch( );
return 1;
}

50
Sample Run:

Please enter the book title: Learning C is Fun


Enter the author’s name: Sam Sons
Enter the value: 357.75
Learning C is Fun by Sam Sons: 357.75

Oops . . . Before you proceed…


Note: Just in case you wonder why the sample programs made use of gets( ) instead of
scanf( ), recall the scanf( ) terminates the reading of a string value once a space is
encountered. Thus, it is more appropriate to use gets( ) in reading string inputs to
accommodate string value with more than one word.

ARRAY OF STRUCTURES

Array of structures are just the same with ordinary arrays such as arrays of list, float and
char. However, the use of arrays of structures will enable us to handle different data in a
much easier way. Since structures can have members of different data type, it follows
that arrays of structures can handle and manipulate many structures once template has
been created. First, we should learn how to declare arrays of structures, second, how to
get access to individual members.

DECLARING AN ARRAY OF STRUCTURES

The process of declaring an array of structure is perfectly analogous to declaring any other
kind of array.

Recall our struct template record, and our struct variable mypal of type struct record. Let’s
fix our program so that 10 students’ name and age can be entered and displayed. To
handle this, we need an array of structures.

struct record
{
char name[30];
int age;
};

struct record buddies[5]; //declaration of array of struct team with 5 elements

Each element of the array team is a structure of record type. Thus, buddies[0] is a record
structure, buddies[1] is a second record structure, and so on. The name team itself is not
a structure name; it is the name of the array holding the structures. The actual structures
would then be team[0], team[1] and so on.

51
name age

buddies[0] buddies[0].name buddies[0].age


The dot operator
buddies[1]
. buddies[1].name buddies[1].age
.
. Index of the
buddies[5] buddies[5].name buddies[5].age array struct

Before we proceed with the discussion of sample programs, please remember the
following important considerations in implementing or using array of structures.

• To declare an array of structures, you must first define a structure, and then declare
an array variable of that type.
• To access a specific structure within the array, the structure variable name is
indexed.
• Arrays of structures begin their indexing at 0.

Let’s proceed with the revision of our program in Sample 4.1 and make use of array of
structures to handle 5 students.

Sample 4.2

#include<stdio.h>
#include<conio.h>
void main( )
{
struct record
{
char name[30];
int age;
};
int ctr;
struct record buddies[5]; //declaration of array of struct
variable buddies with 5 elements
for(ctr = 0; ctr < 5; ctr++)

{
printf(“Enter name:”);
scanf(“\n”);
gets(buddies[ctr].name);
printf(“Enter student age:”);
scanf(“”%d”, &buddies[ctr].age);
}
//loop to display values of the entire array of struct buddies[5]

for(ctr = 0; ctr < 5; ctr++)


{

52
printf(“%s is %d years old.\n”, buddies[ctr].age);
}
getch( );
return;
}

Enter student name: Hannah


Enter student age: 17
Enter student name: Ruth
Enter student age: 19 Run
Enter student name: Joshua
Enter student age: 20
Enter student name: Daniel
Enter student age: 18
Enter student name: Abigail
Enter student age: 15
Hannah is 17 years old
Ruth is 19 years old
Joshua is 20 years old
Daniel is 18 years old
Abigail 15 years old

53
Watch:

https://www.youtube.com/watch?v=7zXqMD6Fj_E
https://www.youtube.com/watch?v=-Vy4qrl675E

Read:

• Programming Logic and Design, 8 th ed/ 3rd edition, Joyce Farrel,2015

Review:

1. What is structure?
2. What are the advantages of structure?

Activities/Assessment: Unit 4 - Structure

1. Determine which of the following statements are true and which are false.

__________ a. A structure cannot have two fields with the same name.
__________ b. A structure cannot have two fields of the same type.
__________ c. A structure must have at least one field.
__________ d. A field in a structure can itself be a structure.
__________ e. A structure cannot have members with the same name.

2. Create a template for a structure of student record consisting of five fields:


Student ID(int), first name(string), last name(string), total units completed(int), and
accumulated grade point average(float).

3. Create a structure that can describe a restaurant. It should have members that include
the name, address, average cost, and type of food available.

54
4. Declare an array of structures with 12 elements. Each element is a structure with three
fields. The first field shows the month in numeric form (1 to 12). The second field
shows the name of the moth. The third field shows the number of days in the month.

5. Explain what is wrong with the following:

struct myStruct
{
int a;
float b;
struct thisStruct c;
};

struct thisstruct
{
int d;
float e;
struct myStruct c;
};

6. Explain what’s wrong with this template.

Structure{
char *emp_name;
int rank_number[20];
char dept_name;
}

55
7. Trace the output of the following:

#include<stdio.h>
#include<conio.h>
void main()
{
struct myStruct
{
int a, b;
};

struct myStruct myArray[5];


int i;
clrscr( );
for(i=0;i<5;i++)
{
myArray[i].a=i;
myArray[i].b=5-i;
}
for(i=0;i<5;i++)
{
printf(“%d %d %d\n”,i, myArray[i].a,myArray[i].b);
}
getch();
}

Output:

PROGRAMMING PROBLEMS

56
Programming Problems

1. Write a program to score five – card poker hands into one of the following categories:
nothing, one pair, two pairs, three of a kind, straight (in order), flush(all the same suit),
full house(three of a kind and one pair), four of a kind and a straight flush (both straight
and flush). Use an array of structures to store the hand. The structure has one
member for the value and one for the suit of the card.

2. Using the concept of structures, write a program to assign passenger seats in an


airplane. Assume a small airplane with seats numbered as follows:

1 A B C D
2 A B C D
3 A B C D
4 A B C D
5 A B C D

The program should display the seat pattern, marking with an ‘X’ the seats already
assigned. For example, after seats 1A, 2B, and 4C are taken, the display should look like:

1 X B C D
2 A X C D
3 A B C D
4 A B X D
5 A B C D

Seats are assigned by specifying a number and a letter. If the user types in a seat
that is already assigned, the program should say that the seat is occupied and ask for
another choice. The program should run until all seats are filled, or the user signals that
the program should end.

STRUCTURE WITHIN STRUCTURE

It is just common that you will need data type such as arrays as members of the structure.
The same true with problems which may require the use of structure as another member
of the same struct.

The first point to remember is how the inner structure is set up in the template. It is simply
declared, just as an int or any other data type of variable would. Let’s discuss this using
the sample program below.

Sample 4.4

#include<stdio.h>
#include<conio.h>
void main( )
{

57
struct date
{
int month, day, year;
}
struct record
{
char name[30];
int age;
struct date bdate;
};
struct record mypal;
int ctr;
clrscr( );
for(ctr = 0; ctr < 5; ctr++)
{
puts(“Enter name:”);
gets(mypal.name);
printf(“Enter age:”);
scanf(“”%d”, mypal.age);
puts(“Enter birthdate month in number:”);
scanf(“%d”,&mypal.bdate.month);
puts(“Enter birthdate day in number:”);
scanf(“%d”,&mypal.bdate.day);
puts(“Enter birthdate year in number:”);
scanf(“%d”,&mypal.bdate.year);
printf(“Hello %s!\n”, mypal.name);
printf(“Your birthday is on %d-%d-%d!\n”,mypal.bdate.month, mypal.bdate.day
mypal.bdate.year);
printf(“Wow you’ll be %d soon!”, mypal.age+1);
getch( );}

PASSING STRUCTURE TO FUNCTIONS

• When a structure is used as an argument to a function, the entire structure is


passed using the standard call by value method.

• Any changes made to the contents of the structure inside the function to which it
is passed do not affect the structure used as an argument.

• When using a structure as a parameter, the most important thing to remember is


that the type of the argument must match the type of the parameter. The best way
to do this is to define a structure globally and then use its name to declare structure
variables and parameters as needed.

Example:

struct record //global template of structure record


{
char name[30];
int age;

58
};
void funct(struct record paramrec);//function prototype with structure as
parameter
void main( )
{
struct record argrec;
argrec.age = 23;
funct(argrec); //function call passing structure argrec
getch( );
}
void funct(struct record paramrec);
{
printf(“%d”, paramrec.age); //prints 23 on the screen
}

Sample 4.5 Sample program for passing array of structure to function.

#include<stdio.h>
#include<conio.h>

struct product
{
char pname[30];
int num;
float bill, price;
};
void funct(struct product two[ ); Sample Run:
void main( )
{ Enter product name: Monitor
clrscr( ); Enter number: 2
struct product one[2]; Enter price: 2500
float temp;
int a; Enter product name: Printer
for(a = 0; a < 2; a++) Enter number: 3
{
Enter price: 7000
printf(“\nEnter product name:”);
scanf(“”);
gets(one[a].pname); Values of records are:
printf(“\nEnter number:”);
scanf(“”); Monitor 2 2500
scanf(“%d”, &one[a].num); Printer 3 7000
printf(“\nEnter price:”);
scanf(“%f”,&temp); Total bill is 26000.00
one[a].price = temp;
one[a].bill = one[a].num * one[a].price;
}

59
funct(one);
getch( );
}
void funct(struct product two[ ])
{
int a;
float tbill = 0.00;
for(a = 0; a < 2; a++)
tbill = tbill + two[a].bill;
printf(“\nValues of the recors are:\n\n”);
for(a = 0; a < 2; a++)
printf(“%s %d %0.2f\n”, two[a].pname, two[a].num, two[a].price, two[a].bill);
printf(“\nTotal bill is %0.2f”,tbill);
}

POINTER TO STRUCTURE

We can create a pointer to the data type you are familiar with scuh as character, integer,
float and double, structure can be pointed by another structure of the same type.

Declaration:

struct <tag name> *<pointer to structure variable>;

Example:

1 struct record
2 {
3 char name[30];
4 int age;
5 };
6 struct record buddy, *pointbuddy;
7
8 pointbuddy = &buddy;

The above example shows how to declare a pointer to structure through the bold
statement in line #6.

Line #8, shows how pointer-to-structure pointbuddy points to the address of


structure buddy.

Note: to find the address of a structure variable, the & operator is placed before the
structure’s name.

Example:

pointbuddy = &buddy;

The statement above points pointbuddy to the address of buddy

60
To access a structure element being pointed by a pointer-to-structure variable, the arrow
operator is used, not the dot operator. A minus and greater than symbol is combined.

-> Arrow operator

Example: pointbuddy->age = 23 + 3;

Sample 4.6 Sample program for passing structure to function using pass by reference or
using the pointer to struct.

#include<stdio.h>
#include<conio.h>

struct record
{
char name[30];
int age;
};

void fpass(struct record *recX);

void main( )
{
clrscr( );
int a;
struct record recY = {“Arnie”, 23};
printf(“In main, Before:\n”);
printf(“%s %d\n”, recY.name, recY.age);
fpass(&recY);
printf(“In main, After:\n”);
printf(“%s %d\n”, recY.name, recY.age);
getch( );
}
Void fpass(struct record *recX)
{
printf(“In fpass:\n”);
printf(“%s %d\n”, recX->name, recX->age);
recX->age = recX->age + 3;
}

Sample Run:

In main, Before:
Arnie 23

In fpass:
Joselito 26

In main, After:
Joselito 26

61
Activities/Assessment: Unit 4 - Structure- Part2

1. Trace the output of the following and write the final output inside the box.

#include<stdio.h>
#include<conio.h>
void main( )
{
struct myStruct
{
int a, b;
};
struct myStruct myArray[5];
struct myStruct *p;
int c;
p = myArray;
for(c =0; c < 5; c++)
{
(p + c) -> a = c;
(p + c) -> b = c * 2;
}
for(c = 0; c < 5; c++)
{
printf(“%d %d %d\n”, c, myArray[c].a, myArray[c].b);
}
getch( );
}

2. Given:
struct record
{
char name[10];
int age;
};
struct record myfriend = {“Dhang”, 24};
struct record *ptrtomyfriend = &myfriend;

Write a C statement showing how to display the value of first member being pointed
by ptrtomyfriend, using ptrtomyfriend.

62
3. Write a C statement showing how to display the value of the second member being
pointed by ptrtomyfriend.

4. Write a C statement showing how to store new value of the members being pointed
by ptrtomyfriend.

PROGRAMMING PROBLEM

The inventory of a shoe store lists shoes by stock number. With each stock number, there
is associated a style number in the range of 0 to 50, the number of pairs in each size (sizes
range from 3 to 14) and a price. A program is to be written to keep track of the inventory.
The user is given the following choices: enter a new record, display a record, change the
price of the stock item, or change the number on hand. When specifying a record the user
may give either the stock number, or the style number. The array index can be used as a
stock number. If the user decides to change the stock on hand, the program should ask
which sizes will have their stock on hand changed. The program should be designed to
run indefinitely, keeping track of changed in stock.

63
Unit 5 - LINEAR LINKED LISTS

Overview:

In this unit you will learn one of the useful data structure and that is linear linked lists. The
concept of a linked list in C programming will be covered and its advantages. A
demonstration of its usage in a program is presented with insert, delete, and search
operations. A linked list is a dynamic data structure where each element (called a node)
is made up of two items: the data and a reference (or pointer), which points to the next
node. A linked list is a collection of nodes where each node is connected to the next node
through a pointer.

Unit Objectives:

After successful completion of this unit, you should be able to:

• know in details the basic concepts of Link List.


• know the algorithm of linear link list – creation, display and looking up an element.

Course Materials:

LINKED LIST

Definition: Link List is a group of nodes or records set which are linked together through
the use of pointers. You might think of it just like a chain where each chain is attached to
one another.

There are different types of linked list:

1. Stacks
2. Queues
3. Uni- directional Lists (Linear- Linked Lists)
4. Bi- directional Lists (Double Linked Lists)
5. Circular List
6. Sorted List

The focus of this lesson will be bounded to a linear linked list.

64
Linear Linked List: Basically the node or record of linear linked list has at least two
members, the first member that will hold a value may it be to type char, int, float or double
and the second member will be a pointer to address of the next node.

Actual you could create more than one member to hold for different values but,
what you should remember at this point of discussion is that the node should
have a member that will hold the address of the next node.

NODE REPRESENTATION

Value holder Pointer to another node


(1st member) Holder
(2nd member)

Address of the node

Figure #1

Terms to Remember:

1. Head- refers to head or front of the list


2. Tail- refers to tail or end of the list.
3. Null-indicate empty or NULL.
4. Node-used to refer to single record in a dynamic structure

Let us first design our node by using the following structure definition

struct node
{
char value;
struct node *nextnodeaddress;
};

This structure has two members, the first member will store character value, the
second member is a pointer to structure that would hold or points the address of another
structure of the same type or tag-name.

Now, let us declare a pointer to structure with the names –current, head & tail, which are
of structure type node that has been recently defined.

struct node*current,*head,*tail;

65
ALGORITHM: Creating a list

Let us now discuss the algorithm of our linear-linked list:

1. Design a node template with 2 members, one member that will hold a character
value and the other member that will hold an address of the same node type.
2. Create the following variable node, which is actually a pointer structure:

a. current
b. head
c. tail

3. Point variable current, head, & tail to NULL.


4. Allocate memory space for the first node using the variable current
5. Input a character value ‘A’ to the 1 st member of the 1st node created (current)
6. Point the 2nd member of the 1st node created (current) to NULL.
7. Point variable head or current since we are at the 1 st node, which is a special
case.
8. Point variable tail to current.(tail always point where current is pointing).
9. Allocate again a memory space for our 2nd node using the variable current.(current
will be pointing now the 2nd node, leaving 1st node to head and tail)
10. Input a character value ‘B’ to the 1 st member of the 2nd node created (current).
11. Point the 2nd member to the 2nd node created (current) to NULL.
12. Point the 2nd member to the 1st node (head or tail) to current since current is now
pointing to the 2nd node.
13. Point now variable tail to current. (tail always point where current is pointing)
14. Allocate again a memory space for our 3 rd node using the variable current. (current
will be pointing now the 3 rd node, leaving 2nd node tail).
15. Input a character value ‘C’ to the 1 st member of the 3rd node created (current).
16. Point the 2nd member of the 3rd node created (current) to NULL.
17. Point the 2nd member the 2nd node (tail) to current since current is now pointing to
the 3rd node.
18. Pointing now variable tail to current. (tail always point where current is pointing).

Following step 1 to 18, while looking at figure 2 will help you fully understand how the
relationships of the three nodes were established. Assuming that the 1 st node created
was allocated at the memory address 300, and the 2 nd node created was allocated at
the memory address 500 & the 3 rd node created was allocated at the memory address
700.

Table 1. Value stored in the pointer structure value.

current head tail


On initialization NULL NULL NULL
1st node 300 300 300
2nd node 500 (Remains 300) 500
3rd node 700 (Remains 300) 700

66
Last values:

Current= 700
Head= 300
Tail =700

FIGURE # 2: Linear Linked list Representative

‘A’ ‘B’ ‘C’

64300 64500 65700


NULL

head current tail

Figure # 2: shows the relationship of the three nodes. As you can observe the first
node ‘s second member is pointing to the 2nd node address and the 2nd node’s second
member is pointing the 3rd node address, and the 3rd node’s second member pointing
to NULL. In this way we have seen the analog of the linear linked list to chain.

ALGORITHM: Displaying the list

Assuming that we will continue our logic of creating a list, add the following to
algorithm to display the list.
1. Point variable current to head.
2. While current is not null
Begin
2.a. Display the value of current ‘s 1st member.
2.b. Point to current to current’s 2nd member (in order to switch or transfer
current to the next node).
End.

THINGS TO REMEMBER:

The important things to remember is what we have a variable that will hold the address
of the very first node of the list, which is the variable head.

67
initial loop

‘A’ ‘B’ ‘C’

64300 64500 65700


NULL

head current tail

2nd loop

‘A’ ‘B’ ‘C’

64300 64500 65700


NULL

head current tail

3rd loop

‘A’ ‘B’ ‘C’

64300 64500 65700


NULL

head current tail

Program to create, display, and search a list

#include <stdio.h>
#include <conio.h>
#include <alloc.h>

void main()
{ /* begin main */
struct node { /* 1 * /
char value;

68
struct node *nextnodeaddress;
};

struct node *current,*head, *tail; /* 2 */

current = NULL; /* 3 */
head = NULL;
tail = NULL;

current = (struct node*) malloc (sizeof(struc node)); /* 4 */


current->value = ’A’; /* 5 */
current->nextnodeaddress = NULL; /* 6 */
head = current; /* 7 */
tail = curent; /* 8 */

current = (structnode ) malloc (sizeof(strucnode)); /* 9 */


current->value = ’B’; /* 10 */
current->nextnodeaddress = NULL; /* 11 */

head->nextnodeaddress = current; /*12*/


tail = current; /* 13 */

current = (ctrucnode ) malloc (sizeof(struct node));/* 14 */


current->value = ’C’; /* 15 */
current->nextnodeaddress = NULL; /* 16 */

tail->nextnodeaddress = current; /* 17 */
tail = current; /*18*/

/****displaying the list****/

clrscr();
current = head; /* 1 */
while (current ! = NULL) /* 2 */
{ printf(“%c/n”,current->value); /* 2.a */
current = current->nextnodeaddress;} /* 2.b */
/* continuation….*/

/****searching the list****/

intf found = 0;
char chartosearch;
printf(“Type the character to search: “);
scanf(“%”,&chartosearch);

current = head;
while (current ! = NULL)
{ if (current->value = = charctosearch)
{
found = 1;
break;

69
}
else
current = current->nextnodeaddress;
}
if (found = = 0)
printf(“\n%c is not on the list”,chartoesarch);
else
printf(“\n%c is on the list!”,chartosearch);
getch();
}

SAMPLE OUTPUT # 1:

A
B
C
Type the character
to search: B

B is on the list

SAMPLE OUTPUT #2:


A
B
C
Type the
character to
search : D

D is not on the list

70
Watch:

https://www.youtube.com/watch?v=dmb1i4oN5oE
https://www.youtube.com/watch?v=6wXZ_m3SbEs

Read:

• Programming Logic and Design, 8 th ed/ 3rd edition, Joyce Farrel,2015

Review:

1. What is linear linked list?


2. What are the advantages of linear linked list?
3. How does it is used?

Activities/Assessment: Unit 5 - Linear Linked List

A. Follow the requirements and write a complete and valid C-statement/s for each item.

1. Create a node name TEMPLATE that contains your name (15 element array
of char), age (int) and a pointer to structure of the same structure type.

2. Create structure name HEAD, TAIL and CURRENT of type TEMPLATE.

3. Allocate memory location for CURRENT.

4. Assign “Loyda” to the CURRENT ‘s first member

71
5. Assign 24 to CURRENT ’s second member

6. Point CURRENT ’s third member to NULL

7. Point HEAD to CURRENT

8. Point TAIL to CURRENT

9. Repeat item #3

10. Using scanf( ) function write a C-statement that will assign value to the 1 st and
2nd members of CURRENT.

11. Repeat item #6,7and 8.

12. Write C- statement that will display the value of 1 st and 2nd member of HEAD

72
13. Write a C- statement that will display the value of 1 st and 2nd member of TAIL

14. Draw the linked list representation of the above statements showing the where
the HEAD, CURRENT, TAIL points finally. Also assume that the node have
valid value in it,

B. Trace the programs below and write the final output inside the box.
1.
#include <stdio.h>
#include<conio.h>
#include<alloc.h>

struct roy {
int Item;
struct roy *next;
};
void main()
{
struct roy *r1,*r2,*r3;
r1 = (struct roy *) malloc (sizeof(struct roy));
r2 = (struct roy *) malloc (sizeof(struct roy));
r3 = (struct roy *) malloc (sizeof(struct roy));

clrscr();
r1->Item = 357; OUTPUT
r1->next = NULL;
r2->Item = 5654;
r2->next = NULL;
r3->Item = 14344;
r3->next = NULL;
r2->next = r3;
r3 = r1;
r1 =r2 ->next;
r3->next = r2;
r1->next = r1;
printf(“%d\n”, r1->Item);
printf(“%d\n”, r2->Item);
printf(“%d\n”, r3->Item);
getch();
}

73
2. Differentiate the output of the two programs.

a. struct node
{
int x;
node *next;
};

int main()
{
node *root; // This will be the unchanging first node
root = new node; // Now root points to a node struct
root->next = 0; // The node root points to has its next pointer
// set equal to a null pointer
root->x = 5;} // By using the -> operator, you can modify the node
// a pointer (root in this case) points to.

OUTPUT

b. struct node
{
int x;
node *next;
};

int main()
{
node *root; // This won't change, or we would lose the list in memory
node *conductor; // This will point to each node as it traverses the list

root = new node; // Sets it to actually point to something


root->next = 0; // Otherwise it would not work well
root->x = 12;
conductor = root; // The conductor points to the first node
if ( conductor != 0 ) {
while ( conductor->next != 0)
conductor = conductor->next;
}

conductor->next = new node; // Creates a node at the end of the list

74
conductor = conductor->next; // Points to that node
conductor->next = 0; // Prevents it from going any further
conductor->x = 42;}

OUTPUT

75
Unit 6 - FILE HANDLING

Overview:

In this unit, you will learn about file handling in C. You will learn to handle standard I/O in
C using fprintf(), fscanf(), fread(), fwrite(), fseek() etc. with the help of examples. A file is
a container in computer storage devices used for storing data. File handling in C refers
to the task of storing data in the form of input or output produced by running C programs
in data files, namely, a text file or a binary file for future reference and analysis.

Unit Objectives:

After successful completion of this unit, you should be able to:

• know in details the basic concepts of Files.


• know how the values of variable be stored in a secondary storage & retrieve them.
• apply and create a real-world programming application with the use of files.

Course Materials:

File Handling

• File is a collection of logically related information


• File is a built-in structure definition that holds value into a storage device.

Before you continue:

In order to work in a file , a file-stream is associated.

Question: What is a stream?


printf(“%d\n”r1->Item);

Answer: Stream is a logical device that enables to functions to work with variety
of physical device such as the monitor, printer, and secondary storage such as
disk drives and CD-ROM drives. Streams are device independent, the functions
that write to disk file can also write to the monitor.
Therefore we can think stream as controller to the program to access
different device, but our discussion will be limited to secondary storage stream
or what we call file stream. Since file is written to & read form a disk

76
Assuming a program ask about your name and you age and the values you entered
will be saved to a variable; but as the program terminates the values that had been stored
to the variables would never retrieved again, right? Yes!
But through file handling we can retrieved manipulate data that has been entered
previously input by saving those values into a disk rather than a memory alone which is
we know is volatile!

What really is file? Can you explain further!

When dealing with file we should remember that we are dealing with 2 objects:

1. the logical file or stream and;

2. the physical file or disk- file

The logical File is the one that being controlled program flow while the physical file is
the actual file where the values are save through the file name. The Logical file or the
stream is always associated to the physical file.

File tend to save the values into a disk, so that the values can be retrieved for future use.

What are the characteristic of a file?

1. Has a name (logically & physically)

2. Must be opened and closed (when the logical file is closed the values from the
logical file will be stored to the physical file)

3. Can be written to, or read from, or appended to;

File Processing Activities:

1. Declaring a file-stream
2. Opening a file-stream
3. Writing to a file-stream
4. Reading from a file-stream
5. Closing a file-stream

DECLARING A FILE
To declare a file we are to use a file pointer.

File pointer: Defined


• A pointer to information that defines various things about the file, including
the name, status and current position.
• It identifies a specific disk file and is used by the stream associated with it to
tell each of the buffered I/O functions where to perform operations.

To declare a file pointer we are to use the structure type FILE. Remember that
FILE is a structure type, which was defined in stdio.h.

77
syntax:
FILE *file_pointer_variable;

type definition a valid identifier

example:
FILE *fp;
FILE *fp1, *fp2;

The file pointer we have just created is the stream that will be used to interact to
with the disk-file.

OPENING A FILE
To open a file, we need a function fopen( ), this function opens a file and associate
a stream with it. It returns a pointer that identifies the stream in subsequent operations.

syntax:
filepointer = fopen(“<filename>”, “<mode>”);

filepointer – is the previously created FILE structure, this is the logical file.

filename – must be string that provides a valid name for the operating system, for
DOS a 1 to 8 characters length followed by a period then a 0 to 3 character length as
extension name, this is the disk file or the physical file.

example:
letter.txt
file1.dat

mode – points to a string containing the desired open status. The legal values are
the following:

String Definition
“r” Open for reading only
Create for writing
“w”
If a file by that name already exists, it will be overwritten
Append; open for writing at end of file, or create for writing if the file does
“a”
not exist
“r+” Open an existing file for update (reading and writing)
Open for append; open for update at the end of the file, or create if the file
“a+”
does not exist.

• To specify that a given file is being opened or created in text mode, append “t” to
the string (“rt”, “rw”, “w+t”, ect.) or not at all (“r”, “w”, “w+”, etc.)
• To specify binary mode, append “b” to the string (“wb”, “a+b”, ect.). fopen( ) also
allow the “t” or “b” to be inserted between the letter and the “+” character in the
string. For example, “rt+” is equivalent to “r+t”.

78
Note: fopen( ) function returns a pointer of type FILE. The value returned
should never be altered. This function returns a NULL pointer if the file can
not be opened.
example:
fp = fopen(“dog.dat”, “rb”); //binary mode
fp1 = fopen(“cat.txt”, “rt”); //text mode
fp2 = fopen(“cat.txt”,”r”); //text mode also

Since fopen( ) returns a pointer, we can check if the value returned is a NULL, if
so then the file cannot be opened. You can add this bold statement after opening a file
pointer.

fp1 = fopen(“cat.txt”, “rt”);


if(fp1 = = NULL)
{puts(“error in fopen! Something wrong!”
exit(1);
}

The above additional program segment is useful as an error trapping code and is
recommended to be included in our program.

NULL is a keyword for empty, we could also substitute zero (0) for it

WRITING TO A FILE(text mode)

To write to a text mode file, we are to use function fprintf( ), this function writes or
prints to the stream associated with the file. It appends a specified number of equal-sized
data items to an output file, instead of printing to the screen it prints to the file.
fprintf( ) function has 3 parameters.

syntax:
fprintf(file pointer, format specifiers, source variable list);

Sample 1
/* this program stores the value of name to file named “MyFamily.txt” */

#include<stdio.h>
#include<conio.h>

void main( )
FILE *fp;
fp = fopen(“MyFamily.txt”,”w”); //write mode
char name[15] = “Melita”;

fprintf(fp, “%s\n”, name);

79
fclose(fp);
}

Sample 2
/* this program stores the value of age to file named “Numbers.txt” */

#include<stdio.h>
#include<conio.h>

void main( )
FILE *fp;
fp = fopen(“Numbers.txt”,”w”); //write mode
int age;

puts(“How old are you?”);


scanf(“%d”, &age);

fprintf(fp, “%d\n”, age);

fclose(fp);
}

Sample 3
/* this program store the value of myfriend to file named “MyData.txt” */

#include<stdio.h>
#include<conio.h>

void main( )
FILE *fp;
fp = fopen(“MyData.txt”,”w”); //write mode

struct record
{
char name[10];
int age;
};

struct record myfriend = {“Loyda”, 23};

fprintf(fp, “%s %d\n”, myfriend.name, myfriend.age);

fclose(fp);
}

80
READING FROM A FILE (Text Mode)

To read from a text mode file, we are to use function fscanf( ), this function reads from
the stream associated with the file. Just like fprintf( ), fscanf( ) has the same number
and type of parameters, the difference is that the format specifications should be prefixed
with and address operator ( & ).

syntax :
fscanf(file pointer, format specifications, &destination variable list);

Sample 4
/* this program reads values from file “MyFamily.txt” and stores it to variable
code and displays it to the screen*/

#include<stdio.h>
#include<conio.h>

void main( )
FILE *fp;
fp = fopen(“MyFamily.txt”,”r”); //read mode
char code[20];

fscanf(fp, “%s\n”, code);

printf(“The value from the file is:”);


printf(“%s”, code);

fclose(fp);
}

Sample 5
/* this program reads values from file “Numbers.txt” and stores it to variable
code and displays it to the screen*/

#include<stdio.h>
#include<conio.h>

void main( )
FILE *fp;
fp = fopen(“Numbers.txt”,”r”); //read mode
int count;
fscanf(fp, “%d\n”, &count);
puts(“The value fetched is:”);
printf(“%d\n”, count);
fclose(fp);
}

81
Sample 6
//READ AND DISPLAY

#include<stdio.h>
#include<conio.h>

void main( )
FILE *fp;
fp = fopen(“MyData.txt”,”r”); //read mode

struct record
{
char name[10];
int age;
};

struct record myfriend; /*fetch from stream and store it to variable*/

fscanf(fp, “%s %d\n”, myfriend.name, &myfriend.age);


puts(“here are the values taken from a file:”); /*displayto console*/
printf(“%s %d”, myfriend.name, myfriend.age);
fclose(fp);
}

Sample 7

/*if more than one record or values were stored in a file, this program show you how
to fetch all the values*/
/*to fetch and display all of the record stored in the file*/

#include<stdio.h>
#include<conio.h>

void main( )
FILE *fp;
fp = fopen(“MyData.txt”,”r”); //read mode
struct record
{
char name[10];
int age;
};
struct record myfriend;
while(fscanf(fp, “%s %d\n”, myfriend.name, &myfriend.age)! = EOF)
printf(“%s %d”, myfriend.name, myfriend.age);

fclose(fp);
}
Note: Unlike fread( ) sample #3 in binary text mode fscanf( ) uses EOF
keyword instead of using NULL keyword or zero( 0). EOF mean End-Of-File

82
Sample 8
/*Create a text mode file for writing*/

#include<stdio.h>
#include<conio.h>
#include<process.h>

struct s_friend
{
char name[50];
int age;
float wage;
};

void main( )
FILE *fp;

struct s_friend f;
int a;
clrscr( );
if(fp = fopen(“friends.dat”,”wt”))= = 0)
{printf(“Error”);
exit(1);
}

for(a = 0; a < 3; a++)


{
printf(“Enter name:”);
scanf(“%s”, &f.name);
printf(“Enter age:”);
scanf(“%d”, &f.age);
printf(“Enter wage:”);
scanf(“%f”, &f.wage);

fprintf(fp, “%s %d %f\n”, f.name, f.age, f.wage);


}

fclose(fp);
}

Sample 9
/*Open a text mode file for reading*/

#include<stdio.h>
#include<conio.h>
#include<process.h>
struct s_friend
{
char name[50];

83
int age;
float wage;
};

void main( )
FILE *fp;
struct s_friend f;
int a;
clrscr( );
if(fp = fopen(“friends.dat”,”rt”))= = NULL)
{printf(“Error”);
exit(1);
}

while(fscanf(fp, “%s%d%F\n”, &f.name, &f.age, &f.wage)! = EOF)


printf(“%s %d %.2f\n”, f.name, .age);

fclose(fp);
}

CLOSING A FILE

To close a file, we are to use fclose( ) function, which is used to close the stream
or the file pointer that was previously opened by a call to fopen( ). It is always
recommended that we close the file we have opened previously in order to sure that the
data written to it will b saved.

syntax:
fclose(file_pointer_variable);

Previously opened file pointer variable using fopen( ) function

example:

fclose(fp);
fclose(fp1);
fclose(fp2);

WRITING TO A FILE(Binary Mode)

To write to a binary mode file, we are to use function fwrite( ), this function wites
to the stream associated with the file. It appends a specified number of equal-sized data
items to an output file.

fwrite( ) function has 4 parameters.

84
syntax:

fwrite(&source variable, size of source variable in bytes, number of data items to be


appended, file pointer);

Example #1:

char name[20] = “Roy”;

fwrite(&name, sizeof(name),1,fp);

Example #2:
struct record
{
char name[10];
int age;
};

struct record myfriend = {“Roy”, 23};

fwrite(&myfriend, sizeof(struct record),1,fp);

note: The 3rd paramenter is always set to 1 in this discussion.

READING FROM A FILE(Binary mode)

To read from a binary mode file, we are to use function fread( ), this function reads
or fetches values/s from the stream associated with the file and then stores the value
fetched to a variable. Just like fwrite( ), fread( ) has the same number and type of
parameters.

syntax:
fread(&destination variable, size of destination variable in bytes,
number of data items to be read, file pointer);

Example #1
char name[10];

fread(&name, sizeof(name),1,fp);

Example #2
struct record
{
char name[10];
int age;
};

struct record myfriend;

fread(&myfriend, sizeof(struct record),1,fp);

85
printf(“\n%s %d”, myfriend.name, myfriend.age);

Example #3
struct record
{
char name[10];
int age;
};

struct record myfriend;

while(fread(&myfriend, sizefo(struct record)1,fp) ! = NULL)


printf(“\n%s %d”, myfriend.name, myfriend.age);

ADDITIONAL FILE FUNCTIONS:


Deleting a filename: remove( ) function.

syntax:

remove(filename);

example:

remove(“roy.dat”);

Renaming a filename: rename( ) function.

syntax:

rename(filename to be replaced, new file name);

example:

rename(“temp.dat”, “roy.dat”);

Sample 10
Complete Sample Program for Binary File
/*Creating a Binary File*/

#include<stdio.h>
#include<conio.h>
#include<process.h>

struct record //structure definition


{
char name[50];

86
int age;
float wage;
};

void main( ) //begin main program


FILE *fp; //file declaration

struct record myfriend; //structure declaration


char file[12];
int a;
clrscr( );
printf(“Enter filename”);
gets(file);
fp = fopen(file, “wb”); //opening a file for writing

if(fp = = NULL) //error trapping


{printf(“Error creating file”);
exit(1);
}

for(a = 0; a < 3; a++) //input record having 3 members


{
printf(“Enter name:”);
scanf(“ “);
scanf(“%s”, &myfriend.name);
printf(“Enter age:”);
scanf(“%d”, &myfriend.age);
printf(“Enter wage:”);
scanf(“%f”, &myfriend.wage);

fwrite(&myfriend, sizeof(struct record),1,fp); //writing the values to a file


}
fclose(fp) //closing the file
getch( );
}
Sample 11
OPENING A BINARY FILE

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<process.h>

struct record //structure definition


{
char name[50];
int age;
float wage;
};

87
void main( ) //begin main program
FILE *fp; //file declaration

struct record myfriend; //structure declaration


char file[12];
int a;
clrscr( );
printf(“Enter filename”);
gets(file);
fp = fopen(file, “rb”); //opening a file for reading only
if(fp = = NULL) //error trapping
{printf(“Error opening file”);
exit(1);
}
printf(“All records\n”);

while(fread(&myfriend, sizefo(struct record)1,fp) ! = NULL)


//reading a file
printf(“\n%s %d %f”, myfriend.name, myfriend.age, myfriend.wage);
//display values

fclose(fp) //closing the file


getch( );
}

Sample 12
EDIT A BINARY FILE CONTENTS
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<process.h>
#include<ctype.h>

struct record //structure definition


{
char name[50];
int age;
float wage;
};

void main( ) //begin main program


FILE *fp, *tp; //file declaration

char key;

88
struct record myfriend; //structure declaration
char file[12];
int a;
clrscr( );
printf(“Enter filename”);
gets(file);
if(fp = fopen(file, “rb”)==0) //opening a file for reading only
{printf(“Error”);
exit(1);
}

if(fp = fopen(“temp.dat”, “wb”)==0) //opening a file for reading only


{printf(“Error”);
exit(1);
}
while(fread(&myfriend, sizeof(struct record)1,fp) ! = NULL)
//reading a file
{printf(“name: %s\nage: %d\n wage: %.2f”, myfriend.name, myfriend.age,
myfriend.wage); //display values
printf(“edit(y/n)”);
key=toupper(getch( ));
if(key = = ‘Y’)
{
printf(“Re-enter name:”);
scanf(“%s”, &myfriend.name);
printf(“Re-enter age:”);
scanf(“%d”, &myfriend.age);
printf(“Re-enter wage:”);
scanf(“%f”, &myfriend.wage);
}
fwrite(&myfriend, sizeof(struct record),1,fp);
}
fclose(fp) //closing the file
fclose(tp);
remove(file);
rename(“temp.dat”,file);

if(fp = fopen(file, “rb”)==0) //opening a file for reading only


{printf(“Error”);
exit(1);
}
clrscr( );
printf(“\nNew fle\n\n”);
while(fread(&myfriend, sizeof(struct record)1,fp) ! = NULL)
printf(“name: %s\nage: %d\n wage: %.2f”,myfriend.name,
myfriend.age,myfriend.wage);
fclose(fp);
getch( );
}

89
TEXT MODE vs FILE MODE

We have discussed how to declare, open and close a file. The functions we have
used in the 3 activities stated is applicable to both binary and text mode file processing,
what differs are the way the data are written to, and read values from the file with regards
to the file modes.

In binary mode file processing we have used fwrite( ) and fread( )functions, but in
text mode file processing we have used fprintf( ) and fscanf( ) functions.

90
Watch:

https://www.youtube.com/watch?v=wVDfRzBp8iE

Read:

• Programming Logic and Design, 8 th ed/ 3rd edition, Joyce Farrel,2015

• https://www.programiz.com/c-programming/c-file-input-output

Review:

1. What is stream?
2. What are the two modes of file processing?
3. Discuss briefly the following modes, in fopen( ) function.
a. “w”
b. “r”
c. “a”
4. What are the default file mode processing of fopen( ) function modes? Text or
Binary?
5. How can we make the file mode processing of fopen( ) function to text mode?
Explain.

Activities/Assessment: Unit 5 - Linear Linked List

1. Declare a file pointer name FILE1.

2. Create a binary file using file pointer FILE1 as you have declared in the previous
number, let us call the file SAMPLE1.DAT.

3. Assuming CYBER is an array of character with value “BARKADA”, store the value
of CYBER to SAMPLE1.DAT using file pointer FILE1.

4. This time open a binary file SAMPLE1. DAT in read mode using the same file
pointer name that we are using since problem #4 of this exercise.

91
5. Read the value stored to file pointer name FILE1 and assign it to variable CYBER.

6. Display the value assigned to variable CYBER to the console unit.

7. Close FILE1.

Programming:

1. Write a program that will simulate the opening of account in a bank. You are to
create first a structure with 3 members – an array of character with 5 elements (for
the account number), another array of character with 4 elements for the PIN or
Personal Identification Number, a float for the balance.
Input 3 unique records of the structure members previously declared and store it
to a text file with name “accounts.dat”.

2. Write a program that will simulate the Automated Teller Machine.

The first screen will have the following:

Enter account number: 12345


Enter PIN: 1997

The program will ask the user to input an account number with 5 digit number, the
program will then searches the account number input from the “account.dat” file, if the
account number exists, then the system will ask the user to enter his PIN. The program
from this point will search the “account.dat” file for the PIN recently input, if the PIN
entered tallies with the account number previously input the next screen will be
something like below:

Welcome to PUP-On-Line Banking Systems

1. Balance Inquiry
2. Deposit
3. Withdraw

Press the number of your choice:

92
If 1 is chosen, the previous balance from the file will be displayed, based on the tallied
account number & PIN entered. The same process goes with the deposit selection,
where the user will be asked on how much is he depositing. The value entered will be
appended to the existing balance of the user, and will be stored back to the file. The
same process if the elected option is to withdraw, the program will ask the user on how
much is to be withdrawn. The value entered will be verified if it will exceed the balance.

93
94

You might also like