0% found this document useful (0 votes)
17 views56 pages

20ESPL101 Programming in C Lab Manual

The document outlines a series of experiments for a C programming lab, detailing various programming tasks such as input/output operations, calculations, and data structure manipulations. Each experiment includes an aim, algorithm, program code, output, and result verification. The tasks range from simple operations like displaying personal details to more complex functions like checking for Armstrong numbers and performing matrix operations.

Uploaded by

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

20ESPL101 Programming in C Lab Manual

The document outlines a series of experiments for a C programming lab, detailing various programming tasks such as input/output operations, calculations, and data structure manipulations. Each experiment includes an aim, algorithm, program code, output, and result verification. The tasks range from simple operations like displaying personal details to more complex functions like checking for Armstrong numbers and performing matrix operations.

Uploaded by

kratosrajsp6
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

1

DEPARTMENT O F COMPUTER SCIENCE AND ENGINEERING


CS3271 – C PROGRAMMING LAB
LIST OF EXPERIMENTS

S.
LIST OF EXPERIMENTS
NO
1. Programming using I/O statements and Expressions
a) Program to display your personal details
b) Program to get the user details and display it
2. a) Program to display biggest of three numbers.
b) Program to check whether the entered character is vowel or not
3. Program to find whether given year is leap year or not
4. Program to perform the calculator operation using switch case
5. Program to check whether a given number is Armstrong or not
6. Program to check whether a given number is odd or not
7. Program to find factorial of given number
8. Program to find out average of n-numbers
9. Program to find largest element in an array
10. Program to perform Matrix addition
11. Program to perform String operations
12. Program to perform search operations such as linear search & Binary search using functions
13. Program to perform swapping using call by value & call by reference
14. Program to perform Fibonacci series using recursion
15. Program to perform sorting names using arrays and pointers
16. Program to display employee details using Structures
17. Program to display 5 student details and calculate total, average and display result using
Structures and Pointer Structure
18. Program to display student details using Union.
19. Program to count the number of words and characters in a file
20. Telephone directory using random access file
2

EX1
PROGRAMUSINGI/OSTATEMENTSANDEXPRESSIONS
DATE:

AIM:

i] Programtodisplayyourpersonaldetails

ALGORITHM:

Step1: Start
Step2:Declareandinitializethevariablesforname,address,dateofbirth,mobilenumber
andage
Step3:Displayname,address,
dateofbirth,mobilenumberandageStep4:End

PROGRAM:

#include<stdio.h>
voidmain()
{
charname[20]="SAIRAM";
char address[80]= "west
tambharam,chennai";intdate=20;
int
month=10;intye
ar=1990;
int
mobile=987456321;int
age=25;
printf("\n=====================");
printf("\n NAME:
%s",name);printf("\nADDRESS:
%s",address);
printf("\n DOB:%d:%d:%d", date , month,
year);printf("\n MOBILE NUMBER:%d",
mobile);printf("\n AGE:%d", age);printf("\
n=====================");
}
3

OUTPUT:

NAME:SAIRAM
ADDRESS:westtambaram,chennai
DO[Link]
MOBILE
NUMBER:987456321AGE:25

RESULT

Thus the C Program to display the personal details has been executed and the output
wasverified.
4

AIM:

ii] Programtogettheuserdetailsanddisplayit.

ALGORITHM:

Step1: Start
Step2:Declarethevariablesforname,address,date,month,year,mobilenumber,age.
Step3:Readvaluesofname, address,date,month,year,mobilenumber, agefromthe
user.
Step4:Displayname,address,date,month,year,
mobilenumber,age.Step5:End

PROGRAM:

