UNIT -1 Algorithm Analysis & File Handling
UNIT -1 Algorithm Analysis & File Handling
Subject Code : CS – 08
Subject Name : Data Structure Using
C Language
Unit-1
Algorithm Analysis & File Handling
Data Structure: A data structure is a particular way of organizing data in a computer so that it can
be used efficiently.
Introduction to Algorithm
To work with a computer, we have to use a computer program.
What is Algorithm?
An algorithm is just a detailed sequence of simple steps that are needed
to solve a problem.
Analysis of Algorithm
In computer science, the analysis of algorithms is the determination of the number of resources
necessary to execute them.
Most algorithms are designed to work with inputs of undefined
length.
Algorithm analysis is an important part of a wide computational complexity theory which provides
theoretical estimates for the resources needed by any algorithm which solves a given
computational problem.
1. TIME Complexity
A program executes number of instructions during the execution time is called as its Time
Complexity.
Instead of measuring actual time required in executing each statement in the code, Time
Complexity considers how many times each statement executes.
The time complexity of an algorithm is commonly expressed using big O notation, which
excludes coefficients and lower order terms.
For Example: Operations, Comparisons, Loop, Function calls to outside.
Time Complexity Chart:
2 O(log n) Logarithmic
4 O(n^2) Quadratic
5 O(n^3) Cubic
2. Space Complexity
Space Complexity of an algorithm is total space taken by the algorithm with respect to the input
size.
Space complexity includes both Auxiliary space and space used by input.
For Example: Variables, Allocations, Function call
Space Complexity = Auxiliary Space + Space used for input values
Auxiliary space is nothing but the space required by an algorithm/problem during the execution of
that algorithm/problem.
Type 1: A Fixed part:
It is independent of the input size. It includes memory for instructions (code), constants, variables,
etc.
Type 2: A Variable part:
It is dependent on the input size. It includes memory for recursion stack, referenced variables, etc.
For Example: dynamic memory allocation, recursion stack space, etc.
Example: 1
int main()
{
int a = 10;
float b = 20.5;
char c = 'A';
int d[10];
return 0;
}
To calculate the complexity of this algorithm, we need to determine the amount of memory used
by each of the variables. In this case:
a is an integer, which takes up 4 bytes of memory.
b is a float, which takes up 4 bytes of memory.
c is a character, which takes up 1 byte of memory.
d is an array of 10 integers, which takes up 40 bytes of memory (10 x 4).
So, the total amount of memory used by this algorithm is 4 + 4 + 1 + 40 = 49 bytes.
Example: 2
Example 1: Addition of Numbers
{
int a = x + y + z;
return (a);
}
So in the above example, there are 4 integer variables those are a, x, y, z so they will take 4
bytes(as given in the table above) space for each variable, and extra 4 ‐byte space will also be
added to the total space complexity for the return value that is a.
Hence, the total space complexity = 4*4 + 4 = 20 bytes
Asymptotic Notations:
Asymptotic notations are mathematical tools to represent time complexity of algorithms for
asymptotic analysis.
We use three types of asymptotic notations to represent the growth of any algorithm, as input
increases:
1. Big Oh(O)
2. Big Omega (Ω)
3. Big Theta (Θ)
1. Big Oh(O)
The Big O notation defines an upper bound of an algorithm’s running time.
It measures the worst case time complexity or the longest amount of time possibly taken
by the algorithm to complete.
The running time complexity is always specified in the so called O‐notation.
The O is the formal method of expressing the upper bound of an algorithm’s running time.
Worst case Time Complexity Example:
If we want to search the element which is present at the last of the list or not present at all
in the list then such cases are called the worst case efficiency.
let we have to find 105 in List =>25,31,42,71,105
Therefore, we have to make 5 (=n) comparisons to search the element
Cworst (n)=n
Now if we have to find 110
Since the element is not in the list even then we have to make 5 (=n) comparisons to
search the element
Cworst (n)=n
Classes/Classification of algorithm
1. Array: An array is a collection of items of the same variable type that are stored at contiguous
memory locations. It’s one of the most popular and simple data structures and is often used
to implement other data structures. Each item in an array is indexed starting with 0.
2. Searching Algorithms: These algorithms are designed to find a particular element or set of
elements within a data structure.
Examples include Linear Search, Binary Search, Depth‐First Search (DFS), and Breadth‐First
Search (BFS).
3. Sorting Algorithms: Sorting algorithms arrange the elements of a data structure in a specific
order. Common sorting algorithms include Bubble Sort, Insertion Sort, Selection Sort, Merge
Sort, Quick Sort, and Heap Sort.
4. Traversal Algorithms: These algorithms visit and process all the nodes or elements of a data
structure in a specific order without searching for any particular element.
Examples include Pre‐order, In‐order, Post‐order, and Level‐order traversal for trees.
5. Graph Algorithms: Graph algorithms which are collections of nodes (vertices) and edges
connecting these nodes.
Examples include DFS, BFS, Dijkstra's algorithm for shortest paths, Kruskal's algorithm for
minimum spanning trees, and Prim's algorithm.
6. Greedy Algorithms: Greedy algorithms make locally optimal choices at each step with the
hope of finding a global optimum.
Examples include Prim's algorithm and Kruskal's algorithm for minimum spanning trees, and
Dijkstra's algorithm for shortest paths.
7. Divide and Conquer Algorithms: These algorithms solve a problem by dividing it into smaller
subproblems, conquering the subproblems recursively, and combining their solutions to solve
the original problem.
Examples include Merge Sort and Quick Sort.
8. Linked List:
9. Stack:
10. Queue:
11. Tree:
File Handling
What is Data Files?
A file structure is a combination of representations for data in files. It is also a collection of
operations for accessing the data. It enables applications to read, write, and modify data.
The C language stores all the data available in a program into a file with the help of file handling in
C.
A file can be classified into two types based on the way the file stores the data.
1. Text Files
A text file contains data in the form of ASCII characters and is generally used to store a stream of
characters.
Each line in a text file ends with a new line character (‘\n’).
It can be read or written by any text editor.
They are generally stored with .txt file extension.
Text files can also be used to store the source code.
2. Binary Files
A binary file contains data in binary form (i.e. 0’s and 1’s) instead of ASCII characters. They
contain data that is stored in a similar manner to how it is stored in the main memory.
The binary files can be created only from within a program and their contents can only be read
by a program.
More secure as they are not easily readable.
They are generally stored with .bin file extension.
File Modes
Syntax:
FILE *Pointer_Variable_name;
Pointer_variable_name = fopen("filename.txt","mode");
2. fclose()
fclose() function is a C library function that releases the memory stream opened by the fopen()
function.
Syntax: fclose(Pointer_VariableName);
#include <stdio.h>
//#include <stdlib.h> if required
#include <conio.h>
void main()
{
// file pointer
FILE* fptr;
clrscr();
// creating file using fopen() access mode "w"
fptr = fopen("file.txt", "w");
3. fprintf()
C fprintf() function passes arguments according to the specified format to the file indicated by the
stream.
This function is implemented in file‐related programs for writing formatted data in any file.
Syntax: fprintf(pointer_variablename,%format,data);
#include<stdio.h>
#include<conio.h>
void main ()
{
FILE *fptr;
clrscr();
fptr = fopen("Z:\\DS\\DS Practical\\Text_File\\file1.txt","w");
fprintf(fptr, "%s %s %d", "Welcome", "to", 2024);
if (fptr == NULL)
{
printf("The file is not opened. The program will exit now");
}
else
{
printf("Data is print Successfully.");
}
fclose(fptr);
getch();
}
Output:
4. fscanf()
fscanf() reads data from the file sequentially, converting it according to the format specifier, and
storing the results in the specified variables.
Syntax:
This format string contains conversion specifiers (like %d, %f, %s, etc.) that indicate the type and
format of the data to be read.
The %s specifier reads a string of characters terminated by whitespace (space, tab, or newline).
The %d format specifier expects an address (pointer) to an integer variable. By using &age, you
are passing the address of the age variable, allowing fscanf() to store the integer value it reads
from the file directly into the memory location associated with the age variable.
#include <stdio.h>
#include <conio.h>
// Driver Code
void main()
{
char str1[50], str2[50], str3[50], str4[50];
clrscr();
FILE *fptr;
fptr= fopen("Z:\\DS\\DS Practical\\Text_File\\file2.txt", "r");
Output:
#include <stdio.h>
#include <conio.h>
// Driver Code
void main()
{
FILE *file;
char name[50];
int age;
clrscr();
// Open the file
file = fopen("Z:\\DS\\DS Practical\\Text_File\\data.txt", "r");
5. getw()
The getw() function reads an integer from a file using fscanf() and returns it.
Syntax:
6. putw()
The putw() function writes an integer to a file using fprintf().
Syntax:
#include <stdio.h>
#include <conio.h>
// Writing to file
fptr = fopen("Z:\\DS\\DS Practical\\Text_File\\number.txt", "w");
putw(number_written, fptr);
fclose(fptr);
number_read = getw(fptr);
getch();
}
Output:
7. fseek()
fseek() is a function in C used to move the file pointer associated with a given file stream to a
specified location.
It allows you to reposition the file pointer within a file, facilitating random access to different parts
of the file.
Offset: The number of bytes you want to move the file pointer. It can be positive or negative.
Whence: Specifies the reference point for the offset. It can take one of the following values:
Example:
#include <stdio.h>
#include <conio.h>
void main()
{
FILE *fptr;
clrscr();
fptr = fopen("Z:\\DS\\DS Practical\\Text_File\\file2.txt", "r");
if (fptr == NULL)
{
printf("Error opening the file.\n");
}
// Move the file pointer 10 bytes from the beginning of the file (Start with 0 index)
fseek(fptr, 10, SEEK_SET);
fclose(fptr);
getch();
}
Output:
8. ftell()
ftell() is a function in C used to determine the current position of the file pointer within a file
associated with a given file stream. It returns the current file position indicator for the stream.
#include <stdio.h>
#include <conio.h>
void main()
{
FILE *fptr;
char ch;
long fileSize;
clrscr();
// Read and print characters from the middle to the end of the file
while ((ch = fgetc(fptr)) != EOF)
{
printf("%c", ch);
}
// Move the file pointer 10 bytes backward from the current position
fseek(fptr, ‐10, SEEK_CUR);
printf("\n\nLast 10 characters:\n");
// Read and print the last 10 characters of the file
while ((ch = fgetc(fptr)) != EOF)
{
printf("%c", ch);
}
9. rewind()
The rewind() function sets the file pointer at the beginning of the stream. It is useful if you have to
use stream many times.
rewind(FILE *Pointer_VariableName);
Example:
#include <stdio.h>
#include <conio.h>
void main()
{
FILE *fptr;
char c;
clrscr();
fptr=fopen("Z:\\DS\\DS Practical\\Text_File\\file2.txt","r");
while((c=fgetc(fptr))!=EOF)
{
printf("%c",c);
}
while((c=fgetc(fptr))!=EOF)
{
printf("%c",c);
}
fclose(fptr);
getch();
}
Output:
10. freopen()
freopen() is a function in C that is used to associate a new file with the specified stream, effectively
redirecting input and output. This function is useful when you want to change the file associated
with an existing stream (like stdin, stdout, or stderr) during runtime.
Syntax:
Example of stdout:
#include <stdio.h>
#include <conio.h>
void main()
{
// Output will be redirected to "output.txt"
freopen("Z:\\DS\\DS Practical\\Text_File\\output.txt", "w", stdout);
clrscr();
getch();
}
Output:
Example of stdin:
#include <stdio.h>
#include <conio.h>
void main()
{
freopen("Z:\\DS\\DS Practical\\Text_File\\output.txt", "r", stdin);
clrscr();
char data[50];
// Read integers from the file and print them
while (scanf("%s", data) == 1)
{
printf("%s",data);
}
Output:
11. remove()
Example:
#include <stdio.h>
#include <conio.h>
void main()
{
char filename[] = "Z:\\DS\\DS Practical\\Text_File\\data.txt";
clrscr();
if (remove(filename) == 0)
{
printf("%s file deleted successfully.\n", filename);
}
else
{
perror("Error deleting file");
}
getch();
}
This code snippet attempts to delete a file named "data.txt" in the current directory.
If successful, it prints a success message; otherwise, it prints an error message using perror().
12. rename()
This code snippet renames a file named "old_filename.txt" to "new_filename.txt".
If successful, it prints a success message; otherwise, it prints an error message using perror().
Example:
#include <stdio.h>
#include <conio.h>
void main()
{
char old_name[] = "Z:\\DS\\DS Practical\\Text_File\\example1.txt";
char new_name[] = "Z:\\DS\\DS Practical\\Text_File\\example.txt";
clrscr();
if (rename(old_name, new_name) == 0)
{
printf("File renamed successfully.\n");
}
else
{
perror("Error renaming file");
}
getch();
}
13. feof()
feof() is a function used to check if the end‐of‐file indicator has been set for a stream.
Example:
#include <stdio.h>
#include <conio.h>
void main()
{
FILE *fptr;
char character;
Output:
I/O Operations
To handle files in C, file input/output functions available in the stdio library are:
Solve Practical Example for File Handling:
Write a program for writing data into student.txt file.
Input:
Om VVIM College
20
20.5
Output:
argc stands for "argument count" and indicates the number of command ‐line arguments passed to
the program, including the name of the program itself.
argv stands for "argument vector" and is an array of strings (char*), where each element
represents one command‐line argument. argv[0] is always the name of the program itself.
Example:
#include <stdio.h>
#include <conio.h>
int main(int argc, char *argv[]) //argv represent 2D Array. * indicate array size not fix.
{
int i;
clrscr();
// argc is the number of arguments passed
printf("Number of arguments: %d\n", argc);//argc represent count number of argument
getch();
return 0;
}
Steps for run Command Line Argument Program:
Go to Options Menu ‐> Click on Environment ‐> Give Argument of any data type.
Output: