PPS Unit 3,4 ,&5 by BMK 9652707440
PPS Unit 3,4 ,&5 by BMK 9652707440
PPS Unit 3,4 ,&5 by BMK 9652707440
D) 9652707440
File Operations
In C, you can perform four major operations on the file, either text or binary:
Creating a newfile
Opening an existingfile
Closing afile
Reading from and writing information to a file
Let's suppose the file newprogram.txt doesn't exist in the location E:\cprogram. The first function creates a
new file named newprogram.txt and opens it for writing as per the mode 'w'. The writing mode allows
you to create and edit (overwrite) the contents of thefile.
Now let's suppose the second binary file oldprogram.bin exists in the location E:\cprogram. The second
function opens the existing file for reading in binary mode'rb'. The reading mode only allows you to read
the file, you cannot write into thefile.
Sr.No. Mode & Description
1 "r"
Opens a file for reading. The file must exist.
2 “W”Creates an empty file for writing. If a file with the same name
already exists, its content is erased and the file is considered
as a new empty file.
3 "a"
Appends to a file. Writing operations, append data at the end of
the file. The file is created if it does not exist.
4 "r+"
Opens a file to update both reading and writing. The filemust
exist.
5 "w+"
Creates an empty file for both reading and writing.
6 "a+"
Opens a file for reading and appending.
Closing a file:
The file (both text and binary) should be closed after reading/writing. Closing a file is performedusing
For reading and writing to a text file, we use the functions fprintf() and fscanf().
They are just the file versions of printf() and scanf(). The only difference is that, fprint and fscanfexpects a
pointer to the structure FILE.
#include <stdio.h>
int main()
{
int num; FILE *fp;
fptr = fopen("C:\\program.txt","w"); if(fp == NULL)
{
printf("Error!");exit(1);
}
printf("Enter num: ");scanf("%d",&num);
fprintf(fp,"%d",num);fclose(fp);
return 0;
}
This program takes a number from user and stores in the file program.txt.
File Types
A file represents a sequence of bytes on the disk where a group of related data is stored. File iscreated for
permanent storage of data. It is a readymade structure.
FILE *fp;
C provides a number of functions that helps to perform basic file operations. Following are thefunctions,
Function
fopen()
fclose()
getc()
putc()
fscanf()
fprintf()
getw()
putw()
fseek()
ftell()
rewind()
General Syntax :
Here filename is the name of the file to be opened and mode specifies the purpose of opening the file.
Mode can be of following types,
*fp is the FILE pointer (FILE *fp), which will hold the reference to the opened (or created) file.
Closing a File
Here fclose() function closes the file and returns zero on success, or EOF if there is an errorin closing the file.
This EOF is a constant defined in the header file stdio.h.
In the above table we have discussed about various file I/O functions to perform reading and writing on file.
getc()and putc()are simplest functions used to read and write individual characters to afile.
#include<stdio.h>#include<conio.h> main()
RE{
FILE *fp; char ch;
fp = fopen("one.txt", "w");printf("Enter data");
while( (ch = getchar()) != EOF)
{
putc(ch,fp);
}
fclose(fp);
fp = fopen("one.txt", "r");
PPS BY BMK 9652707440D
PPS PART-2 UNIT-3,4,5 By MANIKUMAR ASST PROF(B.TECH,M.TECH,MBA,Ph.D) 9652707440
void main()
{
struct emp e;FILE *p,*q;
p = fopen("one.txt", "a");
q = fopen("one.txt", "r"); printf("Enter Name and Age"); scanf("%s%d", e.name, &e.age);
fprintf(p,"%s %d", e.name, e.age);fclose(p);
do
{
fscanf(q,"%s %d", e.name, e.age);
printf("%s %d", e.name, e.age);
}
while( !feof(q) );getch();
}
In this program, we have create two FILE pointers and both are refering to the same file but in different
modes. fprintf() function directly writes into the file, while fscanf() reads from the file, which can then
be printed on console usinf standard printf() function.
Difference between Append and Write Mode
Write (w) mode and Append (a) mode, while opening a file are almost the same. Both are used to write in a
file. In both the modes, new file is created if it doesn't exists already.
The only difference they have is, when you open a file in the write mode, the file is reset, resulting in
deletion of any data already present in the file. While in append mode this will not happen. Append
mode is used to append or add data to the existing data of file(if any). Hence, when you open a file in
Append(a) mode, the cursor is positioned at the end of the present data in thefile.
A Binary file is similar to the text file, but it contains only large numerical data. The Opening modes are
mentioned in the table for opening modes above.
fread() and fwrite() functions are used to read and write is a binary file.
fread() is also used in the same way, with the same arguments like fwrite() function.
Below mentioned is a simple example of writing into a binary file
const char *mytext = "The quick brown fox jumps over the lazy dog";FILE *bfp= fopen("test.txt", "wb");
if (bfp)
{
fwrite(mytext, sizeof(char), strlen(mytext), bfp) ;fclose(bfp) ;
}
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.
Before storing data onto the secondary storage , firstly we must specify following things – Filename, Data
Structure Perpose / Mode.
Very first task in File handling is to open file File name : Specifies Name ofthe File
First field is name fieldand second field is of extension fieldExtension field is optional
Both File name and extension are separated by period or dot.
Data Structure
Data structure of file is defined as FILE in the library of standard I/O functions In short we haveto declare
the pointer variable of type FILE
File opening modes
In C Programming we can open file in different modes such as reading mode,writing mode andappending
mode depending on purpose of handling file.
Following are the different Opening modes of File :
{
FILE *fp; char ch;
fp = fopen("INPUT.txt","r") // Open file in Read modefclose(fp); // Close File after Reading return(0);
}
If we want to open file in different mode then following syntax will be used – Reading Modefp =
fopen("hello.txt","r");
Writing Mode fp = fopen("hello.txt","w"); Append Mode fp = fopen("hello.txt","a");
Create NewFile
w Writing Over write on Existing
Create NewFile
a Append –
Explanation:
File can be opened in basic 3 modes : Reading Mode, Writing Mode, Appending Mode
If File is not present on the path specified then New File can be created using Write and Append
Mode.Generally we used to open following types of file in C –
C Source File .c
Writing on the file will overwrite previous content EOF and feof function >> stdio.h >> File Handling in C
Syntax :
A ) In Text File :
Special Character EOF denotes the end of File
As soon as Character is read,End of the File can be detected. EOF is defined in stdio.h
Equivalent value of EOF is -1 PrintingValue of EOF :
void main()
{
printf("%d", EOF);
B ) In Binary File :
feof function is used to detect the end of file It can be used in text file feof Returns TRUE if end of file is
reached
Syntax :
int feof(FILE *fp);
Way of Writing feof Function :
with if statement :
PPS BY BMK 9652707440D
PPS PART-2 UNIT-3,4,5 By MANIKUMAR ASST PROF(B.TECH,M.TECH,MBA,Ph.D) 9652707440
fopen():
fclose() :
function is used to close an already opened file. int fclose( FILE *fp);
getc() and putc() are the simplest functions which can be used to read and write individual characters to a
file.
fprintf() function directly writes into the file, while fscanf() reads from the file, which can thenbe printed on
the console using standard printf() function.
Example of Reading and Writing to File using fprintf() and fscanf() functions#include<stdio.h>
struct emp
{
char name[10]; int age;
};
void main()
{
struct emp e; FILE *p,*q; p = fopen("one.txt", "a");
q = fopen("one.txt", "r"); printf("Enter Name and Age:"); scanf("%s %d", e.name, &e.age);
fprintf(p,"%s %d", e.name, e.age);fclose(p);
do
{
fscanf(q,"%s %d", e.name, e.age);
printf("%s %d", e.name, e.age);
} while(!feof(q));
}
fseek()
ftell()
rewind()
PPS BY BMK 9652707440D
PPS PART-2 UNIT-3,4,5 By MANIKUMAR ASST PROF(B.TECH,M.TECH,MBA,Ph.D) 9652707440
fseek()
It is used to set file pointer to any position. Prototype is:int fseek ( FILE * stream, long int offset, int origin );
Parameters
tream: pointer to a file.
Offset: Number of bytes or characters from the origin.
Origin: The original position is set here. From this position, using the offset, the file pointer is setto a new
position. Generally, three positions are used as origin:
Return
Type: Integer
Value: On success Zero (0) On failure Non-Zero
Example
int main()
{
FILE *fp;
fp = fopen ( "file.txt" , "w" );if (fp==NULL)
printf ("Error in opening file");else
{
fputs("I am supporter of France.",fp );fseek (fp , 18 , SEEK_SET );
fputs ("Brazil" , fp ); fseek(fp , 0 , SEEK_CUR );fputs(" and Portugal" , fp ); fclose ( fp );
}
return 0;
}
Then using SEEK_SET and offset, the word France is replaced by Brazil. Then by usingSEEK_CUR, and
position is appended with the string.
ftell()
It is used to get current position of the file pointer. The functionprototype is: long int ftell ( FILE * stream );
Parameters
Value: On success value of current position oroffset bytes On failure -1. System specific error no is set
Example
Code:
int main ()
{
PPS BY BMK 9652707440D
PPS PART-2 UNIT-3,4,5 By MANIKUMAR ASST PROF(B.TECH,M.TECH,MBA,Ph.D) 9652707440
In this example, file.txt is opened and using fseek(), file pointer is set to the end of the file. Then,ftell() is
used to get the current position, i.e. offset from the beginning of the file.
rewind()
Parameters
stream: Pointer to a file.
In any stage of the program, if we need to go back to the starting point of the file, we can use
rewind() and send the file pointer as the parameter.
Example
Code:
int main ()
{
int n; FILE * fp;
fp = fopen ("file.txt","w+"); if(fp==NULL)
printf ("Error in opening file");
else { fputs ("France is my favorite team",fp); rewind (fp);
fputs("Brazil",fp);fclose (fp);
}
return 0;
}
In the above example, first, some string is written in the file. Then rewind() is used to set the file pointer at
the beginning of the file. Then overwrite a word.
Parameters
stream − This is the pointer to a FILE object that identifies thestream.
offset − This is the number of bytes to offset fromwhence.
whence − This is the position from where offset is added. It is specified by one ofthefollowing constants−
Sr.No. Constant & Description
1
SEEK_SET
Beginning of file
2
SEEK_CUR
End of file
Return Value:
Example:
The following example shows the usage of fseek() function.
Let us compile and run the above program that will create a file file.txt with the following content. Initially
program creates the file and writes This is tutorialspoint.com but later we had reset the write pointer at
7th position from the beginning and used puts() statement which over-write the file with the following
content –
#include <stdio.h>
int main ()
{
FILE *fp; int c;
fp = fopen("file.txt","r"); while(1)
{
c = fgetc(fp); if( feof(fp) )
{
break;
PPS BY BMK 9652707440D
PPS PART-2 UNIT-3,4,5 By MANIKUMAR ASST PROF(B.TECH,M.TECH,MBA,Ph.D) 9652707440
}
printf("%c", c);
}
fclose(fp); return(0);
}
Let us compile and run the above program to produce the following result −
It is possible to pass some values from the command line to your C programs when they are executed.
These values are called command line argumentsand many times they are important for your program
especially when you want to control your program from outside instead of hard coding those values
inside thecode.
The command line arguments are handled using main() function arguments where argc refers to the
number of arguments passed, and argv[] is a pointer array which points to each argument passed to
the program. Following is a simple example which checks if there is any argument supplied from the
command line and take action accordingly –
#include <stdio.h>
$./a.out testing
The argument supplied is testing
When the above code is compiled and executed with a two arguments, it produces the following result.
When the above code is compiled and executed without passing any argument, it produces thefollowing
result.
$./a.out
One argument expected
It should be noted that argv[0] holds the name of the program itself and argv[1] is a pointer tothe first
command line argument supplied, and *argv[n] is the last argument. If no arguments are supplied, argc
will be one, and if you pass one argument then argc is set at 2.
You pass all the command line arguments separated by a space, but if argument itself has a space then
you can pass such arguments by putting them inside double quotes "" or single quotes ''. Let us re-
write above example once again where we will print program name and we also pass a command line
argument by putting inside double quotes −
#include <stdio.h>
int main( int argc, char *argv[] )
{
printf("Program name %s\n", argv[0]); if( argc == 2 )
{
printf("The argument supplied is %s\n", argv[1]);
When the above code is compiled and executed with a single argument separated by space but inside
double quotes, it produces the following result.
$./a.out "testing1 testing2"
UNIT-IV
Introduction to functions
A function is a group of statements that together perform a task. Every C program has at least one function,
which is main(), and all the most trivial programs can define additional functions.
You can divide up your code into separate functions. How you divide up your code among different
functions is up to you, but logically the division is such that each function performs a specific task.
A function declaration tells the compiler about a function's name, return type, and parameters. A function
definition provides the actual body of the function.
The C standard library provides numerous built-in functions that your program can call. For example,
strcat() to concatenate two strings, memcpy() to copy one memory location to another location, and
many more functions.
A function can also be referred as a method or a sub-routine or a procedure, etc.
Defining a Function
}
A function definition in C programming consists of a function header and a function body. Here are all the
parts of a function −
Return Type − A function may return a value. The return_type is the data type of the value the function
returns. Some functions perform the desired operations without returning a value. In this case, the
return_type is the keyword void.
Function Name − This is the actual name of the function. The function name and the parameter list
together constitute the function signature.
Parameters − A parameter is like a placeholder. When a function is invoked, you pass a value to the
parameter. This value is referred to as actual parameter or argument. The parameter list refers to the
type, order, and number of the parameters of a function. Parameters are optional; that is, a function
may contain no parameters.
Function Body − The function body contains a collection of statements that define what the function does.
Example
Given below is the source code for a function called max(). This function takes two parameters num1 and
int result;
result = num1;
else
result = num2;
return result;
}
num2 and returns the maximum value between the two −
Function Declarations
A function declaration tells the compiler about a function name and how to call the function. The actual
body of the function can be defined separately.
A function declaration has the following parts −
Function prototype
A function prototype is simply the declaration of a function that specifies function's name, parameters and
return type. It doesn't contain function body.
A function prototype gives information to the compiler that the function may later be used in the program.
In the above example, int add Numbers(int a, int b);is the function prototype which provides following
information to the compiler:
The function prototype is not needed if the user-defined function is defined before the main()function.
Category of functions:
A function depending an whether the arguments are present or not and whether a value isreturned or not,
may belong to one of following categories
In this category, the function has no arguments. It does not receive any data from the calling function.
Similarly, it doesn‟t return any value. The calling function doesn‘t receive any data from the called
function. So, there is no communication between calling and called functions.
In this category, function has some arguments. It receives data from the calling function, but itdoesn‟t
return a value to the calling function. The calling function doesn‘t receive any data from the called
function. So, it is one way data communication between called and calling functions.
Note:
In the main() function, n value is passed to the nat() function. The n value is now stored in theformal
argument n, declared in the function definition and subsequently, the natural numbers up to n are
obtained.
In this category, functions have some arguments and it receives data from the calling function.Similarly, it
returns a value to the calling function. The calling function receives data from thecalled function. So, it
is two-way data communication between calling and called functions.
PPS BY BMK 9652707440D
PPS PART-2 UNIT-3,4,5 By MANIKUMAR ASST PROF(B.TECH,M.TECH,MBA,Ph.D) 9652707440
#include<stdio.h>#include<conio.h>intfact(int); voidmain()
{
int n;
printf("\n Enter n:"); scanf("%d",&n);
printf("\n Factorial of the number : %d", fact(n));
}
int fact(int n)
{
int i,f; for(i=1,f=1;i<=n;i++)f=f*i;
return(f);
}
In this category, the functions have no arguments and it doesn‘t receive any data from the calling function,
but it returns a value to the calling function. The calling function receives data from the called function.
So, it is one way data communication between calling and called functions.
int sum()
{
int a[20], i, s=0,n;
scanf("%d",&n);
printf("\n Enter theelements:");for(i=0;i< n; i++) scanf("%d",&a[i]);
for(i=0;i< n; i++)s=s+a[i];
return s;
}
Downward Communication
Upward Communication
Bi-directional Communication
Downward Communication
In this type of communication, the data is transferred from calling function to called function but not from
called function to calling function. The function with parameters and without return value is considered
under Downward communication.
Example
printf("\nBefore swap: num1 = %d, num2 = %d", num1, num2) ; addition(num1, num2) ; // calling function
getch() ;
}
void addition(int a, int b) // called function
{
printf("SUM = %d", a+b) ;
}
Output SUM=30
Upward Communication
In this type of communication, the data is transferred from called function to calling function but not from
calling function to called function. The function without parameters and with return value is considered
under upward communication.
Example
#include <stdio.h> #include<conio.h> void main(){
int result ;
int addition() ; // function declaration clrscr() ;
Output SUM=30
Bi-Directional Communication
In this type of communication, the data is transferred from called function to calling function and also from
PPS BY BMK 9652707440D
PPS PART-2 UNIT-3,4,5 By MANIKUMAR ASST PROF(B.TECH,M.TECH,MBA,Ph.D) 9652707440
calling function to called function. The function with parameters and with return value is considered
under Bi-Directional communication.
Example
num1 = 10 ; num2 = 20 ;
Output SUM=30
Function Calls
This calls the actual function
Syntax:
function_name (arguments list);
There are two ways that a C function can be called from a program. They are,
1. Call byvalue
2. Call byreference
Call by Value
In call by value method, the value of the variable is passed to the function as parameter.
The value of the actual parameter cannot be modified by formal parameter.
Different Memory is allocated for both actual and formal parameters. Because, value of actual parameter is
copied to formal parameter.
Note:
Call by Reference:
In call by reference method, the address of the variable is passed to the function as parameter.
The value of the actual parameter can be modified by formal parameter.
Same memory is used for both actual and formal parameters since only address is used by both
parameters.
PPS BY BMK 9652707440D
PPS PART-2 UNIT-3,4,5 By MANIKUMAR ASST PROF(B.TECH,M.TECH,MBA,Ph.D) 9652707440
In C Programming we have different ways of parameter passing schemes such as Call by Value and Call
by Reference.
Function is good programming style in which we can write reusable code that can be called whenever
require.
Whenever we call a function then sequence of executable statements gets executed. We can pass some
of the information to the function for processing called argument.
Two Ways of Passing Argument to Function in C Language :
Call by Reference
Call by Value
Let us discuss different ways one by one –
Call by Value:
#include<stdio.h>
void interchange(int number1,int number2)
{
int temp;
temp = number1; number1 = number2;number2 = temp;
}
int main() {
Output:
Number 1 :50
Number 2 :70
In the above example num1 and num2 are the original values and Xerox copy of these values is passed to
the function and these values are copied into number1,number2 variable of sum function respectively.
As their scope is limited to only function so they cannot alter the values inside main function.
Call by Reference/Pointer/Address:
#include<stdio.h>
void interchange(int *num1,int *num2)
{
int temp;
temp = *num1;
*num1 = *num2;
*num2 = temp;
}
int main() {
int num1=50,num2=70; interchange(&num1,&num2); printf("\nNumber 1 : %d",num1);printf("\nNumber 2 :
%d",num2); return(0);
}
Output :
Number 1 :70
Number 2 :50
Call by Address
While passing parameter using call by address scheme, we are passing the actual address of the variable
to the called function.
Any updates made inside the called function will modify the original copy since we are directly modifying the
content of the exact memory location.
Recursion
The process of calling a function by itself is called recursion and the function which calls itself iscalled
recursive function. Recursion is used to solve various mathematical problems by dividing it into smaller
problems.
Syntax of Recursive Function
Flowchart of Recursion
Note: In order to prevent infinite recursive call, we need to define proper exit condition in a recursive
function.
For example, consider the program below:
#include<stdio.h> intmain()
{
printf("Hello world"); main();
return 0;
}
In this program, we are calling main() from main() which is recursion. But we haven't defined any condition
for the program to exit. Hence this code will print "Hello world" infinitely in the output screen.
Types of recursion
DirectRecursion
IndirectRecursion
Direct Recursion
A function is said to be direct recursive if it calls itself directly.
In this program, fibo() is a direct recursive function. This is because, inside fibo() function, there is a
statement which calls fibo() function again directly.
Indirect Recursion
A function is said to be indirect recursive if it calls another function and this new function calls the first
calling function again.
int func1(int n)
{
if (n<=1) return 1;
else
return func2(n);
}
int func2(int n)
{
return func1(n);
}
Whenever we need to pass a list of elements as argument to any function in C language, it ispreferred to
do so using an array.
Declaring Function with array as a parameter
There are two possible ways to do so, one by using call by value and other by using call by reference.
We can either have an array as a Parameter
Or, we can have a pointer in the parameter list, to hold the base address of our
Example 1:
#include<stdio.h>
void giveMeArray(int a);int main()
{
int myArray[] = { 2, 3, 4 };giveMeArray(myArray[2]);return 0;
}
void giveMeArray(int a)
{
printf("%d", a);
}
Output: 4
Example 2:
int main()
{
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8,9, 0};
for (int i=0; i<10;i++)
{
/* Passing addresses of array elements*/disp (&arr[i]);
}
return 0;
} OUTPUT:
1234567890
Output: 94.6
#include<stdio.h>
void displayArray(int arr[3][3]); int main()
{
int arr[3][3], i, j;
printf("Please enter 9 numbers for the array: \n");for (i = 0; i < 3;++i)
{
for (j = 0; j < 3;++j)
{
scanf("%d", &arr[i][j]);
}
}
// passing the array as argument displayArray(arr);return 0;
}
void displayArray(int arr[3][3])
{
int i, j;
printf("The complete array is:\n");for (i = 0; i < 3;++i)
{
// getting cursor to new lineprintf("\n");for (j = 0; j < 3;++j)
{
// \t is used to provide tab space printf("%4d", arr[i][j]);
}}}
Output:
Please enter 9 numbers for the array: 1 2 3 4 5 6 7 8 9
The complete array is: 1 2 3 4 5 6 7 8 9
Passing string to function
Example: Charar[20]
The above example will store 19 character with I null character.
Strings are just char arrays. So, they can be passed to a function in a similar manner as arrays.#include
<stdio.h>
void displayString(char str[]);int main()
{
char str[50]; printf("Enter string: ");gets(str);
displayString(str);
// Passing string c to function. return 0;
}
void displayString(char str[])
{
printf("String Output: ");puts(str);
}
Here, string c is passed from main() function to user-defined function displayString(). In function
declaration, str[] is the formal argument
for(i=0; i<len;i++)
{
c=string[i];
string2[len-i]=c;
}
string2[len+1]='\0';string=string2;
//printf("%s\n", string);
}
The exact size of array is unknown until the compile time, i.e., time when a compiler compiles code written
in a programming language into a executable form. The size of array you have declared initially can be
sometimes insufficient and sometimes more than required.
Dynamic memory allocation allows a program to obtain more memory space, while running or to release
space when no space is required.
Although, C language inherently does not has any technique to allocated memory dynamically, thereare 4
library functions under "stdlib.h" for dynamic memory allocation.
Dynamic memory management refers to manual memory management. This allows you to obtain more
memory when required and release it when not necessary.
malloc()
Allocates requested size of bytes and returns a pointer first byte of allocated space
calloc()
Allocates space for an array elements, initializes to zero and then returns a pointer to memory
free()
realloc()
Write a C program to find sum of n elements entered by user. To perform this program, allocate memory
dynamically using malloc() function.
if(ptr==NULL)
{
printf("Error! memory not allocated.");exit(0);
}
printf("Enter elements of array: ");for(i=0;i<n;++i)
{
scanf("%d",ptr+i); sum+=*(ptr+i);
}
printf("Sum=%d",sum);free(ptr);
return 0;
}
malloc() calloc()
malloc () doesn‟t initializes the allocated memory. calloc () initializes the allocated
It contains garbage values memory to zero
Searching
Searching is one of the most common problems that arise in computing. Searching
is the algorithmic process of finding a particular item in a collection of
items. A search typically answers either True or False as to whether the
item is present. On occasion it may be modified to return where the item is found.
Search operations are usually carried out on a keyfield.
Well, to search an element in a given array, there are two popular algorithms
available:
LinearSearch
BinarySearch
Linear Search
Linear search is a very basic and simple search algorithm. In Linear search, we
search an element or value in a given array by traversing the array from the
starting, till the desired element or value is found.
It compares the element to be searched with all the elements present in the array
and when the element is matched successfully, it returns the index of the
element in the array, else it return -1.
Linear Search is applied on unsorted or unordered lists, when there are fewer
elements in a list.
It has a time complexity of O(n), which means the time is linearly dependent on the
number of elements, which is not bad, but not that goodtoo.
It has a very simple implementation.
It has a simpleimplementation.
SelectionSort
InsertionSort
Bubble Sort in C
Bubble sort is a simple sorting algorithm in which each element is compared with
adjacent element and swapped if their position is incorrect. It is named as
bubble sort because same as like bubbles the lighter elements come up and
heavier elements settledown.
Both worst case and average case complexity is O(n2).
Example Program for Bubble Sort #include<stdio.h>
int main()
{
int a[50],n,i,j,temp;
printf("Enter the size of array: ");scanf("%d",&n);
printf("Enter the array elements: ");
for(i=0;i<n;++i) scanf("%d",&a[i]);
for(i=1;i<n;++i) for(j=0;j<(n-i);++j)
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1]; a[j+1]=temp;
}
printf("\nArray after sorting: ");for(i=0;i<n;++i)
printf("%d ",a[i]);
return 0;
}
Output
Enter the size of array: 4
Enter the array elements: 3 7 9 2
Array after sorting: 2 3 7 9
Step 1: Select the first element of the list (i.e., Element at first position in thelist).
Step 2: Compare the selected element with all other elements in thelist.
Step 3: For every comparision, if any element is smaller than selected element(for
Ascending order), then these two areswapped.
Step 4: Repeat the same procedure with next position in the list till the entire list
issorted.
#include<stdio.h> #include<conio.h>
void main(){
int size,i,j,temp,list[100]; clrscr();
printf("Enter the size of the List: ");
scanf("%d",&size);
printf("Enter %d integer values: ",size);for(i=0; i<size; i++)
scanf("%d",&list[i]);
//Selection sort logicfor(i=0; i<size; i++){
for(j=i+1; j<size; j++){if(list[i] >list[j])
{
temp=list[i]; list[i]=list[j];
list[j]=temp;
}}}
printf("List after sorting is: ");for(i=0; i<size; i++)
printf(" %d",list[i]);
getch();
}
Insertion Sort in C
The insertion sort inserts each element in proper place. The strategy behind the
insertion sort is similar to the process of sorting a pack of cards. You can take a
card, move it to its location in sequence and move the remaining cards left or
right as needed.
In insertion sort, we assume that first element A[0] in pass 1 is already sorted. In
pass 2 the next second element A[1] is compared with the first one and inserted
into its proper place either before or after
the first element. In pass 3 the third element A[2] is inserted into its proper place and
so on.
Example Program for Insertion Sort
while((temp<a[j])&&(j>=0))
{
a[j+1]=a[j]; //moves element forward j=j-1;
}
a[j+1]=temp; //insert element in properplace
}
printf("\nSorted list is as follows\n");for(i=0;i<n;i++)
{
printf("%d ",a[i]);
}
return 0;
}
Algorithm Time
Complexity