#include<stdio.h>
#include<conio.h
>#include<string.
h>intmain()
{
charname[20];ch
ar
address[80];intd
ate;
int
month;int
year;
longint
mobile;char
gender[20];inta
ge;
printf("\nENTERYOURNAME:=");
gets(name);
printf("\nENTERYOURADDRESS=");
gets(address);
printf("\nENTER YOUR
date/month/year=");scanf("%d/%d/%d",&dat
e,&month,&year);printf("\n ENTER YOUR
AGE=");scanf("%d",&age);
printf("\nENTERYOURGENDER(MALE/FEMALE)=");
scanf("%s",gender);
printf("\nENTERYOURMOBILENUMBER=");
scanf("%ld",&mobile);
5

printf("\n=====================");
printf("\n NAME:
%s",name);printf("\nADDRESS:
%s",address);
printf("\n DOB:%d:%d:%d", date , month,
year);printf("\nAGE:%d",age);
printf("\nGENDER:%s",gender);
printf("\n MOBILE NUMBER:%d",
mobile);printf("\
n=====================");
return0;
}

OUTPUT:

ENTERYOURNAME:=karthikeyan

ENTERYOURADDRESS=westtambharam,chennai.E

NTERYOURdate/month/year=03/12/1992

ENTERYOURAGE=28

ENTERYOURGENDER(MALE/

FEMALE)=MALEENTERYOURMOBILENUMBER

=987654321

=====================
NAME:karthikeyanADDRESS:westt
ambharam,[Link][Link]
AGE:28GENDE
R:MALE
MOBILENUMBER:987654321
========================

RESULT:

ThustheCProgramtoreadand displaytheuserdetailshasbeenexecuted andtheoutputwas


6
verified.
7

EX2A
PROGRAMTODISPLAYBIGGESTOFTHREENUMBERS

DATE:

AIM:

ii]Programtocheckbiggestofthreenumbers

ALGORITHM:

Step1:Start

Step 2:Read three numbers A,B & C

Step3: Check whether A is greater than B and then check whether A is greater than C then

print A is greater

Step 4:Otherwise print C is greater

Step5:Check whether B is greater than C

Then print B is greater

Step6: Otherwise printC isgreatest

Step8:end

PROGRAM:

#include
<stdio.h>voidmai
n()
{
intA,B,C;
printf("Enter 3 integer number \
n");scanf("%d",&A);
scanf("%d",&B);
scanf("%d",&C);
if(A>B){
if(A>C){
printf("%d istheGreatestNumber\n",A);
}
else{
printf("%disthegreatestNumber\n",C);
}
8
}
else{
if(B>C){

printf("%disthegreatestNumber\n",B);
}
else{
printf("%disthegreatestNumber\n",C);
}
}
}

OUTPUT:

Enter three numbers: -


4.53.9
5.6
5.60isthe largest number.

RESULT:

Thus the C Program to display the personal details has been executed and the output
wasverified.
9

EX2B PROGRAM TO CHECK WHETHER THE


ENTEREDCHARACTERISVOWELORNOT(USESWITC
DATE:
HCASE)

AIM:

ii]Programtocheckwhethertheenteredcharacter isvowelornot(Useswitchcase)

ALGORITHM:

Step1: Start
Step2:Declarevariables
Step3:Gettheinputfromtheuserandcompare witheachcases

Steep 4: if match found, print vowel otherwise print consonant

Step5:End

PROGRAM:

