DTU B.tech 1st Year CO LAB FILE
DTU B.tech 1st Year CO LAB FILE
UNIVERSITY
INTRODUCTION:
The program accepts a value from the user and divides it with 10 and stores the remainder
and then the number in its integer form is reduced by the factor of 10 and the process is
repeated. This is carried out as long as the number reduced by the factor of 10 is greater 0
after reduction.
ALGORITHM:
Step-1: Start
[End of loop]
Step-7: End
CODE:
#include<stdio.h>
int main()
int n,rem,sum=0;
printf("Enter a number:\n");
scanf("%d",&n);
while(n>0)
rem=n%10;
sum=sum+rem;
n=n/10;
return 0;
Output:
We learned how to use while loop to read the digits of a number and to find its sum.
INTRODUCTION:
This program reverse the number entered by the user and then prints the reversed
number on the screen. For example if user enter 12345 as input then 54321 is printed as
output. -In our program we use modulus(%) operator to obtain the digits of a number. To
invert number look at it and write it from opposite direction or the output of code is a
number obtained by writing original number from right to left.
ALGORITHM:
Step 1: Start
Step 2: Read: Take input for n
Step 3: [Initialize] reverse = 0
Step 4: [Check Value] If n > 0 then:
[Compute] rem = n%10
reverse = reverse*10 + rem and n = n/10]
[Repeat loop] Go to Step 4.
[End of If Structure]
Step 5: Print: reverse
Step 6: Exit
CODE:
#include<stdio.h>
int main()
int n,rem,rev=0;
while(n>0)
rem=n%10;
rev=rev*10+rem;
n=n/10;
return 0;
OUTPUT:
INTRODUCTION:
Decimal to Binary conversion involves a number getting divided by 2 and the remainder
noted, now the quotient of previous calculation is treated as a decimal and the process is
repeated. As long as quotient is either 0 or 1, this process is repeated. The remainders are
noted together and the reverse of this is the binary form of given decimal number.
Binary to Decimal conversion: The total number of terms in binary is noted, say n. To get
decimal, the first term is multiplied by 2n-1, second by 2n-2, and so on till n=1. The sum of all
these is taken and the resulting number is the decimal.
ALGORITHM:
CODE:
#include<stdio.h>
#include<math.h>
#include<conio.h>
int main()
int choice,dec=0,i=0,rem;
scanf("%d",&choice);
if(choice==1)
scanf("%d",&dec);
while(dec!=0)
rem=dec%2;
binary=binary+rem*pow(10,i++);
dec=dec/2;
if(choice==2)
scanf("%d",&binary);
while(binary!=0)
rem=binary%10;
dec=dec+rem*pow(2,i++);
binary=binary/10;
return 0;
OUTPUT:
We learned the steps required for conversion of binary numbers to decimal numbers and
vice versa.
Also the use of while loop for repetition and basic mathematical operations provided by C.
INTRODUCTION:
The switch() case in C programming allows case based programming. The user’s response
to test statement in the parentheses with ‘switch’ case gives the outcome associated with
that response.
ALGORITHM:
Step1: Start
Step4: Read input and execute the statement associated with that input
Step5: If no statement is associated with the given input, print “Out of range”
Step6: End
CODE:
#include<stdio.h>
void main()
int n;
scanf("%d",&n);
switch(n)
break;
break;
break;
break;
break;
default:
printf("Out of range!!");
break;
OUTPUT:
We learned how to use switch statements to make a menu driven program which can be
used as an efficient replacement of if else nested loops for certain cases.
INTRODUCTION:
Fibonacci series is defined as a sequence of numbers in which the first two numbers are 1
and 1 and each subsequent number is the sum of the previous two. So, in this series, the
Mathematically, the nth term of the Fibonacci series can be represented as:
tn = tn-1 + tn-2
The Fibonacci sequence upto certain term can be represented as: 1, 1, 2, 3, 5, 8, 13, 21,
34…
ALGORITHM:
STEP 1. Start
Print fib
STEP 7. End
CODE:
#include<stdio.h>
int i,n,fib=1,t1=0,t2=1;
scanf("%d",&n);
for(i=1;i<=n;i++)
printf("%d ",fib);
fib=t1+t2;
t1=t2;
t2=fib;
return 0;
OUTPUT:
INTRODUCTION:
ex = ∑
ALGORITHM:
Step1: Start
Step2: Declare integer variables i and n and float variables x t and sum
[End loop]
Step6: End
CODE:
#include<stdio.h>
#include<conio.h>
int main()
int n,i;
float x,t=1,sum=1;
scanf("%f",&x);
scanf("%d",&n);
for(i=1;i<=n;i++)
t=t*x/i;
sum=sum+t;
return 0;
We learned about exponential series and how to form series in programming language to
calculate exact value of a function.
INTRODUCTION:
Linear search or sequential search is a method for finding a particular value in a list, that
consists of checking every one of its elements, one at a time and in sequence, until the
desired one is found.
ALGORITHM:
1. START
2. Declare an integer array and its size
3. Enter elements in array one by one
4. Enter the element to be found
5. Using for loop check each element in the array sequentially
6. If found, print ‘Number is present’ and its position in the array
7. END
CODE:
#include <stdio.h>
void main()
int array[10];
scanf("%d", &n);
scanf("%d", &array[i]);
scanf("%d", &keynum);
if (keynum == array[i] )
found = 1;
break;
if (found == 1){
else
We learned how to search elements of an array. We also learned how for loop can be used
to read elements in an array one by one.
INTRODUCTION:
ALGORITHM:
1. START
2. Enter the size of array, say n
3. Declare an array, ‘array’ of given size
4. Begin for i=0 to n-1
Input array[i], elements of the array
End for
5. Sort the array using BubbleSort
6. Enter number to be searched
7. Compare the number with the middle element of the array(sub array)
8. If number is equal, go to step 11, if not go to step 9
9. If number is smaller than the middle value, consider half of the array containing
smaller values and go to step 7
10. If number is greater than the middle value, consider half of the array containing
larger values and go to step 7
11. Print the position of the number.
12. If not found print “SEARCH FAILED!”
13. END
CODE:
void main()
int array[10];
scanf("%d", &n);
scanf("%d", &array[i]);
{
2K19/A4/11 Farhan Raja Page 24
temp = array[j];
array[j + 1] = temp;
printf("%d\n", array[i]);
scanf("%d", &keynum);
low = 1;
high = n;
do
high = mid - 1;
low = mid + 1;
else
OUTPUT:
We learned about Binary search of elements in the array. We also learned how to Bubble
sort array.
INTRODUCTION:
Bubble sort, sometimes referred to as sinking sort, is a simple sorting algorithm that
repeatedly steps through the list to be sorted, compares each pair of adjacent items and
swaps them if they are in the wrong order. The pass through the list is repeated until no
swaps are needed, which indicates that the list is sorted. The algorithm, which is a
comparison sort, is named for the way smaller or larger elements "bubble" to the top of the
list.
ALGORITHM:
Step 1: START
Step 2: Repeat Steps 2 and 3 for i=1 to 10
Step 3: Set j=1
Step 4: Repeat while j<=n
(A) if array[i] < array[j]
Then interchange array[i] and array[j]
[End of if]
(B) Set j = j+1
[End of Inner Loop]
[End of Step 1 Outer Loop]
Step 5: END
CODE:
#include <stdio.h>
void main()
{
int array[20];
int i, j, n , temp;
OBJECT:
Program to sort an array using Selection sort.
INTRODUCTION:
Selection sort algorithm sorts an array by repeatedly finding the minimum element
(considering ascending order) from unsorted part and putting it at the beginning. The
algorithm maintains sub arrays in a given array.
ALGORITHM:
STEP 1: Start
[End of if]
STEP 8: Stop
printf("\nUnsorted data:\n");
for(i=1;i<=size;i++)
printf("%d\t",arr[i]);
selsort(size, arr);
}
void selsort(int n, int arr[])
{ int i, j, min, temp;
printf("\nSorted List is:\n");
for(i=1;i<=n-1;i++)
{
min = i;
for(j=i+1;j<=n;j++)
{
if(arr[j]<arr[min])
min = j;
}
temp=arr[i];
arr[i]=arr[min];
arr[min]=temp;
}
OUTPUT:
OBJECT:
Program to sort an array using insertion sort:
INTRODUCTION:
This is an in-place comparison -based sorting algorithm. Here, a sub-list is
maintained which is always sorted. For example, the lower part of an array is
maintained to be sorted. An element which is to be
'insert'ed in this sorted sub-list, has to find its appropriate place and then it
has to be inserted there.
Hence the name, insertion sort.
ALGORITHM:
CODE:
#include<stdio.h>
#include<conio.h>
void main()
{
int n, array[1000], c, d, t;
INTRODUCTION:
The product of positive integers from 1 to N is called factorial N. It can also be defined as
the factorial of a number N is defined as the product of first N Natural Numbers. Factorial N
is denoted by N!
Where,
N! = 1.2.3.4.5………(N-2)(N-1).N
This function is defined for all positive integers including 0. Factorial of some
positive integers are given below.
0! = 1
1! = 1
2! = 2.1 = 2
3! = 3.2.1 = 6
4! = 4.3.2.1 = 24
ALGORITHM:
1. START
2. Declare a recursive function factorial()
3. Take input, n
4. If n=1 or n=0, return 1
Else return n*factorial(n-1)
5. Print the value of n!
6. END
#include<stdio.h>
int factorial(int);
int main(){
int num,f;
scanf("%d",&num);
f=factorial(num);
return 0;
//recursive function
if(n==1 || n==0)
return 1;
else
OUTPUT:
We learned about recursive functions and how to use them in programs to make it more
portable.
INTRODUCTION:
ALGORITHM:
CODE:
#include <stdio.h>
/*
*/
// main function
int main()
int i,length=0;
char string[100];
printf("Enter a string:\n");
gets(string);
length++;
string_function(string);
return 0;
We learned how to pass string to a function and we also learned how to find length of a
sting using for loop.
INTRODUCTION:
C program to count number of vowels in a string: for example, in the string "love" there are
two vowels 'o' and 'e'. In the program both lower and upper case are considered i.e., 'a', 'A',
'e', 'E', 'i', 'I', 'o', 'O', 'u' and 'U'. In this program we check every character in the input string, if
it's a vowel then counter is incremented by one, consonants and special characters are
ignored.
ALGORITHM:
CODE:
#include<stdio.h>
int main()
char string[100];
printf("Enter a string:");
gets(string);
if(string[i] == 'a'||string[i]=='A')
{ count_a++;}
if(string[i] == 'e'||string[i]=='E')
{count_e++;}
if(string[i] == 'i'||string[i]=='I')
{count_i++;}
if(string[i] == 'o'||string[i]=='O')
{count_o++;}
if(string[i] == 'u'||string[i]=='U')
{count_u++;}
i++;
return 0;
}
2K19/A4/11 Farhan Raja Page 42
OUTPUT:
We learned how to count certain characters in a string and also how to use basic logical
operators in a program.
INTRODUCTION:
Palindromes are words or phrases that read the same in both directions.
ALGORITHM:
CODE:
#include <stdio.h>
#include <string.h>
int main(){
char string[50];
int i, length;
int flag = 0;
printf("Enter a string:");
scanf("%s", string);
length = strlen(string);
if (flag) {
printf("%s is not a palindrome", string);
}
else {
printf("%s is a palindrome", string);
}
return 0;
}
OUTPUT:
We learned about palindromes. We also learned about strlen function and how to iterate to
check given word is palindrome or not.
INTRODUCTION:
ALGORITHM:
CODE:
#include<stdio.h>
int main()
gets(str1);
gets(str2);
str1[i] = str2[j];
str1[i] = '\0';
return 0;
OUTPUT:
We learned string properties and how to concatenate two strings without using strcat(), but
using for loop.
INTRODUCTION:
This program prompts the user to enter two strings and check whether the two strings are
same or have same length or not using a for loop.
ALGORITHM:
1. START
2. Declare two char arrays named string1 and string2 to store the strings
entered by the user.
3. Input 2 strings
4. Find length of the two strings. If they are same print same length and go
to step 5 if not print strings are not same, end program
5. Using a for loop form i=0 to i<length check if every character of the two
string is same or not if same print same if not print not same
6. END
CODE:
#include<stdio.h>
#include<string.h>
int main()
gets(string1);
gets(string2);
x=strlen(string1);
y=strlen(string2);
if(x!=y)
exit(0);
else
if(string1[i] != string2[i])
flag=1;
if(flag==1)
else
return 0;
OUTPUT:
We also learned how to compare to strings and check if they are same or not.
INTRODUCTION:
Reverse of string
First we calculate the length of string using strlen function and then assigns characters of
input string in reverse order to create a new string using a for loop.
So, this program reverses a string entered by the user. For example if a user enters a
string "reverse me" then on reversing the string will be "em esrever".
ALGORITHM:
Step 1: Start
Step 2: Length = 0
Step 3: Repeat step 4 while string[length] ≠ NULL
Step 4: length = length + 1
Step 5: Return length
Step 6: Take 2 Subscript Variables i, j
Step 7: j is positioned on Last Character
Step 8: i is positioned on first character
Step 9: string[i] is interchanged with string[j]
Step 10: Increment i
Step 11: Decrement j
Step 12: If i > j then goto step 3
Step 13: Stop
CODE:
#include<stdio.h>
int main()
int length,i,j=length;
char string[100];
gets(string);
length = strlen(string);
printf("%c",string[i]);
return 0;
OUTPUT:
From this experiment we learn how to effectively reverse a string using a for loop.
Program to convert a string from lower case to upper case and vice versa.
INTRODUCTION:
This program converts the case of each letter that is upper to lower and vice versa.
The logic to convert lower to upper: subtract 32 with lower case letter.
Example:
convert a to A
=> a – 32
=> 97 – 32
=> 65
And 65 is ASCII value of A
ALGORITHM:
CODE:
#include<stdio.h>
#include<string.h>
void main()
char str[100];
int i;
gets(str);
for (i=0;i<=strlen(str);i++)
if (str[i]>='A'&&str[i]<='Z')
OUTPUT:
From this experiment we learn how to change the string from lower to upper case and vice
versa by using ASCII value and changing them accordingly.
INTRODUCTION:
The program prompts the user to enter elements of the first matrix and then the elements of
the other matrix. It then adds the corresponding elements and displays the addition matrix
as the output.
ALGORITHM:
1. START
2. Create 3 2-d integer arrays viz., first, second and sum
First two arrays to store the values entered by the user and sum array to store the
final addition matrix.
3. Declare variables c and d of type integer
4. Input the values
5. Use two for loops add the corresponding elements of the two arrays and store them
at their respective positions in the sum array.
6. Print the elements of the sum array
7. END
CODE:
#include <stdio.h>
int main()
scanf("%d", &first[c][d]);
printf("\n");
scanf("%d", &second[c][d]);
printf("%d\t", sum[c][d]);
printf("\n");
return 0;
OUTPUT:
From this experiment we learned how to create a 2-d array. We also learn how to store
values in a 2-d array and also how to add the corresponding elements of the two arrays and
store the array in another array.
INTRODUCTION:
This program asks the user to enter the size (rows and columns) of two matrices.
To multiply two matrices, the number of columns of the first matrix should be equal to the
number of rows of the second matrix.
The program below asks for the number of rows and columns of two matrices until the
above condition is satisfied.
Then, the multiplication of two matrices is performed, and the result is displayed on the
screen.
ALGORITHM:
Step 1: START
Step 2: Enter the row and column of the first (a) matrix.
Step 3: Enter the row and column of the second (b) matrix.
Step 9: Multiply the first (a) and second (b) matrix and store the element in the third matrix
(c)
CODE:
#include <stdio.h>
void main()
int a[25][25],b[25][25],c[25][25],i,j,k,r,s;
int m,n;
scanf("%d%d",&m,&n);
scanf("%d%d",&r,&s);
if(m!=r)
else
for(i= 0;i<m;i++)
for(j=0;j<n;j++)
scanf("\t%d",&a[i][j]);
for(j=0;j<n;j++)
scanf("\t%d",&b[i][j]);
for(i=0;i<m;i++)
printf("\n");
for(j=0;j<n;j++)
c[i][j]=0;
for(k=0;k<m;k++)
c[i][j]=c[i][j]+a[i][k]*b[k][j];
for(i=0;i<m;i++)
printf("\n");
for(j=0;j<n;j++)
printf("\t%d",c[i][j]);
}
2K19/A4/11 Farhan Raja Page 62
}
OUTPUT:
From this experiment we learned how to create a 2-d array. We also learn how to store
values in a 2-d array and also how to multiply elements of the two matrix arrays and store
the array in another array.
INTRODUCTION:
The program prompts the user to enter 2 numbers and the swaps numbers using pointers
Pointer: Pointer in C language is a variable that stores/points the address of another
variable. A pointer in C is used to allocate memory dynamically i.e. at run time. The pointer
variable might be belonging to any of the data type.
Pointer syntax: data_type *var_name;
where * is used to denote that var_name is a pointer variable.
ALGORITHM:
1. START
2. Declare variables a and b of integer type
3. Input the numbers
4. Store the location of a and b inpointer variables ptra and ptrb respectively
5. Perform following algorithm:
temp = *ptra; temp stores the value at location ptra
*ptra = *ptrb; assigning value at location ptrb to ptra
*ptrb = temp; assign value of themp to the variable at location ptrb
6. Print the values of a and b
7. END.
CODE:
#include<stdio.h>
int main()
{
int a, b;
int *ptra, *ptrb;
ptra = &a;
ptrb = &b;
temp = *ptra;
*ptra = *ptrb;
*ptrb = temp;
return 0;
OUTPUT:
We learned how to declare and use pointers. We also learned how to swap numbers using
pointers and how to pass address of variables to pointers.
INTRODUCTION:
o store employees details we used structure array. Each element in the structure array
represents the single employee.
Name
Id
Salary
Age
After taking input, we simply printed all employee details by iterating using for loop.
ALGORITHM:
1. START
2. Define structure employee with required data in it
3. Enter number of employees
4. Enter details of name, age, id, salary.
5. Then print the details using dot(‘.’) notation
6. END
CODE:
#include<stdio.h>
int id,age,salary;
char name[25];
}emp[100];
void main()
int i,n;
scanf("%d",&n);
for(i=0;i<n;i++)
printf("ID: ");
scanf("%d",&emp[i].id);
printf("Name: ");
scanf("%s",&emp[i].name);
printf("Age: ");
scanf("%d",&emp[i].age);
printf("Salary: ");
scanf("%d",&emp[i].salary);
2K19/A4/11 Farhan Raja Page 68
}
printf("\n====================EMPLOYEE DETAILS======================");
printf("\nID\t\tNAME\t\tAGE\t\tSALARY\n");
for(i=0;i<n;i++)
printf("%d\t\t%s\t\t%d\t\t%d\n",emp[i].id,emp[i].name,emp[i].age,emp[i].salary);
OUTPUT:
From this experiment we learned about structures in C and about its use as well.
Program to find area and perimeter of a circle, rectangle, square and triangle using
functions.
INTRODUCTION:
This program is used to find the perimeter of a circle, rectangle and triangle. The formula
used in this program are:
perimeter of rectangle: 2 * (a + b)
perimeter of circle: 2 * pi * r
ALGORITHM:
1. START
2. Create functions for area and perimeter of different figures of type float with
required variables
3. Declare variables length, breadth, radius, area, perimeter, a, b, c of type float
4. Take input regarding the figure
5. Using switch statement, calculate the area and perimeter of the required figure by
passing the values to the functions.
6. Display the values of area and perimeter
7. END
CODE:
#include<stdio.h>
#include<stdlib.h>
void main()
while(1)
int fig_code;
printf("\n========================================\n");
printf("\nPress 0 to exit!");
2K19/A4/11 Farhan Raja Page 71
printf("\n========================================\n");
scanf("%d", &fig_code);
switch(fig_code)
case 1:
scanf("%f",&radius);
perimeter = per_circle(radius);
area = area_circle(radius);
break;
case 2:
scanf("%f", &length);
scanf("%f", &breadth);
case 3:
scanf("%f", &side);
perimeter = per_square(side);
area = area_square(side);
break;
case 4:
break;
case 0:
exit(0);
break;
default:
}
2K19/A4/11 Farhan Raja Page 73
}
float per_circle(float r)
return perimeter;
float area_circle(float r)
return perimeter;
return area;
float per_square(float l)
{
2K19/A4/11 Farhan Raja Page 74
float perimeter = 4*l;
return perimeter;
float area_square(float l)
return area;
return perimeter;
float s = 0.5*(a+b+c);
return area;
We learned more about switch case statements and functions together in a program. We
also learned about passing variables to a function and returning the value from the
function and storing it in another variable.
Write a program to pass and return pointer to a function and hence calculate the
average of an array.
INTRODUCTION:
The program prompts the user to enter values of elements of the array and calculates
the average of the array by using pointers and displays it as the output.
ALGORITHM:
1. START
2. Create a pointer variable a, which points to an integer data.
3. Now, create another variable n (size of array) and a variable total=0, which will
stpre total sum of all the elements of the array.
4. Now create size_of_array(n)*size_of_each_element(integer) times space using
malloc() function, assigning the starting address of this space to the pointer variable,
a.
5. Using for loop (0 to n), start iteration, reach at every array element location by
adding the value of I to the value of a, taking array element as input.
6. Again start iteration, this time reach at each array element location, and accessing
them to add to the total variable
7. Using total, calculate the average of the array
8. Print average
9. END
CODE:
/*
C program to find the sum of all elements of an array using pointers as arguments.
*/
#include<malloc.h>
void main()
int array[20];
int i,total=0,n;
int *a;
scanf("%d",&n);
a = (int *)malloc(n*sizeof(int));
scanf("%d",a+i);
{
2K19/A4/11 Farhan Raja Page 78
total += *(a + i);
OUTPUT:
From this experiment we learned about pointers. We learn how to calculate the sum of
elements of an array using pointers. We also learn about the malloc function. In C, the
library function malloc is used to allocate a block of memory on the heap. The program
accesses this block of memory via a pointer that malloc returns.
Write a program to pass an array as pointer to a function that calculates the sum of all
the elements of the array.
INTRODUCTION:
Just like variables, array can also be passed to a function as an argument using pointers.
The program calls a function to add all the element of an array and passes the array
argument as a pointer. The program should dynamically allocate a piece of memory for
that array and use a pointer to point to that array memory as well as traverse that array
using a pointer.
ALGORITHM:
1. START
2. Declare an array of some size.
3. Take a variable sum, which will store the total sum of all the array elements.
4. Create a function with a single argument, in which we will pass the above created
array argument. This function will return the sum.
5. Inside this function, a for loop will run from 0 to array size-1, accessing each
element of array by adding the iterator i to the pointer variable (array argument,
which was passed to this function).
6. Elements will get add and the total sum will be returned from this function.
7. Variable sum inside main() function, will get this returned value and will be printed.
8. END
CODE:
#include <stdio.h>
void main()
{
2K19/A4/11 Farhan Raja Page 80
int array[20];
int i, n, sum;
scanf("%d",&n);
scanf("%d",&array[i]);
return(total);
}
2K19/A4/11 Farhan Raja Page 81
OUTPUT:
We learned how to pass array to a function using pointers and how to calculate sum of
elements of array using this method.
INTRODUCTION:
As we know that, pointers are the special type of variables that are used to store the address
of another variable. And array is the group of similar type of variables (using single name
for all variables), that takes contiguous memory locations.
"Array of pointes" is an array of the pointer variables. Here, in this program, we are
declaring an array of float pointers that will store the address of float variables.
This step is similar to any other pointer variable. We get the address of a variable using the
address of & operator and then save that address in the array of pointers.
ALGORITHM:
1. START
2. Declare five variables to store marks of five subjects
3. Declare an array of integer pointers that will point to the address of variables
containing marks of different subjects
4. Take input of the marks form user
5. Calculate percentage of each subject using pointers
6. Print percentage of marks
7. END
CODE:
#include <stdio.h>
int main()
float eng,phy,chem,math,comp;
int i;
float *ptr[5];
ptr[0]= ŋ
ptr[1]= &phy;
ptr[2]= &chem;
ptr[3]= &math;
ptr[4]= ∁
scanf("%f",&eng);
scanf("%f",&phy);
scanf("%f",&chem);
scanf("%f",&comp);
printf("\n==========================================================\n");
printf("Marks of:\n English: %.2f\n Physics: %.2f\n Chemistry: %.2f\n Mathematics: %.2f\n
Computer: %.2f\n",*ptr[0],*ptr[1],*ptr[2],*ptr[3],*ptr[4]);
*ptr[i] = (*ptr[i]/70)*100;
printf("\nPercentage of subjects:\n");
printf("\n English: %.2f\n Physics: %.2f\n Chemistry: %.2\n Mathematics: %.2f\n Computer:
%.2f\n",*ptr[0],*ptr[1],*ptr[2],*ptr[3],*ptr[4]);
return 0;
We learned about array of pointers and how to store address of variables in it. We also
learned how to perform basic mathematical operations using array of pointers.
Write a program to create a file called emp.txt and store information about a person, in
terms of his name, age and salary.
INTRODUCTION:
This C Program creates a file & store information. We frequently use files for storing
information which can be processed by our programs. In order to store information
permanently and retrieve it we need to use files and this program demonstrate file creation
and writing data in that.
ALGORITHM:
1. START
2. Declare a file pointer
3. Open file named emp.txt using fopen() in writing mode
4. If file pointer points to a null value, print file doesn’t exist
5. Enter details of name, age, and salary
6. Close the file using fclose()
7. END
CODE:
#include<stdio.h>
#include<conio.h>
void main()
FILE *fptr;
char name[20];
float salary;
if (fptr == NULL)
return;
scanf("%s", name);
scanf("%d", &age);
scanf("%f", &salary);
OUTPUT:
We learned how to open and close a file and how to create a text file. We learned about
functions like fopen, fclose and file pointers. Moreover, we also learned how to write data in
a file using various funtions.
INTRODUCTION:
A File can be used to store a large volume of persistent data. Like many other languages 'C'
provides the following file management functions,
Creation of a file
Opening a file
Reading a file
Writing to a file
Closing a file
In this program we will copy a file to another file, firstly you will specify a file to copy. We
will open the file and then read the file that we wish to copy in "read" mode and target file
in "write" mode.
ALGORITHM:
1. START
2. Input file path of source and destination file.
3. Open source file in r (read) and destination file in w (write) mode.
4. Read character from source file and write it to destination file using fputc().
5. Repeat step 3 till source file has reached end.
6. Close both source and destination file.
7. END
CODE:
#include <stdio.h>
#include <stdlib.h>
FILE *sourceFile;
FILE *destFile;
char sourcePath[100];
char destPath[100];
char ch;
scanf("%s", sourcePath);
scanf("%s", destPath);
/*
*/
exit(EXIT_FAILURE);
ch = fgetc(sourceFile);
fputc(ch, destFile);
ch = fgetc(sourceFile);
fclose(destFile);
return 0;
OUTPUT:
We learned about file handling of .txt files in C program. We also learned how to copy
content from one file to another.
Write a program to read a file and after converting all lower case to upper case letters write
it to another file.
INTRODUCTION:
Given a text file, our task is to convert all the lower case characters of file into upper case.
Open the file in read mode. Check if there is any error in opening or locating a file. If yes,
then throw an error message.
If the file is found, then with the help of while loop, convert all the characters using toupper
of that file into upper case.
Close the file using fclose() function by passing the file pointer in it.
ALGORITHM:
1. START
2. Open source file in read mode, store its reference in fptr.
3. Create a temporary file to store result, store its reference in dest.
4. Read a character from source file fptr. Store character read in ch
5. Convert lowercase characters to uppercase. Which means if islower(ch) then
convert to uppercase.
6. Write converted character to dest file.
7. Repeat step 3-5 till end of file.
8. Close both files fptr as well as dest.
9. END
CODE:
/*C program to convert lowercase to uppercase of a file and copy the contents after
converting case
#include <stdlib.h>
int main()
FILE *fPtr;
char path[100];
scanf("%s", path);
if (fPtr == NULL)
exit(EXIT_FAILURE);
toggleCase(fPtr, path);
return 0;
/**
*/
FILE *dest;
char ch;
if (dest == NULL)
fclose(fptr);
exit(EXIT_FAILURE);
if (islower(ch))
ch = toupper(ch);
fputc(ch, dest);
fclose(fptr);
fclose(dest);
OUTPUT:
From this experiment we learned how to change case of letters in a file using C program.
We learned about basic file handling functions in C. We also learned how to open, close,
read/write and create a file using C language.
INTRODUCTION:
The function fseek() is used to set the file pointer at the specified position. In general, it is
used to move the file pointer to the desired position within the file.
The idea is to use fseek() in C and ftell() in C. Using fseek(), we move file pointer to end,
then using ftell(), we find its position which is actually size in bytes.
ALGORITHM:
1. Begin
2. Declare function file_size()
3. Open a file pointer fp in read only mode.
4. If fp is equals to null then
a. Print “File not found” and return -1.
Else count the file size.
b. Close the file.
5. Put the file pointer at the beginning of the file
6. Declare a integer variable result and initialize it with the output of the ftell()
function.
7. Close file pointer fp.
8. Return result.
9. End
CODE:
#include<stdio.h>
#include<process.h>
len = ftell(fp);
return len;
void main(void)
FILE *fp;
char filename[20];
scanf("%s",filename);
fp = fopen(filename, "r");
if(fp == NULL)
exit(0);
OUTPUT:
From this experiment we learned about file handling operations and functions. We learned
how to find the size of a .txt extension file size in C language.