0% found this document useful (0 votes)
48 views25 pages

File Handelling in C

File handling in C allows for the creation, reading, writing, and deletion of files, enabling persistent storage of data beyond volatile memory. Key functions include fopen() for opening files, fprintf() and fscanf() for writing and reading formatted data, and fseek() for setting the file pointer to specific locations. The document provides examples and explanations of various file operations and their syntax.

Uploaded by

shivgovindvns
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
48 views25 pages

File Handelling in C

File handling in C allows for the creation, reading, writing, and deletion of files, enabling persistent storage of data beyond volatile memory. Key functions include fopen() for opening files, fprintf() and fscanf() for writing and reading formatted data, and fseek() for setting the file pointer to specific locations. The document provides examples and explanations of various file operations and their syntax.

Uploaded by

shivgovindvns
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

File Handling in C

In programming, we may require some specific input data to be generated several numbers
of times. Sometimes, it is not enough to only display the data on the console. The data to
be displayed may be very large, and only a limited amount of data can be displayed on the
console, and since the memory is volatile, it is impossible to recover the programmatically
generated data again and again. However, if we need to do so, we may store it onto the
local file system which is volatile and can be accessed every time. Here, comes the need of
file handling in C.

File handling in C enables us to create, update, read, and delete the files stored on the local
file system through our C program. The following operations can be performed on a file.

o Creation of the new file


o Opening an existing file
o Reading from the file
o Writing to the file
o Deleting the file

Functions for file handling


There are many functions in the C library to open, read, write, search and close the file. A list
of file functions are given below:

No. Function Description

1 fopen() opens new or existing file

2 fprintf() write data into the file

3 fscanf() reads data from the file

4 fputc() writes a character into the file

5 fgetc() reads a character from file

6 fclose() closes the file


7 fseek() sets the file pointer to given position

8 fputw() writes an integer to file

9 fgetw() reads an integer from file

10 ftell() returns current position

11 rewind() sets the file pointer to the beginning of the file

Opening File: fopen()


We must open a file before it can be read, write, or update. The fopen() function is used to
open a file. The syntax of the fopen() is given below.

1. FILE *fopen( const char * filename, const char * mode );

The fopen() function accepts two parameters:

o The file name (string). If the file is stored at some specific location, then we must mention the
path at which the file is stored. For example, a file name can be
like "c://some_folder/some_file.ext".
o The mode in which the file is to be opened. It is a string.

We can use one of the following modes in the fopen() function.

Mode Description

r opens a text file in read mode

w opens a text file in write mode

a opens a text file in append mode

r+ opens a text file in read and write mode

w+ opens a text file in read and write mode


a+ opens a text file in read and write mode

rb opens a binary file in read mode

wb opens a binary file in write mode

ab opens a binary file in append mode

rb+ opens a binary file in read and write mode

wb+ opens a binary file in read and write mode

ab+ opens a binary file in read and write mode

The fopen function works in the following way.

o Firstly, It searches the file to be opened.


o Then, it loads the file from the disk and place it into the buffer. The buffer is used to provide
efficiency for the read operations.
o It sets up a character pointer which points to the first character of the file.

Consider the following example which opens a file in write mode.

1. #include<stdio.h>
2. void main( )
3. {
4. FILE *fp ;
5. char ch ;
6. fp = fopen("file_handle.c","r") ;
7. while ( 1 )
8. {
9. ch = fgetc ( fp ) ;
10. if ( ch == EOF )
11. break ;
12. printf("%c",ch) ;
13. }
14. fclose (fp ) ;
15. }
Output

The content of the file will be printed.

#include;
void main( )
{
FILE *fp; // file pointer
char ch;
fp = fopen("file_handle.c","r");
while ( 1 )
{
ch = fgetc ( fp ); //Each character of the file is read and stored in the character
file.
if ( ch == EOF )
break;
printf("%c",ch);
}
fclose (fp );
}

Closing File: fclose()


The fclose() function is used to close a file. The file must be closed after performing all the
operations on it. The syntax of fclose() function is given below:

1. int fclose( FILE *fp );

C fprintf() and fscanf()


Writing File : fprintf() function
The fprintf() function is used to write set of characters into file. It sends formatted output to
a stream.

Syntax:

1. int fprintf(FILE *stream, const char *format [, argument, ...])

Example:

1. #include <stdio.h>
2. main(){
3. FILE *fp;
4. fp = fopen("file.txt", "w");//opening file
5. fprintf(fp, "Hello file by fprintf...\n");//writing data into file
6. fclose(fp);//closing file
7. }