#include<stdio.h>
#include<conio.h
>intmain()
{
charch;
printf("Enter a character:
");scanf("%c",&ch);
//condition to check character is alphabet or
notif((ch>='A'&&ch<='Z')||(ch>='a'&&ch<='z'))
{

switch(ch)
{
case'A':
case'E':
case'I':
case'O':
case'U':
case'a':
case'e':
case'i':
case'o':
case'u':
printf("%cisaVOWEL.\n",ch);
10

break;
default:
printf("%cisaCONSONANT.\n",ch);
}
}
else
{
printf("%cisnot analphabet.\n",ch);
}

return0;
}

OUTPUT:

Enter a

characterE

Eis avowelEnter

a characterX

X is a

consonantEntera

character

+isnotanalphabet

RESULT:

Thus the C Program check whether the entered character is vowel or not (Use
switchcase) has beenexecutedand theoutputwas verified.
11

EX3 PROGRAMTOFIND WHETHERTHEGIVENYEARISLEAP


YEAR ORNOT
DATE:

AIM:

TowriteaCProgramtofindwhetherthegiven yearisleapyearornot.

ALGORITHM:

Step1:Start

Step2:Takeintegervariableyear

Step3:Checkifyearisdivisibleby400thenDISPLAY"isaleapyear"

Step4:Checkifyearis notdivisibleby100ANDdivisibleby4thenDISPLAY"isaleapyear"

Step5:Otherwise,DISPLAY"isnotaleapyear"Step

6:Stop

PROGRAM:

#include<stdio.h>#
include
<conio.h>voidmai
n()
{
intyear;
printf("Enter a year :\
n");scanf("%d",&year);
if((year% 400)==0)
printf("%disaleapyear\n",year);else
if((year%100)!=0&&(year
%4)==0)printf("%disa leapyear\n",year);
else
printf("%disnotaleapyear \n",year);
}
12

OUTPUT:

Enterayear:
2000
2000isaleapyear

Enterayear:
1900
1900isnotaleapyear

RESULT:
Thus the C Program to find whether the given year is leap year or not has
beenexecutedsuccessfullyand theoutputwas verified.
13

EX4 PROGRAM TO PERFORM THE CALCULATOR


OPERATIONS,NAMELY,ADDITION,SUBTRACTION,MULTIPLICATI
DATE: ON,DIVISIONANDSQUAREOFANUMBER by Using Switch case

AIM:

ToperformtheCalculatoroperations,namely,addition,subtraction,multiplication,divisi
onandsquareofanumber

ALGORITHM:

Step1: Start the program

Step 2 : Declare the variables and display menu for arithmetic operation

Step3: Gettheinputvalues

Step4:Performtheoperationsusingswitch case

Step5:Printtheresults

Step6:Stoptheprogram

PROGRAM:

#include<stdio.h>
#include<conio.h>
int main()
{
inta,b;
int op;
printf(" [Link]\n [Link]\n [Link]\n [Link]\n");
printf("Enter the values of a & b: ");
scanf("%d %d",&a,&b);
printf("Enter your Choice : ");
scanf("%d",&op);
switch(op)
{
case 1 :
printf("Sum of %d and %d is : %d",a,b,a+b);
break;
case 2 :
printf("Difference of %d and %d is : %d",a,b,a-b);
break;
case 3 :
printf("Multiplication of %d and %d is : %d",a,b,a*b);
break;
case 4 :
printf("Division of Two Numbers is %d : ",a/b);
break;
14
default :
printf(" Enter Your Correct Choice.");
break;
}
return 0;
}

OUTPUT:

[Link]
[Link]
[Link]
[Link]
Enter the values of a & b: 20 15
Enter your Choice : 1
Sum of 20 and 15 is : 35

RESULT

ThustheCProgramtoperformtheCalculatoroperations,namely,addition,subtraction,
multiplication, division and square of a number has been executed and results areverified.
15

EX5 PROGRAMTOCHECKWHETHERAGIVENNUMBERISAR
MSTRONGNUMBER ORNOT?
DATE:

EX5:
AIM:

Programtocheck whetherthegivennumberisArmstrongnumberornot

ALGORITHM:

Step1: Start

Step 2: Declare Variable sum, temp,

numStep3:ReadnumfromUser

Step4:InitializeVariablesum=0andtemp=num

Step 5: Repeat the flowing steps 6 & 7 Until the value of num is 0
Step 6: Calculate the remainder value by using modulo operator
Step 7: cube the remainder value and its added with sum. Then
Number is decremented by dividing the num value by 10.

Step8:IFsum==tempPrint"ArmstrongNumber"ELSEPrint"NotArmstrongNumber"

Step9:Stop

PROGRAM:

#include<stdio.h>
intmain()
{
intnum,copy_of_num,sum=0,rem;printf("\
nEnter a number:");scanf("%d",&num);
while(num!=0)
{
rem=num%10;
sum=sum+
(rem*rem*rem);num=num/10;
}
if(copy_of_num==sum)
printf("\n%disanArmstrongNumber",copy_of_num);else
printf("\n%disnotanArmstrongNumber",copy_of_num);return(0);
}
16

OUTPUT:

Enteranumber: 370
370isanArmstrongNumber

RESULT:
Thus the C Program to check whether a given number is Armstrong or not has
beenexecutedandtheoutputwas verified.
17

EX6 PROGRAMTOCHECKWHETHERAGIVENNUMBERIS
ODDOREVEN
DATE:

AIM:

Programtocheckwhetheragivennumberisoddoreven

ALGORITHM:

Step 1: Start the

programStep2:

Getthenumber

Step3:Check thenumberifitisoddorevenusingifstatement.

Step4:Ifthenumberisevencheck theconditionasn

%2==0elseitiseven.Step5:Displaytheresult

Step6: Stopthe program

PROGRAM:

#include

<stdio.h>intmain(

int number;

printf("Enter an integer:

");scanf("%d",&number);

// True if the number is perfectly divisible by 2 if(number % 2 ==

0)printf("%dis even.",number);

else

printf("%d is odd.",

number);return0;
18
}
19

OUTPUT:

Enteraninteger:-7

-7isodd.

Enter an integer :

88is even

RESULT

ThustheCProgramtofindwhetherthegivennumberisoddorevennumberhasbeensuccessfullyexecut
edandverified
20

EX7
PROGRAMTOFINDFACTORIALOFAGIVENNUMBER

DATE:

AIM:

Tofindfactorialofa givennumber

ALGORITHM:

Step 1. Start the

[Link]

number

Step 3. If the number < 0 print “Error for finding a

factorial”[Link]←1i←1

Step 5. Readvalueofn

Step6. Repeatthestepuntili=n, calculate factorial=factorial*i.

Step 7:Displayfactorial

Step 8. Stoptheprogram

PROGRAM:

intmain()

int n, i; longfactorial =
1;printf("Enter an integer:
");scanf("%d",&n);
//
showerroriftheuserentersanegativeintegerif(n<0
)
printf("Error! Factorial of a negative number doesn't
exist.");else

{
21

for(i=1;i<=n;++i)
{

factorial*=i;
//factorial=factorial*i;
}
printf("Factorialof%d=%lu",n,factorial);
}
return0;
}

OUTPUT:

Enter an integer:
10Factoriaof10=3628800

RESULT

ThustheCProgramtofindthe
factorialofagivennumberhasbeensuccessfullyexecutedandverified.
22

EX8
PROGRAMTOFIND OUTTHEAVERAGEOFn -INTEGERS

DATE:

AIM:
Tofindaverageof4 integers

ALGORITHM:

[Link]

[Link]

[Link] the n numbersof values by using for loop. Then

find the sum of n values

[Link]=sum/n

Step 5. Display the output

[Link]

PROGRAM:

#include<stdio.h>
voidmain()

inti,n,sum=0,nu[100];
floatavg;

clrscr();

printf("\nEnterthenumbers\n");

for(i=0;i<n;i++)

scanf("%d",&nu[i]);
sum=sum+ nu[i];

}
23

avg=(float)sum/n;

printf("\nAverage is : %.2f\
n",n,avg);getch();
}

