Unit 4
Unit 4
Unit 4
TECHNIQUES
Unit 4 : Advanced
Variable Types &
Working with Files
• Advanced Variable Types : Arrays, Arrays and variables, Pseudo code for
common array operations, Single dimensional array, Multi-dimensional array,
searching an array, understanding array bounds, using loop to process array.
• Working with Files : Basics of computer files, working on different file
operations (read, write & append), understanding of access of files: sequential
access & random access.
• Each element of an array is of same data type and carries the same size, i.e., int = 4 bytes.
• Elements of the array are stored at contiguous memory locations where the first element is stored at the
smallest memory location.
• Elements of the array can be randomly accessed since we can calculate the address of each element of
the array with the given base address and the size of the data element.
Advantages of Array :
2) Ease of traversing: By using the for loop, we can retrieve the elements of an array easily.
3) Ease of sorting: To sort the elements of the array, we need a few lines of code only.
4) Random Access: We can access any element randomly using the array
1) Fixed Size: Whatever size, we define at the time of declaration of the array, we can't exceed the limit.
So, it doesn't grow the size dynamically like LinkedList which we will learn later.
All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and
the highest address to the last element.
An array is a series or list of variables in computer memory, all of which have the same name but are
differentiated with special numbers called subscripts. A subscript is a number that indicates the
position of a particular item within an array. Whenever you require multiple storage locations for
objects, you are using a real-life counterpart of a programming array. For example, if you store important
papers in a series of file folders and label each folder with a consecutive letter of the alphabet, then you are
using the equivalent of an array.
The simplest way to initialize an array is by using the index of each element. We can initialize each element
of the array by using the index. Consider the following example.
int marks[5];
marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;
int marks[5]={20,30,40,50,60};
In such case, there is no requirement to define the size. So it may also be written as the following code.
int marks[]={20,30,40,50,60};
Here's how you can take input from the user and store it in an array element.
scanf("%d", &mark[2]);
scanf("%d", &mark[i-1]);
In the 1D array, we don't need to specify the size of the array if the declaration and initialization are being
done simultaneously. However, this will not work with 2D arrays. We will have to define at least the second
dimension of the array. The two_x0002_dimensional array can be declared and defined in the following
way.
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
1. Column-Major Order : In this method the elements are stored column wise, i.e. m elements of first
column are stored in first m locations, m elements of second column are stored in next m locations and so
on.
2. Row-Major Order : In this method the elements are stored row wise, i.e. n elements of first row are
stored in first n locations, n elements of second row are stored in next n locations and so on.
1. float x[3][4];
Here, x is a two-dimensional (2d) array. The array can hold 12 elements. You can think the array as a table
with 3 rows and each row has 4 columns.
1. float y[2][4][3];
Our basic operation starts with visiting each element of the array exactly once and in order. We can write
that in pseudocode in two ways:
In the first example we are going by position starting at the first position 0 and going to the last position. In
the second example we are going element by element.
In any summing problem, we need a place or variable to store the sum. We have to initialize this variable to
zero to start with and then traverse the array adding each element to the sum. Here is the pseudocode:
SET Sum to 0
ENDFOR
PRINT Sum
INITIALIZE Sum to 0
ENDFOR
WRITE Sum
To find the maximum value, you initialize a placeholder called max with the value of the first element in
the array. Then you go through the array element by element. If any element is greater than max you
replace max with that element. Here is the pseudocode:
ENDIF
ENDFOR
PRINT Max
Let the element that we are searching for be X. We need to know if that element occurs in the array. One
way is to return the position of the first occurrence of that element and if that element does not exist return -
1 which is an invalid index. This is the pseudocode:
IF X = array[i] THEN
RETURN i
ENDIF
ENDFOR
RETURN -1
RETURN Count
SET Count to 0
IF X = array[i] THEN
INCREMENT Count
ENDIF
ENDFOR
A File is a collection of data stored in the secondary memory. So far data was entered into the programs through the
keyboard. So Files are used for storing information that can be processed by the programs. Files are not only used for
storing the data, programs are also stored in files. In order to use files, we have to learn file input and output operations.
That is, how data is read and how to write into a file.
1. When a program is terminated, the entire data is lost. Storing in a file will preserve your data even if the program
terminates.
2. If you have to enter a large number of data, it will take a lot of time to enter them all. However, if you have a file
containing all the data, you can easily access the contents of the file using a few commands in C.
3. You can easily move your data from one computer to another without any changes.
3. There is no need to worry about storage. And without loss of data, we can easily transfer the contents of a file.
filename is the name of the file to be opened and mode specifies the purpose of opening the file.
Types of Files
When dealing with files, there are two types of files you should know about:
1. Text files
2. Binary files
Text files are the normal .txt files. You can easily create text files using any simple text editors such as Notepad.When
you open those files, you'll see all the contents within the file as plain text. You can easily edit or delete the contents.They
take minimum effort to maintain, are easily readable, and provide the least security and takes bigger storage space.
User can create these types of files easily while dealing with file handling in C. It stores information in the form of ASCII
characters internally and when the file is opened, the content is readable by humans. It can be created by any text editor
with a .txt or .rtf (rich text) extension. Since text files are simple, they can be edited by any text editor like Microsoft
Word, Notepad, Apple Textedit etc.
2. Binary files
Instead of storing data in plain text, they store it in the binary form (0's and 1's).
They can hold a higher amount of data, are not readable easily, and provides better security than text files.
A random-access data file enables you to read or write information anywhere in the file. In a sequential-
access file, you can only read and write information sequentially, starting from the beginning of the file.If
you are always accessing information in the same order, a sequential-access file is faster. If you tend to
access information randomly, random access is better.As a quick example, modern computer hard disks are
using Random Access whereas Tape Storage devices (used for offline backups) use Sequential Access.
1. Open
2. Read
3. Write
4. Close
Stored as sequence of bytes, logically contiguous (may not be physically contiguous on disk). The last byte of a file
contains the end-of-file character (EOF), with ASCII code 1A (hex).While reading a text file, the EOF character can be
checked to know the end.
Prepared by : Ms. Aditi Mehta 25
Prepared by : Ms. Aditi Mehta 26
MODES TO OPEN FILE IN C
To open a file we use fopen() with different opening modes. The most common modes used are listed
below.
Here fclose() function closes the file and returns zero on success, or EOF if there is an error in closing the
file. This EOF is a constant defined in the header file stdio.h.
fseek(): It is used to move the reading control to different positions using fseek function.
ftell(): It tells the byte location of current position of cursor in file pointer.
FILE *file_pointer_name;
Eg : FILE *fp;
When declaring a file in C, the pointer of the file type (FILE) is used to point the file. fopen() will give the
address of the file to the file pointer which is going to create/open.
int main()
FILE * file;
file = fopen("file2.txt","w");
A new file will be created in the folder where your code is saved. You can also specify the path where you
want your file to be created. file = fopen ("C://file2.txt", "w");
We use write mode because it will create a new file if the file is not present.
#include <stdio.h>
int main()
FILE * file;
file = fopen("file2.txt","r");
#include <stdio.h>
int main()
FILE *file;
#include <stdlib.h>
int main()
FILE *fp;
char s;
fp=fopen("file2.txt","r");
if(fp==NULL)
do
printf("%c",s);
while(s!=EOF);
fclose(fp);
return 0;
In the above program, getc() will read the file character by character until the end of the file(EOF) does not occur.