Reading File : fscanf() function


The fscanf() function is used to read set of characters from file. It reads a word from the file
and returns EOF at the end of file.

Syntax:

1. int fscanf(FILE *stream, const char *format [, argument, ...])

Example:

1. #include <stdio.h>
2. main(){
3. FILE *fp;
4. char buff[255];//creating char array to store data of file
5. fp = fopen("file.txt", "r");
6. while(fscanf(fp, "%s", buff)!=EOF){
7. printf("%s ", buff );
8. }
9. fclose(fp);
10. } Output:
Hello file by fprintf...

C File Example: Storing employee information


Let's see a file handling example to store employee information as entered by user from
console. We are going to store id, name and salary of the employee.

1. #include <stdio.h>
2. void main()
3. {
4. FILE *fptr;
5. int id;
6. char name[30];
7. float salary;
8. fptr = fopen("emp.txt", "w+");/* open for writing */
9. if (fptr == NULL)
10. {
11. printf("File does not exists \n");
12. return;
13. }
14. printf("Enter the id\n");
15. scanf("%d", &id);
16. fprintf(fptr, "Id= %d\n", id);
17. printf("Enter the name \n");
18. scanf("%s", name);
19. fprintf(fptr, "Name= %s\n", name);
20. printf("Enter the salary\n");
21. scanf("%f", &salary);
22. fprintf(fptr, "Salary= %.2f\n", salary);
23. fclose(fptr);
24. } Output:
Enter the id
1
Enter the name
sonoo
Enter the salary
120000

Now open file from current directory. For windows operating system, go to TC\bin directory,
you will see emp.txt file. It will have following information.

emp.txt

Id= 1
Name= sonoo
Salary= 120000

C fputc() and fgetc()


Writing File : fputc() function
The fputc() function is used to write a single character into file. It outputs a character to a
stream.

Syntax:
1. int fputc(int c, FILE *stream)

Example:

1. #include <stdio.h>
2. main(){
3. FILE *fp;
4. fp = fopen("file1.txt", "w");//opening file
5. fputc('a',fp);//writing single character into file
6. fclose(fp);//closing file
7. }

file1.txt

Reading File : fgetc() function


The fgetc() function returns a single character from the file. It gets a character from the
stream. It returns EOF at the end of file.

Syntax:

1. int fgetc(FILE *stream)

Example:

1. #include<stdio.h>
2. #include<conio.h>
3. void main(){
4. FILE *fp;
5. char c;
6. clrscr();
7. fp=fopen("myfile.txt","r");
8.
9. while((c=fgetc(fp))!=EOF){
10. printf("%c",c);
11. }
12. fclose(fp);
13. getch();
14. }

myfile.txt

this is simple text message

C fputs() and fgets()


The fputs() and fgets() in C programming are used to write and read string from stream. Let's
see examples of writing and reading file using fgets() and fgets() functions.

Writing File : fputs() function


The fputs() function writes a line of characters into file. It outputs string to a stream.

Syntax:

1. int fputs(const char *s, FILE *stream)


Example:
1. #include<stdio.h>
2. #include<conio.h>
3. void main(){
4. FILE *fp;
5. clrscr();
6.
7. fp=fopen("myfile2.txt","w");
8. fputs("hello c programming",fp);
9.
10. fclose(fp);
11. getch();
12. }
myfile2.txt
hello c programming

Reading File : fgets() function


The fgets() function reads a line of characters from file. It gets string from a stream.
Syntax:

1. char* fgets(char *s, int n, FILE *stream)

Example:

1. #include<stdio.h>
2. #include<conio.h>
3. void main(){
4. FILE *fp;
5. char text[300];
6. clrscr();
7.
8. fp=fopen("myfile2.txt","r");
9. printf("%s",fgets(text,200,fp));
10.
11. fclose(fp);
12. getch();
13. }

Output:

hello c programming

C fseek() function
The fseek() function is used to set the file pointer to the specified offset. It is used to write
data into file at desired location.

Syntax:

1. int fseek(FILE *stream, long int offset, int whence)

There are 3 constants used in the fseek() function for whence: SEEK_SET, SEEK_CUR and
SEEK_END.

Example:

1. #include <stdio.h>
2. void main(){
3. FILE *fp;
4.
5. fp = fopen("myfile.txt","w+");
6. fputs("This is My Program", fp);
7.
8. fseek( fp, 7, SEEK_SET );
9. fputs("sonoo jaiswal", fp);
10. fclose(fp);
11. }

