Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Unit 4

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 34

LOGIC BUILDING

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.

Prepared by : Ms. Aditi Mehta 3


WHAT IS ARRAY ?
An array is defined as the collection of similar type of data items stored at contiguous memory locations.
Arrays are the derived data type in C programming language which can store the primitive type of data
such as int, char, double, float, etc. It also has the capability to store the collection of derived data types,
such as pointers, structure, etc. The array is the simplest data structure where each data element can be
randomly accessed by using its index number.
C array is beneficial if you have to store similar elements. For example, if we want to store the marks of a
student in 6 subjects, then we don't need to define different variables for the marks in the different subject.
Instead of that, we can define an array which can store the marks in each subject at the contiguous memory
locations.
By using the array, we can access the elements easily. Only a few lines of code are required to access the
elements of the array.
-----------OR--------
An array is collection of items stored at contiguous memory locations. The idea is to store multiple items of
same type together. Instead of declaring individual variables, such as number0, number1, ..., and number99,
you declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to
represent individual variables. A specific element in an array is accessed by an index.

Prepared by : Ms. Aditi Mehta 4


Properties of array :

• 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 :

1) Code Optimization: Less code to the access the data.

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

Prepared by : Ms. Aditi Mehta 5


Disadvantages of 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.

Prepared by : Ms. Aditi Mehta 6


MEMORY REPRESENTATION

Prepared by : Ms. Aditi Mehta 7


Declaration of Array :
data_type array_name[array_size];
int marks[5];
Here, int is the data_type, marks are the array_name, and 5 is the array_size.

Access Array Elements :


You can access elements of an array by indices.
Suppose you declared an array mark as below. The first element is mark[0], the second element is mark[1] and so
on.
float mark[5];
Few keynotes:
Arrays have 0 as the first index, not 1. In this example, mark[0] is the first element.
If the size of an array is n, to access the last element, the n-1 index is used.
In this example, mark[4] Suppose the starting address of mark[0] is 2120. Then, the address of the mark[1] will be
2124. Similarly, the address of mark[2] will be 2128 and so on. This is because the size of a float is 4 bytes.(16 bit).

Prepared by : Ms. Aditi Mehta 8


Initialization of 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;

Prepared by : Ms. Aditi Mehta 9


Array: Declaration with Initialization

We can initialize the c array at the time of declaration.

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

Input and Output Array Elements

Here's how you can take input from the user and store it in an array element.

// take input and store it in the 3rd element

scanf("%d", &mark[2]);

// take input and store it in the ith element

scanf("%d", &mark[i-1]);

Prepared by : Ms. Aditi Mehta 10


Prepared by : Ms. Aditi Mehta 11
TWO DIMENSIONAL ARRAY
The two-dimensional array can be defined as an array of arrays. The 2D array is
organized as matrices which can be represented as the collection of rows and
columns. However, 2D arrays are created to implement a relational database lookalike
data structure. It provides ease of holding the bulk of data at once which can be passed
to any number of functions wherever required.
Declaration of two dimensional Array
The syntax to declare the 2D array is given below.
data_type array_name[rows][columns];
Consider the following example.
int twodimen[4][3];
Here, 4 is the number of rows, and 3 is the number of columns.
Prepared by : Ms. Aditi Mehta 12
Initialization of 2D Array

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

Prepared by : Ms. Aditi Mehta 13


MEMORY REPRESENTATION IN 2D ARRAY
A 2D array’s elements are stored in contiguous memory locations. It can be represented in memory using
any of the following two ways:

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.

Prepared by : Ms. Aditi Mehta 14


In C programming, you can create an array of arrays. These arrays are known as multidimensional arrays.
For example,

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.

Similarly, you can declare a three-dimensional (3d) array. For example,

1. float y[2][4][3];

Prepared by : Ms. Aditi Mehta 15


Traversing an Array

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:

FOR i = 0 to array length - 1

Display value of 1 element of arry

FOR each element in the array

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.

Prepared by : Ms. Aditi Mehta 16


Summing the Array

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