OUTPUT:

Enter the

numbers32

45

54

22

Average is38.25

RESULT

ThustheCProgramtofindtheaverageof4numbershasbeenexecutedandverified.
24

EX9
PROGRAM TO FIND LARGEST ELEMENT IN AN ARRAY
DATE:

AIM:

Tofind largest element in an array

ALGORITHM:

Step1:Starttheprogram

STEP 2: Initialize arr[] = {25, 11, 7, 75, 56}

STEP 3: find the length of the given array

STEP 4: set max = arr[0]

STEP 5: seti=0. REPEAT STEP 6

and STEP 7 i<length

STEP 6: if(arr[i]>max)

max=arr[i]

STEP 7: i=i+1.

STEP 8: PRINT "Largest element in given array:" assigning max.

STEP 9: RETURN 0

Step10: Stoptheprogram

PROGRAM:
#include <stdio.h>
int main()
{
intarr[] = {25, 11, 7, 75, 56};
int length = sizeof(arr)/sizeof(arr[0]);
int max = arr[0];

for (inti = 0; i< length; i++) {


25
if(arr[i] > max)
max = arr[i];
}
printf("Largest element present in given array: %d\n", max);
return 0;
}

OUTPUT:

Largest element present in given array: 75

RESULT:

Thus the C Program to find the largest number in an array has been
executedandtheresultwas verified
26

EX10
PROGRAMTOPERFORM MATRIX ADDITION
DATE:

AIM:

Toperform matrix addition using arrays

ALGORITHM:

Step1:Starttheprogram

Step2:Declare the array variables

Step 3:Gettheelementsofthe array

Step 3 : Add the array elements

Step 4 : Display the array

elementsStep5:Stoptheprogram

PROGRAM:

#include <stdio.h>
int main() {
int r, c, a[100][100], b[100][100], sum[100][100], i, j;
printf("Enter the number of rows (between 1 and 100): ");
scanf("%d", &r);
printf("Enter the number of columns (between 1 and 100): ");
scanf("%d", &c);
printf("\nEnter elements of 1st matrix:\n");
for (i = 0; i< r; ++i)
for (j = 0; j < c; ++j) {
printf("Enter element a%d%d: ", i + 1, j + 1);
scanf("%d", &a[i][j]);
}

printf("Enter elements of 2nd matrix:\n");


for (i = 0; i< r; ++i)
for (j = 0; j < c; ++j) {
printf("Enter element b%d%d: ", i + 1, j + 1);
scanf("%d", &b[i][j]);
}

// adding two matrices


for (i = 0; i< r; ++i)
for (j = 0; j < c; ++j) {
27
sum[i][j] = a[i][j] + b[i][j];
}

// printing the result


printf("\nSum of two matrices: \n");
for (i = 0; i< r; ++i)
for (j = 0; j < c; ++j) {
printf("%d ", sum[i][j]);
if (j == c - 1) {
printf("\n\n");
}
}

return 0;
}

OUTPUT:

Enter the number of rows (between 1 and 100): 2


Enter the number of columns (between 1 and 100): 3

Enter elements of 1st matrix:


Enter element a11: 2
Enter element a12: 3
Enter element a13: 4
Enter element a21: 5
Enter element a22: 2
Enter element a23: 3
Enter elements of 2nd matrix:
Enter element b11: -4
Enter element b12: 5
Enter element b13: 3
Enter element b21: 5
Enter element b22: 6
Enter element b23: 3

Sum of two matrices:


-2 8 7

10 8 6

RESULT:

Thus the C Program to perform matrix addition has been executedandtheresultwas


verified
28

EX11

PROGRAM TO PERFORM STRING OPERATIONS


DATE:

AIM:

Toperform string operations

ALGORITHM:

Step1:Start
Step2:GetthetwoStrings str1 and str2.
Step3: perform various string operation
.Step4: to find string length, use strlen(str1) function
Step5:To find Uppercase of string use strupr(str1)
.Step6:To find concatenation, use strcat(str1,str2)
Step 7 :To copy the string, use strcpy(str3,str1)
Step8:Stop

PROGRAM:
# include <stdio.h>
# include <conio.h>
# include <string.h>