myfile.txt

This is sonoo jaiswal

Understanding the fseek() Parameters:


Let's understand the input parameters for the fseek() function is essential for complete
use:

File*: The FILE *stream argument is a reference to the file's associated FILE structure. By
utilizing the fopen() method, it is acquired.

Long int offset: The offset parameter specifies how many bytes will relocated to the whence
parameter's location. It may be zero, positive, or negative.

Whence is an integer that indicates the reference place from which the offset is determined.
Any one of the following three constants may be used:

SEEK_SET: It establishes the offset with respect to the file's start.

SEEK_CUR: It modifies the file pointer's offset to its current location.

SEEK_END: It establishes the offset with respect to the file's end.

Detailed Understanding of the fseek() Function


The three main tasks of the fseek() function are used to move the file pointer, write data to
the specified place, and update the file position indication.

The file pointer is being moved: You can shift the file pointer to a specified area of the file
using the fseek() method. You can change the reference point for the offset by altering
the 'whence' parameter to one of the values SEEK_SET, SEEK_CUR, or SEEK_END.
Putting Data in the Right Place: Using operations like fprintf(), fputs(), fwrite(), etc., you
may write data after shifting the file reference to the correct spot. The data will be written
beginning at the file pointer's new location.

A file position indicator update: The fseek() method automatically updates the file
position indication to reflect the changed location of the file pointer. By doing this, you may
be confident that the file will always be operated on from the right angle.

Regular Use Cases of fseek()


There are several regular use cases of fseek() function. Some use cases are as follows:

Random Access: The fseek() function allows you random access to a file, enabling you
to read or write data at any point you want inside the file. It is especially beneficial for huge
files or databases when sequential data access is not the most effective method.

Modifying Existing Data: Without rewriting the whole file, fseek() lets you edit data at
specified locations inside a file. You can replace or insert new data while keeping the
present contents by shifting the file pointer to the appropriate spot.

Data Appending: You may relocate the file pointer to the end of the file and add additional
data by using the fseek() function with the SEEK_END constant. It is quite helpful when
working with log files or adding entries to an existing file.

Reading Specific Portions: You can read only the information you need by using
the fseek() function to move to a specific location inside a file. Working with huge files or
structured data can improve file reading procedures.

Metadata updating: In some circumstances, metadata may be present in places in files.


You may access these metadata sections using fseek() and make the necessary changes. It
is typical when working with file formats that include headers or other descriptive
information.

Support for huge Files: The fseek() function is compatible with huge files when given
a file offset of type long int. You may now work with files that are larger than what is
allowed by standard file operations.

Considerations for Performance: Although fseek() function offers flexibility, frequent use
of random-access operations can have an adverse effect on speed, particularly with big files.
Consider the trade-off between convenience and performance when considering whether
to use fseek() for file manipulation.

Here are several examples of how to use the C fseek() function and their accompanying
results:
Example 1:
Consider the following text in a file called "data.txt":

1. Line 1
2. Line 2
3. Line 3
4. Line 4
5. Line 5
Code:
1. #include <stdio.h>
2.
3. int main() {
4. FILE *file = fopen("data.txt", "r");
5. if (file == NULL) {
6. printf("Unable to open the file.\n");
7. return 1;
8. }
9.
10. char line[100];
11. fseek(file, 4, SEEK_SET); // Move to the beginning of the fourth line
12. fgets(line, sizeof(line), file);
13. printf("Fourth line: %s", line);
14.
15. fclose(file);
16. return 0;
17. }
Output:
Fourth line: Line 4

Example 2:

Let's say we have a binary file called "data.bin" that contains the following information:
1. 1 2 3 4 5
Code:
1. #include <stdio.h>
2.
3. int main() {
4. FILE *file = fopen("data.bin", "r+b");
5. if (file == NULL) {
6. printf("Unable to open the file.\n");
7. return 1;
8. }
9. int value = 10;

10. fseek(file, 3 * sizeof(int), SEEK_SET); // Move to the fourth integer (zero-based index)
11. fwrite(&value, sizeof(int), 1, file);
12. fclose(file);
13. return 0;
14. } Output:
File contents after writing: 1 2 3 10 5

Example 3:
Consider the following text in a file called "log.txt":

1. Log entry 1
2. Log entry 2

Code:

