Unit-2-PPS-2
Unit-2-PPS-2
}
• Write a C program to sort the given array.
#include<stdio.h>
void main ()
{
int arr[20],i,n,temp;
printf("Enter the size of the array?");
scanf("%d",&n);
printf("Enter the elements of the array?");
for(i = 0; i<n; i++)
{
scanf("%d",&arr[i]);
}
for(i = 0; i<10; i++)
{
for(j = i+1; j<10; j++)
{
if(a[j] > a[i])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
printf("Printing Sorted Element List ...\n");
for(i = 0; i<10; i++)
{
printf("%d\n",a[i]);
}
}
Two Dimensional Array in C
• A two-dimensional array in an array of one-dimensional arrays.
• Each element of a two-dimensional array is an array itself.
• It is like a table or a matrix.
• We can visualize a two-dimensional array as one-dimensional arrays stacked
vertically forming a table with ‘m’ rows and ‘n’ columns.
• Hence, the location of any element is characterised by its row number and
column number.
• Both row and column index start from 0.
• The program below displays the row and column indices of each element in a 2D array :
#include <stdio.h> int main()
{ // Create and initialize an array with 3 rows // and 2 columns
int arr[3][2] = { { 0, 1 }, { 2, 3 }, { 4, 5 } };
// Print each array element's value
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 2; j++)
{ printf("arr[%d][%d]: %d ", i, j, arr[i][j]);
}
printf("\n");
} }
Output:
arr[0][0]: 0 arr[0][1]: 1
arr[1][0]: 2 arr[1][1]: 3
arr[2][0]: 4 arr[2][1]: 5
Write a C-Program to read the elements into two dimenational array
#include <stdio.h>
void main() {
int arr[3][2],i,j;
for (int i = 0; i < 3; i++)
{ for (int j = 0; j < 2; j++)
{ printf(“enter the arr[%d][%d] element", I,j);
scanf(“%d”,&arr[i][j];
} }
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 2; j++)
{ printf(“%d ", arr[i][j]);
}
1.#include <stdio.h>
Void main() {
1. int m, n, i, j, a[10][10], b[10][10], c[10][10];
2. printf("Enter the number of rows and columns of the matrices: ");
3. scanf("%d%d", &m, &n);
4. printf("Enter the elements of matrix A: \n");
5. for (i = 0; i < m; i++) {
6. for (j = 0; j < n; j++) {
7. scanf("%d", &a[i][j]);
8. }
9. }
10. printf("Enter the elements of matrix B: \n");
11. for (i = 0; i < m; i++) {
12. for (j = 0; j < n; j++) {
13. scanf("%d", &b[i][j]);
14. }
15. }
16. // add the matrices
17. for (i = 0; i < m; i++) {
18. for (j = 0; j < n; j++) {
19. c[i][j] = a[i][j] + b[i][j];
20. }
21. }
22. // print the result
23. printf("The sum of the two matrices is: \n");
24. for (i = 0; i < m; i++) {
25. for (j = 0; j < n; j++) {
26. printf("%d ", c[i][j]);
27. }
28. printf("\n");
29. } }
#include <stdio.h>
Enter the number of rows and columns of the matrices: 2 2
int main() {
Enter the elements of matrix A: int rows1, cols1, rows2, cols2;
Enter the elements of matrix B: printf("Enter the number of rows and columns for the second matrix: ");
scanf("%d %d", &rows2, &cols2);
#include <stdio.h>
void main() {
int a[10][10], transpose[10][10], r, c;
printf("Enter rows and columns: ");
scanf("%d %d", &r, &c);
printf("\nEnter matrix elements:\n");
for (int i = 0; i < r; ++i) {
for (int j = 0; j < c; ++j)
{ printf("Enter element a[%d][%d] ", i , j );
scanf("%d", &a[i][j]);
} } // computing the transpose
for (int i = 0; i < r; ++i)
for (int j = 0; j < c; ++j) {
transpose[j][i] = a[i][j]; }
// printing the transpose
printf("\nTranspose of the matrix:\n");
for (int i = 0; i < c; ++i)
{
for (int j = 0; j < r; ++j) {
printf("%d ", transpose[i][j]);
}
printf("\n"); }
}
Strings in C
• The string can be defined as the one-dimensional array of characters terminated by a null ('\0').
• The C String is stored as an array of characters.
• The difference between a character array and a C string is that the string in C is
terminated with a unique character ‘\0’.
• The termination character ('\0') is important in a string since it is the only
way to identify where the string ends. When we define a string as char s[10],
the character s[10] is implicitly initialized with the null in the memory.
• C String Declaration Syntax: char string_name[size];
• In the above syntax string_name is any name given to the string variable and size is used to define
the length of the string, i.e the number of characters strings will store.
• There is an extra terminating character which is the Null character (‘\0’) used to indicate the
termination of a string that differs strings from normal character arrays.
1.There are two ways to declare a string in c language. 1. char array 2.string literal
• Char array: char ch[10]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0’};
• String literal: char ch2[11]="javatpoint";
• The difference between the two ways of creating strings, is that the second method is
easier to write, and you do not have to include the \0 character, as C compiler will do it for
you.
#include<stdio.h> Output:
#include <string.h> Char Array Value is: javatpoint
main(){ String Literal Value is: javatpoint
char ch[11]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
char ch2[11]="javatpoint";
printf("Char Array Value is: %s\n", ch);
printf("String Literal Value is: %s\n", ch2); }
• Read a String Input From the Keyboard
// C program to read string from user Output:
Enter the string?MGIT CSE
#include<stdio.h> int main() {
You entered MGIT CSE
// declaring string
char str[50];
printf("Enter the string?");
scanf("%s",str);
printf(“You entered %s",str);
}
#include <stdio.h>
#include <string.h>
void main() {
char str[100];
int i, length=0;
printf("Enter a string: ");
scanf("%s", str);
for (i = 0; str[i] != '\0'; i++) {
length++; }
printf("The length of the string is: %d\n", length);
}
String Functions
• The C string functions are built-in functions that can be used for various operations and manipulations on strings.
• These string functions can be used to perform tasks such as string copy, concatenation, comparison, length, etc.
• The <string.h> header file contains these string functions.
#include<stdio.h>
#include <string.h>
void main(){ Output:
char ch[20]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'}; The second string is:javapoint
char ch2[20];
strcpy(ch2,ch);
printf(“The second string is: %s",ch2);
}
• strcat() function accepts two input strings and appends the second string's content to the end of
the first string.
#include <stdio.h>
#include <string.h>
void main() { Output:
char str1[20] = "Hello "; str1:HelloWorld
char str2[] = "World!";
// Concatenate str2 to str1 (the result is stored in str1)
strcat(str1, str2);
printf(“str1:%s", str1);
}
• The strcmp(first_string, second_string) function compares two strings and returns 0 if both strings are
equal.
#include <stdio.h>
#include <string.h>
void main() {
char str1[] = "Hello";
char str2[] = "Hello";
char str3[] = "Hi";
// Compare str1 and str2, and print the result
printf("%d\n", strcmp(str1, str2));
// Compare str1 and str3, and print the result
printf("%d\n", strcmp(str1, str3));
}
Array of Strings
• In C programming String is a 1-D array of characters and is defined as an array of
characters.
• But an array of strings in C is a two-dimensional array of character types.
• Each String is terminated with a null character (\0). It is an application of a 2d array.
• Syntax: char variable_name[r][m] = {list of string};
var_name is the name of the variable in C.
r is the maximum number of string values that can be stored in a string array.
m is the maximum number of character values that can be stored in each string array.
• char arr[3][10] = {"Geek", "Geeks", "Geekfor"};
#include <stdio.h>
void int main() {
char arr[3][10] = {"Geek", "Geeks", "Geekfor"};
printf("String array Elements are:\n");
for (int i = 0; i < 3; i++)
{
printf("%s\n", arr[i]);
}
}
Output:
String array Elements are:
Geek
Geeks
Geekfor
Structures
• In C, there are cases where we need to store multiple attributes(variables) of
an entity. It is not necessary that an entity has all the information of one
type only. It can have different attributes of different data types. For
example, an entity Student may have its name (string), roll number (int),
marks (float).
• We are often required to work with values of different data types having
certain relationships among them. For example, a book is described by
its title (string), author (string), price (double), number of
pages (integer), etc.
• C provides you with an additional and simpler approach where you can use
a special data structure, i.e., structure, in which, you can group all the
information of different data type regarding an entity.
• The structure in C is a user-defined data type that can be used to group related
variable(items) of possibly different types into a single type.
• The struct keyword is used to define the structure in the C programming language.
• Each variable in the structure is known as a member of the structure.
• Additionally, the values of a structure are stored in contiguous memory locations.
• The difference between an array and a structure is that an array is a homogenous collection of
similar types, whereas a structure can have elements of different types stored adjacently and
identified by a name.
• C Structure Declaration: We use the struct keyword to declare the structure and specify its member variables
along with their datatype.
• structure syntax:
struct structure_name {
data_type member_name1;
data_type member_name1;
....
....
};
• The above syntax is also called a structure template or structure prototype and no memory is allocated
to the structure in the declaration.
• In the following example we are declaring a structure for Book to store the details of a Book −
struct book{
char title[50];
char author[50];
double price;
int pages;
}:
• To use structure in our program, we have to define its instance(variable).
• We can do that by creating variables of the structure type.
• We can define structure variables using two methods:
- Structure Variable Declaration with Structure
struct book{
char title[50];
char author[50];
double price;
int pages;
} book1;
- Structure Variable Declaration after Structure definition
struct book{
char title[50];
char author[50];
double price;
int pages;
};
struct book book1;
• struct book book1 = {"Learn C", "Dennis Ritchie", 675.50, 325};
• Accessing members of the structure:
are two ways to access structure members:
1.By . (member or dot operator) 2.By -> (structure pointer operator)
1. book1.title or book1.author
#include <stdio.h> Output:
struct book{ char title[10]; Title: Learn C
char author[20]; Author: Dennis Ritchie
double price; Price: 675.500000
int pages; Pages: 325
}; Size of book struct: 48
int main()
{ struct book book1 = {"Learn C", "Dennis Ritchie", 675.50, 325};
printf("Title: %s \n", book1.title);
printf("Author: %s \n", book1.author);
printf("Price: %lf\n", book1.price);
printf("Pages: %d \n", book1.pages);
printf("Size of book struct: %d", sizeof(struct book));
}
#include <stdio.h> Output:
#include <string.h> Title: Learn C
struct book{ char title[10]; Author: Dennis Ritchie
char author[20]; Price: 675.500000
Pages: 325
double price; int pages;
} book1;
void main(){ strcpy(book1.title, "Learn C");
strcpy(book1.author, "Dennis Ritchie");
book1.price = 675.50;
book1.pages = 325;
printf("Title: %s \n", book1.title);
printf("Author: %s \n", book1.author);
printf("Price: %lf \n", book1.price);
printf("Pages: %d \n", book1.pages); }
struct employee
{ int id;
char name[20];
float salary;
};
#include <stdio.h>
Output:
#include <string.h> Title: Learn C
struct book{ char title[10]; Author: Dennis Ritchie
char author[20]; Price: 675.500000
double price; Pages: 325
int pages; }; Size of book struct: 48
void main(){
struct book book1 = {"Learn C", "Dennis Ritchie", 675.50, 325},
book2;
book2 = book1;
printf("Title: %s \n", book2.title);
printf("Author: %s \n", book2.author);
printf("Price: %lf \n", book2.price);
printf("Pages: %d \n", book2.pages);
printf("Size of book struct: %d", sizeof(struct book));
}
#include <stdio.h>
#include <string.h>
struct book{ char title[10]; Output:
char author[20]; Title: Learn C
double price; Author: Dennis Ritchie
int pages; }; Price: 675.500000
void main(){ Pages: 325
struct book book1; Size of book struct: 48
printf(“Enter the book title”);
scanf(“%s”,&book1.title);
printf(“Enter the book author name”);
scanf(“%s”,&book1.author);
printf(“Enter the book price”);
scanf(“%lf”,&book1.price);
printf(“Enter the book pages”);
scanf(“%d”,&book1.pages);
Printf(“Print the book inforamtion”);
printf("Title: %s \n", book1.title);
printf("Author: %s \n", book1.author);
printf("Price: %lf \n", book1.price);
printf("Pages: %d \n", book1.pages);
printf("Size of book struct: %d", sizeof(struct book));
}
Array of Structures
• An array of structres in C can be defined as the collection of multiple structures variables(objects)
where each variable contains information about different entities.
• The array of structures in C are used to store information about multiple entities of different data
types.
• Let us define a struct type called book as follows:
struct book{
char title[10];
double price;
int pages;
};
• struct book b[3] = { {"Learn C", 650.50, 325},
{"C Pointers", 175, 225},
{"C Pearls", 250, 250}
};
#include<stdio.h>
#include <string.h>
struct student{
int rollno;
char name[10];
};
void main(){
int i;
struct student st[5];
printf("Enter Records of 5 students");
for(i=0;i<5;i++){
printf("\nEnter Rollno:");
scanf("%d",&st[i].rollno);
printf("\nEnter Name:");
scanf("%s",&st[i].name);
}
printf("\nStudent Information List:");
for(i=0;i<5;i++){
printf("\nRollno:%d, Name:%s",st[i].rollno,st[i].name);
}
}
Output:
Enter Records of 5 students
Enter Rollno:1
Enter Name:Sonoo
Enter Rollno:2
Enter Name:Ratan
Enter Rollno:3
Enter Name:Vimal
Enter Rollno:4
Enter Name:James
Enter Rollno:5
Enter Name:Sarfraz
Student Information List:
Rollno:1, Name:Sonoo
Rollno:2, Name:Ratan
Rollno:3, Name:Vimal
Rollno:4, Name:James
Rollno:5, Name:Sarfraz
C Unions
• The Union is a user-defined data type in C language that can contain elements of the
different data types just like structure.
• But unlike structures, all the members in the C union are stored in the same memory
location.
• Due to this, only one member can store data at the given instance.
• You can define a union with many members, but only one member can
contain a value at any given time.
• Unions provide an efficient way of using the same memory location for
multiple purpose.
• Syntax: union union_name {
datatype member1;
datatype member2;
...
};
• we only declare the template of the union, i.e., we only declare the members’ names
and data types along with the name of the union. No memory is allocated to the
union in the declaration.
• Define a Union Variable:
- We need to define a variable of the union type to start using union members. There are two methods using which
we can define a union variable.:1.With Union Declaration 2.After Union Declaration
1.Defining Union Variable with Declaration
union union_name {
datatype member1;
datatype member2;
...
} var1, var2, ...;
2. Defining Union Variable after Declaration
union union_name var1, var2, var3...;
#include <stdio.h> Output:
// Define a union Size of a: 4 bytes
Size of b: 4 bytes
union Data { int a; Size of c: 20 bytes
float b; Size of union: 20 bytes
char c[20]; };
void main() {
union Data data;
// Printing the size of the each member of union
printf("Size of a: %lu bytes\n", sizeof(data.a));
printf("Size of b: %lu bytes\n", sizeof(data.b));
printf("Size of c: %lu bytes\n", sizeof(data.c));
// Printing the size of the union
printf("Size of union: %lu bytes\n", sizeof(data));
}
// C Program to demonstrate how to use union
#include <stdio.h>
// union template or declaration
union un {
int member1;
char member2;
float member3; };
We define a struct type called mystruct. It has an integer element "a" and
"b" is the pointer to mystruct type itself.
struct mystruct{int a;
struct mystruct *b; };
• We declare three variables of mystruct type
struct mystruct x = {10, NULL}, y = {20, NULL}, z = {30, NULL};
• Next, we declare three "mystruct" pointers and assign the
references x, y and z to them.
struct mystruct * p1, *p2, *p3;
p1 = &x; p2 = &y; p3 = &z;
• The variables "x", "y" and "z" are unrelated as they will be located at random locations, unlike the
array where all its elements are in adjacent locations.
#include <stdio.h>
struct mystruct{ int a;
struct mystruct *b; };
int main(){
struct mystruct x = {10, NULL}, y = {20, NULL}, z = {30, NULL};
struct mystruct * p1, *p2, *p3;
p1 = &x; p2 = &y; p3 = &z;
x.b = p2;
y.b = p3;
printf("Address of x: %d a: %d Address of next: %d\n", p1, x.a, x.b);
printf("Address of y: %d a: %d Address of next: %d\n", p2, y.a, y.b);
printf("Address of z: %d a: %d Address of next: %d\n", p3, z.a, z.b);
}
UNIT - III
Preprocessor and File handling in C:
Preprocessor: Commonly used Preprocessor commands like include, define, undef, if, ifdef, ifndef
Files: Text and Binary files, Creating and Reading and writing text and binary files, Appending
data to existing files, Writing and reading structures using binary files, Random access using
fseek, ftell and rewind functions.
C Preprocessors
• Preprocessors are programs that process the source code before compilation.
• The C Preprocessor is not a part of the compiler, but is a separate step in the compilation process. In
simple terms, a C Preprocessor is just a text substitution tool and it instructs the compiler to do the
required pre-processing before the actual compilation. We'll refer to the C Preprocessor as CPP.
• One of the important functions of a preprocessor is to include the header files that contain the
library functions used in the program. The preprocessor in C also defines the constants and expands
the macros.
• The preprocessor statements in C are called directives. A preprocessor section of the program
always appears at the top of the C code. Each preprocessor statement starts with the hash (#)
symbol.
Preprocessor Directives Description
#define Used to define a macro
#undef Used to undefine a macro
#include Used to include a file in the source code program
#ifdef Used to include a section of code if a certain macro is defined by #define
#ifndef Used to include a section of code if a certain macro is not defined by #define
#if Check for the specified condition
#include <stdio.h>
#define max 100
int main() {
printf("max is %d", max);
return 0; }
• The following directives tell the CPP to get "stdio.h" from the System Libraries and add the
text to the current source file.
#include <stdio.h>
• Now, take a look at the following #define and #undef directives. They tell the CPP to
undefine existing FILE_SIZE and define it as 42.
#undef FILE_SIZE
#define FILE_SIZE 42
• The following directive tells the CPP to define MESSAGE only if MESSAGE isn't already
defined.
#ifndef MESSAGE
#define MESSAGE "You wish!"
#endif
Macros
• In C, a macro is a piece of code in a program that is replaced by the value of the macro. Macro is
defined by #define directive.
• Whenever a macro name is encountered by the compiler, it replaces the name with the definition of the
macro.
• Macro definitions need not be terminated by a semi-colon(;).
// C Program to illustrate the macro
#include <stdio.h>
// macro definition
#define LIMIT 5
int main() {
for (int i = 0; i < LIMIT; i++)
{ printf("%d \n", i); }
return 0; }
Macro to find the maximum number among two numbers.
#include <stdio.h>
#define MAX(x,y) ((x) > (y) ? (x) : (y))
void main() {
printf("Max between 20 and 10 is %d\n", MAX(10, 20));
}
Macro to find the area of circle
#define AREA(a) (5.18 * a * a)
void main()
{
float r = 3.5, x;
x = AREA (r);
printf ("\n Area of circle = %f", x);
}
Files
• So far the operations using the C program are done on a prompt/terminal which is not
stored anywhere.
• The output is deleted when the program is closed.
• But in the software industry, most programs are written to store the information
fetched from the program.
• 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.
1.Creation of the new file
2.Opening an existing file
3.Reading from the file
4.Writing to the file
5.Deleting the file
Types of Files
• A file can be classified into two types based on the way the file stores the data. They are as follows:
1.Text Files 2.Binary Files
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.
C File Operations
• C file operations refer to the different possible operations that we can perform on a file in C such as:
1.Creating a new file – fopen() with attributes as “r” or “r+” or “w” or “w+” or “a” or “a+”
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
Creating Text File
// C Program to create a file
#include <stdio.h>
#include <stdlib.h>
void main()
{
// file pointer
FILE* fptr;
// creating file using fopen() access mode "w"
fptr = fopen("file.txt", "w");
// checking if the file is created
if (fptr == NULL) {
printf("The file is not opened. The program will "
"exit now");
exit(0);
}
else {
printf("The file is created Successfully."); } }
Reading From a File
• The file read operation in C can be performed using functions fscanf() or fgets().
• Both the functions performed the same operations as that of scanf and gets but with an additional parameter, the
file pointer.
Function Description
fscanf() Use formatted string and variable arguments list to take input from a file.
• The file write operations can be performed by the functions fprintf() and fputs() with similarities to read operations.
Function Description
Similar to printf(), this function use formatted string and varible arguments list to print
fprintf()
output to the file.
fputs() Prints the whole line in the file and a newline at the end.
fwrite() This functions write the specified amount of bytes to the binary file.
Reading Single Character from a File
• The fgetc() function reads a character from the input file referenced by "fp".
• int fgetc(FILE * fp);
• The return value is the character read, or in case of any error, it returns EOF.
#include <stdio.h>
void main(){
FILE *fp ;
char ch ;
fp = fopen ("file1.txt", "r");
while(1) {
ch = fgetc (fp);
if (ch == EOF)
break;
printf ("%c", ch);
}
printf ("\n");
fclose (fp);
}
Reading String from a File
• The fgets() function reads up to "n − 1" characters from the input stream referenced by "fp".
• It copies the read string into the buffer "buf", appending a null character to terminate the string.
// C Program to Read a File using fgets()
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void main() {
FILE *file_ptr;
char str[50];
file_ptr = fopen("test.txt", "r");
if (NULL == file_ptr) {
printf("File can't be opened \n");
}
printf("Content of this file are:: \n");
while (fgets(str, 50, file_ptr) != NULL) {
printf("%s", str);
}
fclose(file_ptr);
Reading Formatted String from a File
• The fscanf() function in C programming language is used to read formatted input from a file.
• Syntax:int fscanf(FILE *stream, const char *format, ...)
#include <stdio.h>
void main() {
FILE *fp; char *s;
int i, a;
float p;
fp = fopen ("file3.txt", "r");
if (fp == NULL) {
puts ("Cannot open file");
return 0; }
while (fscanf(fp, "%d %f %s", &a, &p, s) != EOF)
printf ("Name: %s Age: %d Percent: %f\n", s, a, p);
fclose(fp);
}
Reading text file
#include<stdio.h>
void main( )
{
FILE *fp ;
char ch ;
fp = fopen("file_handle.c","r") ;
if (file == NULL) {
printf("Error in creating file");
Exit(0); }
while ( 1 )
{
ch = fgetc ( fp ) ;
if ( ch == EOF )
break ;
printf("%c",ch) ;
}
fclose (fp ) ;
Writing to a Text File
• The following library functions are provided to write data in a file opened in writeable mode −
• fputc() : Writes a single character to a file.
•fputs(): Writes a string to a file.
•fprintf(): Writes a formatted string (data) to a file.
Writing Single Character to a File
• The fputc() function is an unformatted function that writes a single character value of the argument
"c" to the output stream referenced by "fp".
• syntax: int fputc(int c, FILE *fp);
• In the following code, one character from a given char array is written into a file opened in the "w"
mode:
#include <stdio.h>
void main() { FILE *fp; char * string = "C Programming tutorial from
TutorialsPoint";
int i; char ch;
fp = fopen("file1.txt", "w");
for (i = 0; i < strlen(string); i++) {
ch = string[i];
if (ch == EOF)
break;
fputc(ch, fp);
} printf ("\n");
fclose(fp);
Writing String to a File
• The fputs() function writes the string "s" to the output stream referenced by
"fp".
• It returns a non-negative value on success, else EOF is returned in case of
any error.
• Syntax: int fputs(const char *s, FILE *fp);
• The following program writes strings from the given two-dimensional char
array to a file −
#include <stdio.h>
void main() { FILE *fp;
char *sub[] = {"C Programming Tutorial\n", "C++ Tutorial\n", "Python Tutorial\n",
"Java Tutorial\n"};
fp = fopen("file2.txt", "w");
for (int i = 0; i < 4; i++)
{ fputs(sub[i], fp); }
fclose(fp);
}
Writing Formatted String to a File
• The fprintf() function sends a formatted stream of data to the disk file represented by the FILE
pointer.
• Syntax:int fprintf(FILE *stream, const char *format [, argument, ...])
• In the following program, we have an array of struct type called "employee". The structure has a
string, an integer, and a float element. Using the fprintf() function, the data is written to a file.
#include <stdio.h>
struct employee { int age; float percent; char *name; };
void main() { FILE *fp;
struct employee emp[] = { {25, 65.5, "Ravi"}, {21, 75.5, "Roshan"}, {24, 60.5, "Reena"} };
char *string;
fp = fopen("file3.txt", "w");
for (int i = 0; i < 3; i++)
{
fprintf(fp, "%d %f %s\n", emp[i].age, emp[i].percent, emp[i].name);
}
fclose(fp);
}
File Handing Binary Read and Write Functions
• The read/write operations are done in a binary form in the case of a binary file. You need to include
the character "b" in the access mode ("wb" for writing a binary file, "rb" for reading a binary file).
• There are two functions that can be used for binary input and output: the fread() function and
the fwrite() function.
• Both of these functions should be used to read or write blocks of memories, usually arrays or
structures.
• We can use fwrite() function to easily write a structure in a file. fwrite() function writes the to the file stream in the
form of binary data block.
• Syntax: size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
ptr: pointer to the block of memory to be written.
size: the size of each element to be written (in bytes).
nmemb: umber of elements.
stream: FILE pointer to the output file stream.
• Return:Number of objects written.
• Reading Structure from a File using fread
• We can easily read structure from a file using fread() function. This function reads a block of memory
from the given stream.
• Syntax:size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream)
• ptr: pointer to the block of memory to read.
•size: the size of each element to read(in bytes).
•nmemb: number of elements.
•stream: FILE pointer to the input file stream.
#include <stdio.h>
struct employee { int age;
float percent;
char name[10]; };
int main() {
FILE *fp;
struct employee e[] = { {25, 65.5, "Ravi"}, {21, 75.5, "Roshan"},
{24, 60.5, "Reena"} };
char *string;
fp = fopen("file4.dat", "wb");
for (int i = 0; i < 3; i++) {
fwrite(&e[i], sizeof (struct employee), 1, fp);
} fclose(fp);
}
In the following program, an array of a struct type called "employee" has been declared. We use
the fread() function to read one block of byte, equivalent to the size of one employee data, in a file
that is opened in "rb" mode.
#include <stdio.h>
struct employee {
int age;
float percent;
char name[10]; };
int main() { FILE *fp; struct employee e;
fp = fopen ("file4.dat", "rb");
if (fp == NULL) { puts ("Cannot open file"); return 0; }
while (fread (&e, sizeof (struct employee), 1, fp) == 1)
printf ("Name: %s Age: %d Percent: %f\n", e.name, e.age,
e.percent); fclose(fp);
}
// C program for writing struct person input1 = { 1, "rohan", "sharma" };
// struct to file // write struct to file
#include <stdio.h> int flag = 0;
#include <stdlib.h> flag = fwrite(&input1, sizeof(struct person), 1,
// a struct to be read and written outfile);
struct person { if (flag) {
int id; printf("Contents of the structure written "
char fname[20]; "successfully");
char lname[20]; }
}; else
void main() printf("Error Writing to File!");
{
FILE* outfile; // close file
// open file for writing fclose(outfile);
outfile = fopen("person.bin", "wb"); }
if (outfile == NULL) {
fprintf(stderr, "\nError opened file\n");
exit(1);
}
// C program for reading struct person write_struct = { 1, "Rohan", "Sharma" };
// struct from a file
// writing to file
#include <stdio.h>
fwrite(&write_struct, sizeof(write_struct), 1, infile);
#include <stdlib.h>
// struct person with 3 fields struct person read_struct;
struct person { // setting pointer to start of the file
int id; rewind(infile);
char fname[20]; // reading to read_struct
char lname[20];
fread(&read_struct, sizeof(read_struct), 1, infile);
};
void main() printf("Name: %s %s \nID: %d", read_struct.fname,
{ read_struct.lname, read_struct.id);
FILE* infile; // close file
// Open person.dat for reading fclose(infile);
infile = fopen("person1.dat", "wb+"); }
if (infile == NULL) {
fprintf(stderr, "\nError opening file\n");
exit(1);
}
Read and Write in a Binary File
• Till now, we have only discussed text file operations. The operations on a binary file are similar to text file
operations with little difference.
• Opening a Binary File: To open a file in binary mode, we use the rb, rb+, ab, ab+, wb, and wb+ access mode in
the fopen() function.
• We also use the .bin file extension in the binary filename.
• fptr = fopen("filename.bin", "rb");
• We use fwrite() function to write data to a binary file. The data is written to the binary file in the from of bits (0’s
and 1’s).
• Syntax: size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *file_pointer);
ptr: pointer to the block of memory to be written.
size: size of each element to be written (in bytes).
nmemb: number of elements.
file_pointer: FILE pointer to the output file stream.
// C program to write to a Binary file using fwrite() int flag = 0;
#include <stdio.h> // else it will return a pointer to the file.
#include <stdlib.h> for (n = 1; n < 5; ++n) {
num.n1 = n;
struct threeNum {
num.n2 = 5 * n;
int n1, n2, n3; num.n3 = 5 * n + 1;
}; flag = fwrite(&num, sizeof(struct threeNum), 1,
void main() fptr);
{ }
int n;
// checking if the data is written
// Structure variable declared here. if (!flag) {
struct threeNum num; printf("Write Operation Failure");
FILE* fptr; }
if ((fptr = fopen("C:\\program.bin", "wb")) ==NULL) else {
{ printf("Write Operation Successful");
printf("Error! opening file"); }
fclose(fptr);
// If file pointer will return NULL
}
// Program will exit.
exit(1);
// C program to write to a Binary file using fwrite()
#include <stdio.h>
#include <stdlib.h>
struct threeNum { int n1, n2, n3; };
int main()
{ int n;
// Structure variable declared here.
struct threeNum num;
FILE* fptr;
if ((fptr = fopen("C:\\program.bin", "wb")) == NULL) { printf("Error! opening file");
// If file pointer will return NULL Program will exit.
exit(1);
}
int flag = 0;
for (n = 1; n < 5; ++n) {
num.n1 = n;
num.n2 = 5 * n;
num.n3 = 5 * n + 1;
flag = fwrite(&num, sizeof(struct threeNum), 1,fptr);
}
// checking if the data is written
if (!flag) { printf("Write Operation Failure"); }
else { printf("Write Operation Successful"); }
fclose(fptr);
// C Program to Read from a binary file using fread() // else it will return a pointer to the file.
#include <stdio.h> for (n = 1; n < 5; ++n) {
#include <stdlib.h> fread(&num, sizeof(struct
struct threeNum { threeNum), 1, fptr);
int n1, n2, n3; printf("n1: %d\tn2: %d\tn3: %d\n",
}; num.n1, num.n2,
int main() num.n3);
{ }
int n; fclose(fptr);
struct threeNum num;
FILE* fptr;
if ((fptr = fopen("C:\\program.bin", "rb")) == NULL) {
return 0;
printf("Error! opening file"); }
// If file pointer will return NULL
// Program will exit.
exit(1);
}
Random Access File in C
• Random access (or direct access) in a file refers to the ability to move the file
pointer to any position in the file, allowing reading from or writing to a specific
part of the file without having to sequentially read through the file.
• This is useful when you want to modify or retrieve data from any arbitrary location
in a file rather than reading or writing in order from the start.
• We can move forward or backward in a file using standard functions to simulate
random access.
Types of Access files: Sequential Access and Random Access
• Functions for moving around in a file are 1.fseek() 2.ftell() 3.rewind()
• ftell() is used to find the position of the file pointer from the starting of the file.
• Its syntax:ftell(FILE *fp)
• pos = ftell(FILE *fp);
• Where fp is a file pointer and pos holds the current position i.e., total bytes read (or written).
• For Example: If a file has 20 bytes of data and if the ftell() function returns 5 it means
that 5 bytes have already been read (or written).
• First, let us consider a file - Scaler.txt which contains the following data:
• Scaler is amazing
include<stdio.h>
void main() {
FILE *fp;
fp=fopen("scaler.txt","r");
if(!fp) {
printf("Error: File cannot be opened\n") ;
Exit(0);
}
//Since the file pointer points to the starting of the file, ftell() will return 0
printf("Position pointer in the beginning : %ld\n",ftell(fp));
char ch;
while(fread(&ch,sizeof(ch),1,fp)==1)
{
//Here, we traverse the entire file and print its contents until we reach its end.
printf("%c",ch);
}
printf("\nSize of file in bytes is : %ld\n",ftell(fp)); fclose(fp);
}
Output:
We can observe that in the beginning, ftell returns 0 as the pointer
Position pointer in the beginning : 0
points to the beginning and after traversing completely we print each
Scaler is amazing
character of the file till the end, and now ftell returns 17 as it is the siz
Size of file in bytes is : 17
of the file.
1.rewind() is used to move the file pointer to the beginning of the file.
• Syntax:rewind(FILE *fp)
Here, fp is a file pointer of type FILE.
#include<stdio.h>
int main() {
FILE *fp;
fp = fopen("scaler.txt","r");
if(!fp) {
printf("Error in opening file\n");
exit(0);
}
printf("Position of the pointer : %ld\n",ftell(fp));
char ch;
while(fread(&ch,sizeof(ch),1,fp)==1) {
printf("%c",ch);
}
printf("Position of the pointer : %ld\n",ftell(fp));
rewind(fp);
printf("Position of the pointer : %ld\n",ftell(fp)); fclose(fp);
}
Output:
Position of the pointer : 0
Scaler is amazing
Position of the pointer : 17
Position of the pointer : 0
• We can observe that firstly when ftell is called, it returns 0 as the position of the pointer is at
the beginning,
• then after traversing the file, when ftell is called, 17 is returned, which is the size of the file.
• Now when rewind(fp) is called, the pointer will move to its original position, which is 0. So
last ftell returns 0.
Fseek()
• The fseek() function moves the file position to the desired location
• syntax : int fseek(FILE *fp, long displacement, int origin);
fp - file pointer.
displacement - It indicates the number of bytes skipped from the third
argument's location either backward or forward. This long integer has
two possible values: positive and negative.
origin - It is where something is about a displacement. The three values stated
below are the ones it will accept.
Constant Value Position
SEEK_SET 0 Beginning of file
SEEK_CURRENT 1 Current position
SEEK_END 2 End of file
Operation Description
fseek(fp, 0, 0) This takes us to the beginning of the file.
fseek(fp, N, 1) This takes us N bytes forward from the current position in the file.
fseek(fp, -N, 1) This takes us N bytes backward from the current position in the file.
fseek(fp, -N, 2) This takes us N bytes backward from the end position in the file.
#include<stdio.h>
int main() {
FILE *fp;
fp = fopen("scaler.txt","r");
if(!fp) {
printf("Error: File cannot be opened\n");
Exit(0); }
//Move forward 6 bytes, thus we won't be seeing the first 6 bytes i
till the end.
fseek(fp, 6, 0);
char ch;
while(fread(&ch,sizeof(ch),1,fp)==1) {
//Here, we traverse the entire file and print its contents until w
end.
printf("%c",ch); }
fclose(fp);
return 0;
}
Output:
is amazing
• We can observe that when fseek(fp,6,0) the pointer moves to the 7th byte in the file, or we
can say 6 bytes forward from the beginning, So when we traverse the file from that position,
we receive output as is amazing.
UNIT - IV:
Function and Dynamic Memory Allocation:
Functions: Designing structured programs, Declaring a function, Signature of a function, Parameters and return type of a
function, passing parameters to functions, call by value, Passing arrays to functions, passing pointers to functions, idea of call by
reference, Some C standard functions and libraries
Recursion: Simple programs, such as Finding Factorial, Fibonacci series etc., Limitations of Recursive functions
Dynamic memory allocation: Allocating and freeing memory, Allocating memory for arrays of different data types
• A function is a set of statements are enclosed within { } braces that perform some
specific tasks.
• It is the basic building block of a C program that provides code reusability
• They are also called subroutines or procedures in other languages.
• Advantage of functions:
- Divide the program into sub programs which reduce the complexity
- code Reusability
Function Definition
• The function definition consists of actual statements which are executed when the function is called.
• return_type function_name (para1_type para1_name, para2_type para2_name)
{
// body of the function
}
int sum(int a, int b)
{
return a + b;
}
•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.
•Argument List − An argument (also called parameter) is like a placeholder. When a function is invoked,
you pass a value as a parameter. This value is referred to as the 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 defines what the function
does.
Function Call
• A function call is a statement that instructs the compiler to execute the function.
• We use the function name and parameters in the function call.
• In the below example, the first sum function is called and 10,30 are passed to the sum function.
• After the function call sum of a and b is returned and control is also returned back to the main function of the
program.
• Example for Function without argument and return value
#include<stdio.h>
void main ()
{void printName();
printf("Hello ");
printName();
}
void printName()
{ printf("Javatpoint"); }
#include<stdio.h>
int sum();
void main()
{
int result;
printf("\nGoing to calculate the sum of two numbers:");
result = sum();
printf("%d",result);
}
int sum()
{
int a,b;
printf("\nEnter two numbers");
scanf("%d %d",&a,&b);
return a+b;
}
Example for Function without argument and with return value
#include<stdio.h>
void main()
{
int square()
printf("Going to calculate the area of the square\n");
float area = square();
printf("The area of the square: %f\n",area);
}
int square()
{
float side;
printf("Enter the length of the side in meters: ");
scanf("%f",&side);
return side * side;
}
#include<stdio.h>
void main()
{
int a,b,result;
int sum(int, int);
printf("\nGoing to calculate the sum of two numbers:");
printf("\nEnter two numbers:");
scanf("%d %d",&a,&b);
result = sum(a,b);
printf("\nThe sum is : %d",result);
}
int sum(int a, int b)
{
return a+b;
}
Passing Parameters to Functions
• The data passed when the function is being invoked is known as the Actual parameters.
• In the below program, 10 and 30 are known as actual parameters.
• Formal Parameters are the variable and the data type as mentioned in the function declaration.
• In the below program, a and b are known as formal parameters.
• We can pass arguments to the C function in two ways: 1.Call by Value 2.Call by Reference
call by Value
• In call by value, a copy of the value is passed to the function and changes that are made to the function are not
reflected back to the values.
• Actual and formal arguments are created in different memory locations.
1 A copy of the value is passed into the function An address of value is passed into the function
3 Only one value is returned from called function More than one value is return from called function
Pass Arrays as Function Parameters
#include <stdio.h>
void myFunction(int a[5]) {
for (int i = 0; i < 5; i++) {
printf("%d\n", a[i]);
}
}
void main() {
int myNumbers[5] = {10, 20, 30, 40, 50};
myFunction(myNumbers);
}
Recursion
• Recursion is the technique of making a function call itself.
• This technique provides a way to break complicated problems down into simple problems which are
easier to solve.
• recursion is used to solve complex problems by breaking them down into simpler sub-problems. We can solve
large numbers of problems using recursion in C.
• For example, factorial of a number, generating Fibonacci series, generating subsets, etc.
#include <stdio.h>
int fact (int);
int main() {
int n,f;
printf("Enter the number whose factorial you want to calculate?");
scanf("%d",&n);
f = fact(n);
printf("factorial = %d",f);
}
int fact(int a)
{
if (a==0 || a==1 )
return 1;
else
return a*fact(a-1);
}
1.#include<stdio.h>
2.int fibonacci(int);
3.void main ()
4.{
5. int n,f;
6. printf("Enter the value of n?");
7. scanf("%d",&n);
8. f = fibonacci(n);
9. printf("%d",f);
10.}
11.int fibonacci (int n)
12.{
13. if (n==0)
14. {
15. return 0;
16. }
17. else if (n == 1)
18. {
19. return 1;
20. }
21. else
22. {
23. return fibonacci(n-1)+fibonacci(n-2);
24. }
25.}
• The process of reserving memory is called allocation.
• The way to allocate memory depends on the type of memory.
• C has two types of memory: Static memory and dynamic memory.
Static Memory
• Static memory is memory that is reserved for variables before the program runs. Allocation of static
memory is also known as compile time memory allocation.
• C automatically allocates memory for every variable when the program is compiled.
• For example, if you create an integer array of 20 students (e.g. for a summer semester), C will
reserve space for 20 elements which is typically 80 bytes of memory (20 * 4):
#include <stdio.h>
void main() {
int students[20];
printf("%lu", sizeof(students)); // 80 bytes
}
• But when the semester starts, it turns out that only 12 students are attending. Then you have
wasted the space of 8 unused elements.
• Since you are not able to change the size of the array, you are left with unnecessary reserved
memory.
• If you want better control of allocated memory, take a look at Dynamic Memory below.
Dynamic Memory
• Dynamic memory is memory that is allocated after the program starts
running. Allocation of dynamic memory can also be referred to
as runtime memory allocation.
• Unlike with static memory, you have full control over how much memory is
being used at any time. You can write code to determine how much
memory you need and allocate it.
• Dynamic memory does not belong to a variable, it can only be accessed
with pointers.
• The concept of dynamic memory allocation in c language enables the C
programmer to allocate memory at runtime.
• Dynamic memory allocation in c language is possible by 4 functions of
stdlib.h header file:
1.malloc()
2.calloc()
3.realloc()
4.free()
static memory allocation dynamic memory allocation
memory is allocated at compile time. memory is allocated at run time.
memory can't be increased while executing program. memory can be increased while executing program.
used in array. used in linked list.
malloc() Function
• The “malloc” or “memory allocation” method in C is used to dynamically allocate a single large block of memory
with the specified size.
• It returns a pointer of type void which can be cast into a pointer of any form.
• Syntax: ptr = (cast-type*) malloc(byte-size)
• ptr = (int*) malloc(100 * sizeof(int));
Since the size of int is 4 bytes, this statement will allocate 400 bytes of memory. And, the pointer ptr holds the
address of the first byte in the allocated memory.
1.#include<stdio.h>
2.#include<stdlib.h>
Void main(){
1. int n,i,*ptr,sum=0;
2. printf("Enter number of elements: ");
3. scanf("%d",&n);
4. ptr=(int*)malloc(n*sizeof(int)); //memory allocated using malloc
5. if(ptr==NULL)
6. {
7. printf("Sorry! unable to allocate memory");
8. exit(0);
9. }
10. printf("Enter elements of array: ");
11. for(i=0;i<n;++i)
12. {
13. scanf("%d",ptr+i);
14. sum+=*(ptr+i);
15. }
16. printf("Sum=%d",sum);
17. free(ptr);
18.}
calloc() function in C
• “calloc” or “contiguous allocation” method in C is used to dynamically allocate the specified number
of blocks of memory of the specified type.
• it is very much similar to malloc() but has two different points and these are:
• It initializes each block with a default value ‘0’.
• It has two parameters or arguments as compare to malloc().
• Syntax: ptr = (cast-type*)calloc(n, element-size);
here, n is the no. of elements and element-size is the size of each element.
• ptr = (float*) calloc(25, sizeof(float));
This statement allocates contiguous space in memory for 25 elements each with the size of the float.
• start from the first element and compare K with each element of the array.
• The value of K, i.e., 41, is not matched with the first element of the array. So, move to the next element.
And follow the same process until the respective element is found.
Now, the element to be searched is found. So algorithm will return the index of the element matched.
• Binary search is the search technique that works efficiently on sorted lists.
• Hence, to search an element into some list using the binary search technique, we must ensure that the list is
sorted.
• Binary search follows the divide and conquer approach in which the list is divided into two halves, and the item is
compared with the middle element of the list.
• If the match is found then, the location of the middle element is returned.
• Otherwise, we search into either of the halves depending upon the result produced through the match.
• First Pass: Sorting will start from the initial two elements. Let compare them to check which is greater.
• Here, 32 is greater than 13 (32 > 13), so it is already sorted. Now, compare 32 with 26.
• Here, 26 is smaller than 36. So, swapping is required. After swapping new array will look like
• Here, 35 is greater than 32. So, there is no swapping required as they are already sorted.
• Now, the comparison will be in between 35 and 10.
• Here, 10 is smaller than 35 that are not sorted. So, swapping is required. Now, we reach at the end of
the array. After first pass, the array will be –
• Here, 10 is smaller than 32. So, swapping is required. After swapping, the array will be
Here, 31 is greater than 12. That means both elements are already in ascending order. So, for now, 12 is
stored in a sorted sub-array.
Step 1: We start with an unsorted array.
[ 7, 12, 9, 11, 3]
Step 2: We can consider the first value as the initial sorted part of the array. If it is just one
value, it must be sorted, right?
[ 7, 12, 9, 11, 3]
Step 3: The next value 12 should now be moved into the correct position in the sorted part
of the array. But 12 is higher than 7, so it is already in the correct position.
[ 7, 12, 9, 11, 3]
Step 4: Consider the next value 9.
[ 7, 12, 9, 11, 3]
Step 5: The value 9 must now be moved into the correct position inside the sorted part of
the
array, so we move 9 in between 7 and 12.
[ 7, 9, 12, 11, 3]
Step 6: The next value is 11.
[ 7, 9, 12, 11, 3]
Step 7: We move it in between 9 and 12 in the sorted part of the array.
[ 7, 9, 11, 12, 3]
Step 8: The last value to insert into the correct position is 3.
[ 7, 9, 11, 12, 3]
Step 9: We insert 3 in front of all other values because it is the lowest value.
[ 3,7, 9, 11, 12]
Selection Sort Algorithm
• 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.
• 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.
Step 1: We start with an unsorted array.
[ 7, 12, 9, 11, 3]
Step 2: Go through the array, one value at a time. Which value is the lowest? 3, right?
[ 7, 12, 9, 11, 3]
Step 3: Move the lowest value 3 to the front of the array.
[ 3, 7, 12, 9, 11]
Step 4: Look through the rest of the values, starting with 7. 7 is the lowest value, and
already at the front of the array, so we don't need to move it.
[ 3, 7, 12, 9, 11]
At present, 12 is stored at the first position, after searching the entire array, it is found that 8 is
the smallest value.
So, swap 12 with 8. After the first iteration, 8 will appear at the first position in the sorted array.
For the second position, where 29 is stored presently, we again sequentially scan the rest
of the items of unsorted array. After scanning, we find that 12 is the second lowest element
in the array that should be appeared at second position.
Now, swap 29 with 12. After the second iteration, 12 will appear at the second position in the
sorted array. So, after two iterations, the two smallest values are placed at the beginning in a
sorted way.
The same process is applied to the rest of the array elements. Now, we are showing a pictorial
representation of the entire sorting process
What is Time complexity?
• Understanding time complexity in algorithm is similar to planning the best route for a road
trip.
• Just as you'd consider various factors like distance, traffic, and road conditions to estimate
travel time and fuel consumption, time complexity helps programmers estimate how long an
algorithm will take to process data based on its size.
• This concept is crucial for creating efficient software projects that can handle large amounts
of data smoothly and quickly
• Moreover, time complexity helps programmers predict the performance of their code and
choose the best algorithm for the task at hand.
• Time complexity is defined as the amount of time taken by an algorithm to run, as a function
of the length of the input.
• It measures the time taken to execute each statement of code in an algorithm.
• It aids in our analysis of the algorithm's performance scaling with increasing
input size.
• It is not going to examine the total execution time of an algorithm.
Best, Worst, and Average Case Complexity:
In analyzing algorithms, we consider three types of time complexity:
1.Best-case complexity (O(best)): This represents the minimum time required for an algorithm to
complete when given the optimal input. It denotes an algorithm operating at its peak efficiency under
ideal circumstances.
2.Worst-case complexity (O(worst)): This denotes the maximum time an algorithm will take to finish
for any given input. It represents the scenario where the algorithm encounters the most unfavourable
input.
3.Average-case complexity (O(average)): This estimates the typical running time of an algorithm when
averaged over all possible inputs. It provides a more realistic evaluation of an algorithm's performance.
#include <stdio.h>
void linear_search(int a[], int n, int key){
int i, count = 0;
for(i = 0; i < n; i++) {
if(a[i] == key) { // compares each element of the array
printf("The element is found at %d position\n", i+1);
count = count + 1; }
}
if(count == 0) // for unsuccessful search
printf("The element is not present in the array\n");
}
void main(){ int i, n, key; n = 6;
int a[10];
Print(“Enter the number of elements in the array”);
Scanf(“%d”,&n);
For(i=0;i<n;i++){
Printf(“Enter the %d elemet in the element in the array”,i);
Scanf(“%d”,&a[i]);
}
Printf(“Element to be searched”);
Scanf(“%d”,&key);
linear_search(a, n, key);
#include <stdio.h>
void insertionSort(int arr[], int n) {
int i, key, j;
for (i = 1; i < n; i++) {
key = arr[i];
j = i - 1;
void main() {
int arr[] = { 12, 11, 13, 5, 6 };
int n = sizeof(arr) / sizeof(arr[0]);
insertionSort(arr, n);
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
}
#include <stdio.h>
void selection(int arr[], int n) {
int i, j, small;
for (i = 0; i < n-1; i++) //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 main() {
int a[] = { 12, 31, 25, 8, 32, 17 };
int i;
int n = sizeof(a) / sizeof(a[0]);
selection(a, n);
printf("\nAfter sorting array elements are - \n");
for (i = 0; i < n; i++)
printf("%d ", a[i]);
}
To insert a sub-string into a given main string from a given position
#include<stdio.h>
#include<conio.h>
#include<string.h> Output
void main() { Enter the string 1 sachin
char str1[20], str2[20]; Enter the string 2 tendulkar
int l1, l2, n, i; Enter the position where the string is to be inserted 4
puts("Enter the string 1\n"); After inserting the string is sachtendulkarin
gets(str1); l1 = strlen(str1);
puts("Enter the string 2\n");
gets(str2); l2 = strlen(str2);
printf("Enter the position where the string is to be inserted\n");
scanf("%d", &n);
for(i = n; i < l1; i++)
{
str1[i + l2] = str1[i];
}
for(i = 0; i < l2; i++)
{
str1[n + i] = str2[i];
}
str2[l2 + 1] = '\0’;
printf("After inserting the string is %s", str1);
}
To delete n Characters from a given position in a given string.
#include<stdio.h> Output
#include<string.h> Enter the string Sachin
void main() { Enter the position where characters are to be deleted 2
char str[20]; Enter the number of characters to be deleted 2
int i, n, l, pos;
The string is sain
puts("Enter the string\n");
gets(str);
printf("Enter the position where the characters are to be deleted\n");
scanf("%d", &pos);
printf("Enter the number of characters to be deleted\n");
scanf("%d", &n);
l = strlen(str);
for(i = pos + n; i < l; i++)
{
str[i - n] = str[i];
}
str[i - n] = '\0’;
printf("The string is %s", str);
}
Write a C program to determine if the given string is a palindrome or not
#include <stdio.h> #include <string.h>
void main()
{
char str[10] = "naman";
int i, len, flag = 0;
len = strlen(str);
for (i = 0; i < len; i++)
{ // Checking if string is palindrome or not
if (str[i] != str[len - i - 1]) {
flag = 1;
break;
}
}
if (flag)
printf("%s is not palindrome", str);
else
printf("%s is palindrome", str);
}
Write a C program that displays the position of a string ch in the string S or – 1 if S doesn„t contain
#include<stdio.h>
#include<string.h>
#include<conio.h>
void main() {
char s[30], t[20];
char *found;
puts("Enter the first string: ");
gets(s);
puts("Enter the string to be searched: ");
gets(t);
found = strstr(s, t);
if(found)
{ printf("Second String is found in the First String at %d position.\n", found - s); }
else
{ printf("-1"); }
}
Write a C program to count the lines, words and characters in a given text.
#include <stdio.h>
void main() { long ctr_char, ctr_word, ctr_line;
// Variables to count characters, words, and lines
int c; // Variable to hold input characters
int flag; // Flag to track word boundaries
ctr_char = 0; // Initialize the count of characters
flag = ctr_line = ctr_word = 0; // Initialize flag and counts for words and lines
printf("Input a string and get number of characters, words and lines:\n");
// Loop to read characters until end-of-file (EOF) is encountered
while ((c = getchar()) != EOF) {
++ctr_char; // Increment the count of characters
if (c == ' ' || c == '\t') {
flag = 0; // Reset the flag when a space or tab is encountered } else if (c == '\n') {
++ctr_line; // Increment the count of lines
flag = 0; // Reset the flag on a newline }
else { if (flag == 0) { ++ctr_word; // Increment the count of words when a new word begins }
flag = 1; // Set the flag to indicate a word is in progress } }
// Print the counts of characters, words, and lines
printf("\nNumber of Characters = %ld", ctr_char);
printf("\nNumber of words = %d", ctr_word);
printf("\nNumber of lines = %d", ctr_line); }
1.Write a C program to read character by character from a file
2. Write a C program to read string by string from a file
3. Write a C program to read formatted string by string from a file
4. Write a C program to write character by character into a file
5. Write a C program to write string by string into a file
6. Write a C program to write character by character into a file
7. Write a C program to write formatted string by string into a file
8. Write a C program which copies one file to another
9. Write a C program to merge two files into a third file (i.e., the contents of the first file followed by those of the second are put
in the third file).