FOR each element in the array

ADD element to Sum

ENDFOR

PRINT Sum

Here is another version of the same code:

INITIALIZE Sum to 0

FOR i = 0 to array length - 1

ADD array[i] to Sum

ENDFOR

WRITE Sum

Prepared by : Ms. Aditi Mehta 17


Find Maximum Value in the Array

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:

SET Max to array[0]

FOR i = 1 to array length - 1

IF array[i] > Max THEN

SET Max to array[i]

ENDIF

ENDFOR

PRINT Max

Prepared by : Ms. Aditi Mehta 18


Sequential Search for an Element in the Array

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:

FOR i = 0 to array length - 1

IF X = array[i] THEN

RETURN i

ENDIF

ENDFOR

RETURN -1

RETURN Count

Prepared by : Ms. Aditi Mehta 19


Another variation of this problem is to return the number of occurrences of X in the array. Here is a
modification of the above code:

SET Count to 0

FOR i = 0 to array length - 1

IF X = array[i] THEN

INCREMENT Count

ENDIF

ENDFOR

Prepared by : Ms. Aditi Mehta 20


WHAT ARE FILES ?
A file represents a sequence of bytes on the disk where a group of related data is stored. File is created for permanent
storage of data. It is a readymade structure.

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.

Why files are needed?

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.

Prepared by : Ms. Aditi Mehta 21


The need for file handling in C is because - 
1. It saves time as we can easily access any part/outcome of the code whenever required.

2. It helps in preserving the data or information for reusability.

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

Prepared by : Ms. Aditi Mehta 22


1. Text 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

Binary files are mostly the .bin files in your computer.

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.

Prepared by : Ms. Aditi Mehta 23


RANDOM AND SEQUENTIAL ACCESS 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.

Prepared by : Ms. Aditi Mehta 24


Typical operations on files:

1. Open

2. Read

3. Write

4. Close

 Creation of the new file

 Opening an existing file

 Reading from the file

 Writing to the file

 Deleting the file

How file is stored?

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.

Prepared by : Ms. Aditi Mehta 27


In append mode, we can write data into an existing file without deletion of existing contents whereas in
write mode existing data is deleted which was already present in the file.

The fclose() function is used to close an already opened file.

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.

rewind(): It moves the control to beginning of the file.

Prepared by : Ms. Aditi Mehta 28


Declaration of File Pointer
A pointer variable is used to points a structure FILE. The members of the FILE structure are used by the
program in various file access operation, but programmers do not need to concerned about them.

FILE *file_pointer_name;

Eg : FILE *fp;

Creating a new file


We use the fopen() function to create a new file as well as open an existing file in our storage.

The syntax of fopen()- fopen("filename","mode")

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.

Prepared by : Ms. Aditi Mehta 29


#include <stdio.h>

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.

Prepared by : Ms. Aditi Mehta 30


Opening an existing file
To open an existing file we use fopen() with the required opening modes . We have already created a file
using write mode. In the following code, use r mode that is open the file in read mode.

#include <stdio.h>

int main()

FILE * file;

file = fopen("file2.txt","r");

Prepared by : Ms. Aditi Mehta 31


Writing data to a file
Let's write in the file that we created in the previous example. So to do that we willbe using fprintf() to
write a text in the file with the name file2.txt.

#include <stdio.h>

int main()

FILE *file;

file = fopen("file2.txt", "w");

fprintf(file, "Hello! Welcome \n");

Prepared by : Ms. Aditi Mehta 32


Reading Data From an Existing File
To read data from an existing file we will use “r” mode in file opening. To read the file character by
character we use getc() and to read line by line we use fgets().
#include <stdio.h>

#include <stdlib.h>

int main()

FILE *fp;

char s;

fp=fopen("file2.txt","r");

if(fp==NULL)

printf("\CANNOT OPEN FILE");

Prepared by : Ms. Aditi Mehta 33


exit(1);

do

s=getc(fp); // read file character by character

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.

Prepared by : Ms. Aditi Mehta 34

You might also like