1. #include <stdio.h>
2.
3. int main() {
4. FILE *file = fopen("log.txt", "a");
5. if (file == NULL) {
6. printf("Unable to open the file.\n");
7. return 1;
8. }
9.
10. fseek(file, 0, SEEK_END); // Move to the end of the file
11. fputs("\nLog entry 3", file);
12.
13. fclose(file);
14. return 0;
15. }

Output:

Log entry 1
Log entry 2
Log entry 3

Example 4:

1. #include <stdio.h>
2. int main() {
3. FILE *file = fopen("data.txt", "r");
4. if (file == NULL) {
5. printf("Unable to open the file.\n");
6. return 1;
7. }
8. fseek(file, 0, SEEK_END); // Move to the end of the file
9. long size = ftell(file); // Get the file size
10. printf("File size: %ld bytes\n", size);
11.
12. fclose(file);
13. return 0;
14. }

Output:

File size: 28 bytes

The fseek() function in the C laguage allows programmers to set the file pointer to a given
offset inside a file, making it an essential tool for file manipulation. Developers may
perform various tasks, including random access, adding data, editing existing
material, and reading particular file sections, skillfully utilizing the fseek() function.

For fseek() to operate properly, it is crucial to comprehend its syntax, which comprises
the FILE pointer, offset, and whence arguments. The reference location from which the
offset is computed is determined by the three variables SEEK_SET, SEEK_CUR,
and SEEK_END, enabling precise control over the movement of the file pointer.

Programmers may manage big files, access data structures in binary files, and modify
metadata sections with the help of fseek(). Additionally, the function has error-handling
features that make it possible to identify and fix problems like looking outside of file
boundaries or using closed files.
When using fseek(), it's crucial to consider the compromise between ease and speed.
Performance can be impacted by excessive random-access operations, especially when
dealing with big files. Therefore, it is essential to analyze how to optimize file handling and
reduce pointless carefully seeks.

Developers may improve their ability to manipulate files by understanding the fseek()
method, which will make their programs more effective, adaptable, and resilient.
Programmers can easily handle sophisticated file operations due to fseek(), which enables
file navigation, data modification, and content adding.

fseek() is a useful tool for manipulating file pointers and accessing data at precise points in
the world of file management in C. By embracing and comprehending the potential of
fseek(), developers may handle files with a new degree of precision and control, resulting in
more complex and useful programs.

C Preprocessor Directives
The C preprocessor is a micro processor that is used by compiler to transform your code
before compilation. It is called micro preprocessor because it allows us to add macros.

Note: Proprocessor direcives are executed before compilation.

All preprocessor directives starts with hash # symbol.

Let's see a list of preprocessor directives.


o #include
o #define
o #undef
o #ifdef
o #ifndef
o #if
o #else
o #elif
o #endif
o #error
o #pragma

C Macros
C macros provide a potent method for code reuse and simplification. They let programmers
construct symbolic names or phrases that are changed to certain values before the
compilation process begins. The use of more macros makes code easier to comprehend,
maintain, and makes mistakes less likely. In this article, we'll delve deeper into the concept
of C macros and cover their advantages, ideal usage scenarios, and potential hazards.

A macro is a segment of code which is replaced by the value of macro. Macro is defined by
#define directive. There are two types of macros:

1. Object-like Macros
2. Function-like Macros

Object-like Macros
The object-like macro is an identifier that is replaced by value. It is widely used to represent
numeric constants. For example:

1. #define PI 3.14

Here, PI is the macro name which will be replaced by the value 3.14.

Function-like Macros
The function-like macro looks like function call. For example:

1. #define MIN(a,b) ((a)<(b)?(a):(b))

Here, MIN is the macro name.

Visit #define to see the full example of object-like and function-like macros.

C Predefined Macros
ANSI C defines many predefined macros that can be used in c program.

No. Macro Description

1 _DATE_ represents current date in "MMM DD YYYY" format.

2 _TIME_ represents current time in "HH:MM:SS" format.

3 _FILE_ represents current file name.

4 _LINE_ represents current line number.

5 _STDC_ It is defined as 1 when compiler complies with the ANSI standard.

C predefined macros example


File: simple.c

1. #include<stdio.h>
2. int main(){
3. printf("File :%s\n", __FILE__ );
4. printf("Date :%s\n", __DATE__ );
5. printf("Time :%s\n", __TIME__ );
6. printf("Line :%d\n", __LINE__ );
7. printf("STDC :%d\n", __STDC__ );
8. return 0;
9. }

Output:
File :simple.c
Date :Dec 6 2015
Time :12:28:46
Line :6
STDC :1