int main()
{
char str1[40], str2[40] ;
clrscr() ;
printf("Enter the first string : \n\n") ;
gets(str1) ;
printf("\nEnter the second string : \n\n") ;
gets(str2) ;
printf("\nString 1 = %s & String 2 = %s ", str1, str2) ;
printf("- Length is : %d and %d", strlen(str1), strlen(str2)) ;
printf("\n\nString 1 = %s & String 2 = %s ", str1, str2) ;
printf("- Uppercase is : %s and %s", strupr(str1), strupr(str2));
printf("\n\nString 1 = %s & String 2 = %s ", str1, str2) ;
printf("- Lowercase is : %s and %s", strlwr(str1), strlwr(str2));
printf("\n\nString 1 = %s & String 2 = %s ", str1, str2) ;
printf("- Reverse is : %s and %s", strrev(str1), strrev(str2)) ;
printf("\n\nString 1 = %s & String 2 = %s ", str1, str2) ;
printf("- String copy is : %s ", strcpy(str1,str2));
printf("\n\nString 1 = %s & String 2 = %s ", str1, str2) ;
printf("- Concatenation is : %s ", strcat(str1,str2));
printf("\n\nString 1 = %s & String 2 = %s ", str1, str2) ;
return 0 ;
}
29

OUTPUT:

Enter the first string :


Football

Enter the second string :


Rocks!

String 1 = Football & String 2 = Rocks! - Length is : 8 and 6


String 1 = Football & String 2 = Rocks! - Uppercase is : FOOTBALL and ROCKS!
String 1 = FOOTBALL & String 2 = ROCKS! - Lowercase is : football and rocks!
String 1 = football & String 2 = rocks! - Reverse is : llabtoof and !skcor
String 1 = llabtoof& String 2 = !skcor - String copy is : !skcor
String 1= !skcor& String 2= !skcor - Concatenation is : !skcor!skcor
String 1 = !skcor!skcor& String 2 = !skcor

RESULT:

ThustheCProgramtoperformstring
operationshasbeenexecutedandtheresultwasverified.
30

EX12 a
PROGRAM TO PERFORM SEARCH OPERATIONS SUCH
AS LINEAR SEARCH USING FUNCTIONS
DATE:

AIM:

Toperform search operations such as linear search using functions

ALGORITHM:

Step1: Start
Step 2: Initialize current element with first element of the list.
Step 3: Compare current element with the key. If they are equal, goto Step 5
Step 4: Set next element, if present, as current element and goto Step 2
Step 5: All elements are traversed and no element of array matches key. So, key not found.
Return -1
Step 6: Key is found. Return the position of the element
Step 7: Stop

PROGRAM:

#include <stdio.h>
#include <stdlib.h>
/*
Input : integer array indexed from 0, key to be searched
Ouput : Position of the key in the array if found, else -1
*/
intlinearSearch(int a[], int n, int key) {
intpos = -1;
for (inti = 0; i< n; ++i) {
if (a[i] == key) {
pos = i;
break;
}
}
returnpos;
}

int main() {
int a[] = {8, 12, 3, 4, 7, 2, 13};
int n = sizeof(a) / sizeof(a[0]);
intpos = linearSearch(a, n, 3);
if (pos != 1)
printf("Key found at position : %d \n", pos);
else
31
printf("Key not found \n");
return 0;
}

OUTPUT:

Key found at position: 2

RESULT:

ThustheCProgramtoperformlinear search hasbeenexecutedandtheresultwasverified.


32

EX12 b
PROGRAM TO PERFORM SEARCH OPERATIONS SUCH
AS BINARY SEARCH USING FUNCTIONS
DATE:

AIM:

Toperform search operations such as binary search using functions

ALGORITHM:

Step1: Start
Step2:Compare the middle element of the search space with the key.
Step3:If the key is found at middle element, the process is terminated.
Step4:If the key is not found at middle element, choose which half will be used as the next
search space.
 If the key is smaller than the middle element, then the left side is used for next
search.
 If the key is larger than the middle element, then the right side is used for next
search.
Step5:This process is continued until the key is found or the total search space is exhausted.
Step 6: Stop

PROGRAM:

#include <stdio.h>

// An iterative binary search function.


intbinarySearch(intarr[], int l, int r, int x)
{
while (l <= r) {
int m = l + (r - l) / 2;

// Check if x is present at mid


if (arr[m] == x)
return m;

// If x greater, ignore left half


if (arr[m] < x)
l = m + 1;

// If x is smaller, ignore right half


else
r = m - 1;
}
33

// If we reach here, then element was not present


return -1;
}

// Driver code
int main(void)
{
intarr[] = { 2, 3, 4, 10, 40 };
int n = sizeof(arr) / sizeof(arr[0]);
int x = 10;
int result = binarySearch(arr, 0, n - 1, x);
(result == -1) ? printf("Element is not present"
" in array")
: printf("Element is present at "
"index %d",
result);
return 0;
}

OUTPUT:

Element is present at index 3

RESULT:

ThustheCProgramtoperformbinary search hasbeenexecutedandtheresultwasverified.


34

EX13
PROGRAM TOPERFORMSWAPPINGUSINGCALL BY VALUE &
CALL BY REFERENCE
DATE:

AIM:

Toperformswappingusing call by value & call by reference

ALGORITHM:

Step1. Starttheprogram
Step2.

Declareandgetthetwointegervariablesaandb.Step3.
Calltheswappingfunction

o In call by value method, the value of the actual


parameters is copied into the formal parameters

o In call by reference, the address of the variable is


passed into the function call as the actual parameter.

Step4. Print the a and b


valuesStep5. Stoptheprogram

PROGRAM:

/* Call by Value */

#include <stdio.h>
void swap(int , int); //prototype of the function
int main()
{
int a = 10;
int b = 20;
printf("Before swapping the values in main a = %d, b = %d\n",a,b);
swap(a,b);
printf("After swapping values in main a = %d, b = %d\n",a,b);
}

void swap (int a, int b)


{
int temp;
35
temp = a;
a=b;
b=temp;
printf("After swapping values in function a = %d, b = %d\n",a,b); // Formal parameters, a
= 20, b = 10
}

/* Call by Reference */

#include <stdio.h>
void swap(int *, int *); //prototype of the function
int main()
{
int a = 10;
int b = 20;
printf("Before swapping the values in main a = %d, b = %d\n",a,b);
swap(&a,&b);
printf("After swapping values in main a = %d, b = %d\n",a,b);
}
void swap (int *a, int *b)
{
int temp;
temp = *a;
*a=*b;
*b=temp;
printf("After swapping values in function a = %d, b = %d\n",*a,*b); // Formal parameters,
a = 20, b = 10
}

OUTPUT:

/* Call by Value */

Before swapping the values in main a = 10, b = 20


After swapping values in function a = 20, b = 10
After swapping values in main a = 10, b = 20
/* Call by Reference */
Before swapping the values in main a = 10, b = 20
After swapping values in function a = 20, b = 10
After swapping values in main a = 20, b = 10

RESULT:
ThustheCProgramtoswaptwonumbersusingcall by value and
referencehasbeenexecutedandverified
36

EX14
PROGRAM TO PERFORM FIBONACCI SERIES USING
DATE: RECURSION

AIM:

Todisplayallprimenumbersbetweentwointervalsusingfunctions

ALGORITHM:

Step1: Start the Program

Step 2: Input the non-negative integer ‘n’

Step 3: If (n==o || n==1) then return the value of n;

otherwise return fib(n-1)+fib(n-2);

Step 4: Print, the nth Fibonacci number

Step5:StoptheProgram

PROGRAM:

#include<stdio.h>
voidprintFibonacci(int n){
staticint n1=0,n2=1,n3;
if(n>0){
n3 = n1 + n2;
n1 = n2;
n2 = n3;
printf("%d ",n3);
printFibonacci(n-1);
}
}
int main(){
int n;
printf("Enter the number of elements: ");
scanf("%d",&n);
printf("Fibonacci Series: ");
printf("%d %d ",0,1);
37
printFibonacci(n-2);//n-2 because 2 numbers are already printed
return 0;
}

OUTPUT:

Enter the number of elements:15


0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

RESULT:

ThustheCProgramtoFibonacci series using recursion hasbeenexecutedandverified.


38

EX15
PROGRAMTO PERFORM SORTING NAMES USING ARRAYS
DATE: AND POINTERS

AIM:

Toperform sorting names using arrays and pointers

ALGORITHM:

Step1: Start
Step2:Declarethe String

Step3: using user defined function perform sorting operations


Step 4: Display the names in the ascending order
Step5:stopthe execution.

PROGRAM:

#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char *x[20];
inti,n=0;
void reorder(intn,char *x[]);
clrscr();
printf("Enter no. of String : ");
scanf("%d",&n);
printf("\n");

for(i=0;i<n;i++)
{
printf("Enter the Strings %d : ",i+1);
x[i]=(char *)malloc(20*sizeof(char));
scanf("%s",x[i]);
}
reorder(n,x);
printf("\nreorder list is : \n");
for(i=0;i<n;i++)
{
printf("%d %s\n",i+1,x[i]);
}
getch();
}
void reorder(intn,char *x[])
{
39
inti,j;
char t[20];
for(i=0;i<n-1;i++)
for(j=i+1;j<n;j++)
if(strcmp(x[i],x[j])>0)
{
strcpy(t,x[j]);
strcpy(x[j],x[i]);
strcpy(x[i],t);
}
return;
}

OUTPUT:
Enter no of strings: 5
Enter the String 1: Priya
Enter the String 2: Ram
Enter the String 3: Arjun
Enter the String 4: Maheshwari
Enter the String 5: Revathi

Reorder list is:

1 Arjun
2 Maheshwari
3 Priya
4 Ram
5 Revathi

RESULT
ThustheCProgramtoperform sorting names using arrays and
pointershasbeenexecutedandverified
40
41

EX16
PROGRAM TO DISPLAY EMPLOYEE DETAILS USING
STRUCTURES
DATE:

AIM:

Todisplay employee details using Structures

ALGORITHM:

Step1:START
Step2:Reademployee’s details like name, employee id and salary using
structureStep3: Display the entered values
Step 4: STOP

PROGRAM:
#include <stdio.h>

/*structure declaration*/
struct employee{
char name[30];
intempId;
float salary;
};

int main()
{
/*declare structure variable*/
struct employee emp;

/*read employee details*/


printf("\nEnter details :\n");
printf("Name ?:"); gets([Link]);
printf("ID ?:"); scanf("%d",&[Link]);
printf("Salary ?:"); scanf("%f",&[Link]);

/*print employee details*/


42
printf("\nEntered detail is:");
printf("Name: %s" ,[Link]);
printf("Id: %d" ,[Link]);
printf("Salary: %f\n",[Link]);
return 0;
}

OUTPUT:
Enter details :
Name ?:Mike
ID ?:1120
Salary ?:76543

Entered detail is:


Name: Mike
Id: 1120
Salary: 76543.000000

RESULT:

ThustheCProgramtostoreanddisplayemployeedetailsusingstructureshasbeenexecutedand
theresultwas verified.
43

EX17 PROGRAM TO DISPLAY 5 STUDENT DETAILS AND CALCULATE


TOTAL, AVERAGE AND DISPLAY RESULT USING STRUCTURES
DATE:
AND POINTER STRUCTURE

AIM:

Toreadthestudentdataandcalculatethetotalmarks

ALGORITHM:

Step1:Starttheprogram

Step 2: Get the details of the 10 students in five

subjectsStep3:Calculate thetotalmarksofeachstudent

Step4:Calculatethestudentwho

gotthehighesttotalmarksStep5:Displaytheresults

Step6:StoptheProgram

PROGRAM:
#include<stdio.h>

structstudent

int

sub1;int

sub2;int

sub3;int

sub4;int

sub5;

};

voidmain()

struct student

s[10];inti,total=0;
44

clrscr();for(i=0;i

<=4;i++)

printf("\nEnterMarksinFiveSubjects=");