Advantages of Using Macros:


There are various advantages of Macros in C. Some main advantages of C macros are as
follows:

Code reuse: By allowing developers to declare a piece of code just once and use it several
times, macros help to promote modular programming and minimize code duplication.

Code abbreviation: Macros make it possible to write clear, expressive code that is simpler
to read and comprehend the intentions of the programmer.

Performance Optimization: By minimizing function call overhead, macros may be utilized


to optimize code execution. For instance, it is possible to inline brief pieces of code using
function-like macros.

Using macros, conditional compilation enables distinct sections of the code to


be included or removed based on predetermined circumstances.
Debugging or platform-specific code both benefit from this functionality.

When Using Macros, Exercise Caution:


Use caution while constructing function-like macros in brackets. Always use brackets to
contain parameters and the full macro body to avoid unexpected outcomes brought on by
operator precedence.

Macro Side consequences: Steer clear of macros with negative consequences. Multiple
evaluations of macro arguments may result in surprising results since macros are directly
substituted.

Use capital letters to distinguish macro names from standard C identifiers and to make the
code easier to understand.

Macros' best practices:


There are various practices of C macros. Some of them are as follows:

For object-like macros, use constants: If possible, use object-like macros for constants to
make the code more readable and make any necessary adjustments simpler.

Macros with Functions for Basic Operations: Use macros that resemble functions for
straightforward, one-line operations. Use normal functions in their place for more intricate
processes.

Use Predefined Macros Wisely: While predefined macros like __DATE__, __TIME__, and
__FILE__ are useful for debugging and logging, don't rely on them for essential functions.

Macros and Conditional Compilation:


When conditional compilation is used, macros significantly contribute utilizing the #ifdef,
#ifndef, #else, and #endif directives. It gives the compiler the ability to include or reject
code blocks depending on precise criteria.

Using Inline Functions vs. Macros:


Inline functions offer comparable advantages to macros while avoiding some of the
possible drawbacks of macros. Macros can enhance speed since they directly replace code.
Modern compilers may frequently inline appropriate functions, making them a safer option
in many circumstances.

Using macros for debugging:


As shown in the example above, macros can be helpful in debugging by supplying extra
details like file names, line numbers, and timestamps.

Conclusion:
As a result, C macros are a crucial component of the C programming language and give
programmers a strong tool for code reuse and optimization. Object-like macros act
as symbolic constants and improve code readability by giving numerical values names that
make sense. The cost of function calls has decreased, and efficiency is increased through
function-like macros, which operate as in lined code snippets.

Code reuse, code simplification, and conditional compilation are a few advantages of
using macros in C. Programmers can build modular code structures and streamline
complicated procedures by designing macros. Additionally, conditional
compilation facilitates platform-specific functions and debugging by enabling developers
to include or remove code blocks based on certain criteria.

Command Line Arguments in C


The arguments passed from command line are called command line arguments. These
arguments are handled by main() function.

To support command line argument, you need to change the structure of main() function as
given below.

1. int main(int argc, char *argv[] )

Here, argc counts the number of arguments. It counts the file name as the first argument.

The argv[] contains the total number of arguments. The first argument is the file name
always.

Example
Let's see the example of command line arguments where we are passing one argument with
file name.

1. #include <stdio.h>
2. void main(int argc, char *argv[] ) {
3.
4. printf("Program name is: %s\n", argv[0]);
5.
6. if(argc < 2){
7. printf("No argument passed through command line.\n");
8. }
9. else{
10. printf("First argument is: %s\n", argv[1]);
11. }
12. }

Run this program as follows in Linux:

1. ./program hello

Run this program as follows in Windows from command line:


1. program.exe hello

Output:

Program name is: program


First argument is: hello

If you pass many arguments, it will print only one.

1. ./program hello c how r u

Output:

Program name is: program


First argument is: hello

But if you pass many arguments within double quote, all arguments will be treated as a
single argument only.

1. ./program "hello c how r u"

Output:

Program name is: program


First argument is: hello c how r u

You can write your program to print all the arguments. In this program, we are printing only
argv[1], that is why it is printing only one argument.
Features of C Language
Answer: A good programming language it must have the following characteristics:

Clear and Unambiguous: The algorithm should be clear and unambiguous. Each of its

steps should be clear in all aspects and must lead to only one meaning.

Well-Defined Inputs: If an algorithm says to take inputs, it should be well-defined

inputs. It may or may not take input. Well-Defined Outputs: The algorithm must clearly
define what output will be yielded and it should be well-defined as well. It should produce
at least 1 output. Finite-ness: The algorithm must be finite, i. it should terminate after a finite
time.

Feasible: The algorithm must be simple, generic, and practical, such that it can be

executed with the available resources. It must not contain some future technology or

anything.

Language Independent: The Algorithm designed must be language-independent, i. it

must be just plain instructions that can be implemented in any language, and yet the

output will be the same, as expected.

Q: What is psudo code?

Ans:
Pseudo code: It’s simply an implementation of an algorithm in the form of annotations and informative
text written in plain English. It is a methodology that allows the programmer to represent the
implementation of an algorithm. It has no syntax like any of the programming language and thus can’t be
compiled or interpreted by the computer. Kernel is central component of an operating system that
manages operations of computer and hardware. It basically manages operations of memory and CPU time.
It is core component of an operating system. Kernel acts as a bridge between applications and data
processing performed at hardware level using inter-process communication and system calls
1. #include<stdio.h>
2. #include<stdlib.h>
3. int main(){
4. int a[10][10],b[10][10],mul[10][10],r,c,i,j,k;
5. system("cls");
6. printf("enter the number of row=");
7. scanf("%d",&r);
8. printf("enter the number of column=");
9. scanf("%d",&c);
10. printf("enter the first matrix element=\n");
11. for(i=0;i<r;i++)
12. {
13. for(j=0;j<c;j++)
14. {
15. scanf("%d",&a[i][j]);
16. }
17. }
18. printf("enter the second matrix element=\n");
19. for(i=0;i<r;i++)
20. {
21. for(j=0;j<c;j++)
22. {
23. scanf("%d",&b[i][j]);
24. }
25. }
26.
27. printf("multiply of the matrix=\n");
28. for(i=0;i<r;i++)
29. {
30. for(j=0;j<c;j++)
31. {
32. mul[i][j]=0;
33. for(k=0;k<c;k++)
34. {
35. mul[i][j]+=a[i][k]*b[k][j];
36. }
37. }
38. }
39. //for printing result
40. for(i=0;i<r;i++)
41. {
42. for(j=0;j<c;j++)
43. {
44. printf("%d\t",mul[i][j]);
45. }
46. printf("\n");
47. }
48. return 0;
49. }
Qus: Write a program in C to print the following pattern:
12345
1234
123
12
1
#include <stdio.h>
int main() {
int i, j, rows;
printf("Enter the number of rows: ");
scanf("%d", &rows);
for (i = 1; i <= rows; ++i) {
for (j = 1; j <= i; ++j) {
printf("%d ", j);
}
printf("\n");
}
return 0;
}
Selection Sort Algorithm
In this article, we will discuss the Selection sort Algorithm. The working procedure of selection sort
is also simple. This article will be very helpful and interesting to students as they might face
selection sort as a question in their examinations. So, it is important to discuss the topic.
In selection sort, the smallest value among the unsorted elements of the array is selected in every
pass and inserted to its appropriate position into the array. It is also the simplest algorithm. It is an
in-place comparison sorting algorithm. In this algorithm, the array is divided into two parts, first is
sorted part, and another one is the unsorted part. Initially, the sorted part of the array is empty, and
unsorted part is the given array. Sorted part is placed at the left, while the unsorted part is placed at
the right.
In selection sort, the first smallest element is selected from the unsorted array and placed at the first
position. After that second smallest element is selected and placed in the second position. The
process continues until the array is entirely sorted.
The average and worst-case complexity of selection sort is O(n2), where n is the number of items.
Due to this, it is not suitable for large data sets.
#include <stdio.h>
void selection(int arr[], int n)
{ int i, j, small;
for (i = 0; i < n-1; i++) // One by one move boundary of unsorted subarray
{
small = i; //minimum element in unsorted array
for (j = i+1; j < n; j++)
if (arr[j] < arr[small])
small = j;
// Swap the minimum element with the first element
int temp = arr[small];
arr[small] = arr[i];
arr[i] = temp;
}
}
void printArr(int a[], int n) /* function to print the array */
{
int i;
for (i = 0; i < n; i++)
printf("%d ", a[i]);
}
int main()
{
int a[] = { 12, 31, 25, 8, 32, 17 };
int n = sizeof(a) / sizeof(a[0]);
printf("Before sorting array elements are - \n");
printArr(a, n);
selection(a, n);
printf("\nAfter sorting array elements are - \n");
printArr(a, n);
return 0;
}

You might also like