scanf("%d%d

%d",&s[i].sub1,&s[i].sub2,&s[i].sub3,&s[i].sub4,&s[i].sub5);total=s[i].sub

1+s[i].sub2+s[i].sub3+s[i].sub4+s[i].sub5;

printf("\nTotalmarksofs[%d]Student=%d",i,total);

getch();

OUTPUT:

Enter Marks in Five

Subjects8070908098

TotalMarks of1student=83.6

Enter Marks in Five

Subjects6075505578

TotalMarks of2student=63.6

Enter Marks in Five

Subjects7070907568

TotalMarks of3student=74.6

RESULT:

ThustheCProgramtoprintthestudentdetailshasbeenexecutedandtheresultwasverified.
45

EX18 PROGRAM TO DISPLAY STUDENT DETAILS USING UNION.

DATE:

AIM:

Todisplay student details using union

ALGORITHM:

Step1:Starttheprogram

Step 2: Get the details of the studentsas union

Step3:Displaytheresults

Step4:StoptheProgram

PROGRAM:
union un {
int member1;
char member2;
float member3;
};

// driver code
int main()
{

// defining a union variable


union un var1;

// initializing the union member


var1.member1 = 15;

printf("The value stored in member1 = %d",


var1.member1);

return 0;
}

OUTPUT:
The value stored in member1 = 15

RESULT:

ThustheCProgramtoprintthestudentdetailsusing union
hasbeenexecutedandtheresultwasverified.
46

EX19 PROGRAM TO COUNT THE NUMBER OF WORDS AND


CHARACTERS IN A FILE
DATE:

AIM:

Tocount the number of words and characters in a file

ALGORITHM:

Step1:Starttheprogram

Step 2: Open a file in read mode using file pointer.

Step 3: Read a line from file.

Step 4: Split the line into words and store it in an array.

Step 5: Iterate through the array, increment count by 1

for each word.

Step 6: Repeat all these steps till all the lines from the

files has been read.

Step 7:StoptheProgram

PROGRAM:
#include <stdio.h>
#include <stdlib.h>

int main()
{ charch;
FILE *file;
int count = 0;

//Opens a file in read mode


file = fopen("[Link]","r");

//Gets each character till end of file is reached


while((ch = fgetc(file)) != EOF){
//Counts each word
if(ch ==' ' || ch == '\n')
count++;
}

printf("Number of words present in given file: %d", count);


fclose(file);
47

return 0;
}

OUTPUT:
Number of words present in given file: 63

RESULT:

ThustheCProgramtocount the number of words and characters in a file


hasbeenexecutedandtheresultwasverified.
48

EX:20

TELEPHONEDIRECTORYUSINGRANDOMACCESSFILE
DATE:

AIM:
To insert, update, delete and append telephone details of an individual or a company into
atelephonedirectoryusing random access file.

ALGORITHM:
Step1:Createarandom accessfile
Step 2:call the respective procedure to insert, update, delete or append based on user
choiceStep3: Access therandom access file tomakethenecessarychanges andsave

PROGRAM
#include
"stdio.h"#include
"string.h"#include
<stdlib.h>#include
<fcntl.h>

structdir
{
char
name[20];charnu
mber[10];
};

void insert(FILE
*);void update(FILE
*);void del(FILE
*);void display(FILE
*);voidsearch(FILE*)
;

int record =
0;int
main(void)
{intchoice=0;
FILE*fp=fopen("[Link]","rb+");
if (fp == NULL ) perror ("Error opening
file");while(choice!=6)
{
printf("\n1 insert\t 2 update\
n");printf("3delete\t4display\
n");
printf("5 search\t 6 Exit\n Enter
choice:");scanf("%d",&choice);
switch(choice)
{
case 1: insert(fp);
break;case 2: update(fp);
break;case3:
del(fp);break;case 4:
49
display(fp); break;case 5:
search(fp);
break;default:;
}
}
50

fclose(fp);
return0;
}

voidinsert(FILE*fp)
{

structdircontact,blank;
fseek( fp, -sizeof(structdir),
SEEK_END );fread(&blank,
sizeof(structdir), 1, fp);printf("Enter
individual/company name:
");scanf("%s",[Link]);
printf("Enter telephone number:
");scanf("%s",[Link]);fwrite(&cont
act,sizeof(structdir),1,fp);
}

voidupdate(FILE*fp)
{
char name[20],
number[10];intresult;
structdir contact,
blank;printf("Enter
name:");scanf("%s",
name);rewind(fp);while
(!feof(fp))
{
result = fread(&contact, sizeof(structdir), 1,
fp);if(result!=0&&strcmp(name,[Link]) ==
0)
{
printf("Enter
number:");scanf("%s",
number);strcpy([Link],nu
mber);
fseek(fp, -sizeof(structdir),
SEEK_CUR);fwrite(&contact,
sizeof(structdir), 1,
fp);printf("Updatedsuccessfully\n");
return;
}
}
printf("Recordnotfound\n");
}

voiddel(FILE*fp)
{
char name[20],
number[10];intresult,
record=0;
structdir contact, blank = {"",
""};printf("Entername:");
scanf("%s",
name);rewind(fp);
51
while(!feof(fp))
{
result = fread(&contact, sizeof(structdir), 1, fp);

if(result != 0 &&strcmp(name, [Link])==0)


{
52
fseek(fp, record*sizeof(structdir),
SEEK_SET);fwrite(&blank,sizeof(structdir),
1,fp);

printf("%d Deleted successfully\n", record-


1);return;
}
record++;
}
printf("notfoundin %drecords\n",record);

voiddisplay(FILE*fp)
{
structdir
contact;int
result;rewind(fp)
;
printf("\n\n Telephone directory\
n");printf("%20s %10s\n", "Name",
"Number");printf("*************************
******\n");while(!feof(fp))
{
result = fread(&contact, sizeof(structdir), 1,
fp);if(result != 0 &&strlen([Link]) >
0)printf("%20s%10s\
n",[Link],[Link]);
}
printf("*******************************\n");

voidsearch(FILE*fp)
{
structdircontact;
int result; char
name[20];rewind(fp);pri
ntf("\nEnter
name:");scanf("%s",nam
e);
while(!feof(fp))
{
result = fread(&contact, sizeof(structdir), 1,
fp);if(result!=0 &&strcmp([Link],name)==
0)
{
printf("\n%20s %10s\n",[Link],
[Link]);return;
}
}
printf("Recordnotfound\n");

}
53
OUTPUT:

1insert 2update
54

3delete 4display
5search 6Exit
Enter choice:
4Telephonedirector
y
Name Number
******************************
*bb 11111
*******************************

1insert 2 update
3delete 4display
5search 6Exit
Enter choice:

5Entername:bb

bb 11111

1insert 2 update
3delete 4display
5search 6Exit
Enterchoice:1
Enter individual/company
name:aaEntertelephonenumber:222
222

1insert 2 update
3delete 4display
5search 6Exit
Enter choice:
2Entername:aa
Enter number:
333333Updated
successfully

1insert 2 update
3delete 4display
5search 6
ExitEnterchoice:

Telephonedirectory
Name Number
******************************
*bb 11111
aa 333333
******************************
*1insert 2 update
55
3delete 4display
5search 6Exit
56

Enterchoice:3

Entername:aa
1 Deleted successfully

1insert 2update
3delete 4display
5search 6Exit
Enterchoice:4

Telephonedirectory
Name Number
******************************
*bb 11111
*******************************

1insert 2 update
3delete 4display
5search 6Exit
Enterchoice:6

RESULT:

ThustheCprogramtoinsert,update,deleteandappendtelephonedetailsofanindividual or a
company into a telephone directory using random access file was successfullywrittenand
executed.

You might also like