0% found this document useful (0 votes)
2 views

PROGRAMMING IN C LAB MANUAL (1)

The document outlines the CS3271 Programming in C Laboratory course at RRASE College of Engineering, including various programming exercises and their algorithms. It includes examples of C programs for displaying personal details, finding the largest of three numbers, checking for vowels, determining leap years, performing basic calculator operations, and checking Armstrong numbers. Each section contains the program's aim, algorithm, code, output, and results, confirming successful execution.

Uploaded by

Poorani Kasiraj
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)
2 views

PROGRAMMING IN C LAB MANUAL (1)

The document outlines the CS3271 Programming in C Laboratory course at RRASE College of Engineering, including various programming exercises and their algorithms. It includes examples of C programs for displaying personal details, finding the largest of three numbers, checking for vowels, determining leap years, performing basic calculator operations, and checking Armstrong numbers. Each section contains the program's aim, algorithm, code, output, and results, confirming successful execution.

Uploaded by

Poorani Kasiraj
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
You are on page 1/ 76

RRASE COLLEGE OF ENGINEERING

PADAPPAI, CHENNAI.

DEPARTMENT OF CYBER SECURITY

CS3271-PROGRMMING IN C LABORATORY
REGULATION 2021

Name : ________________________________________

Reg.No :

Branch :

Year :

Semester : _

AnnaUniversity::Chennai
RRASE COLLEGE OF ENGINEERING
PADAPPAI, CHENNAI.

LABORATORYRECORD

UNIVERSITYREGISTERNO.

Certified that this is the bonafide record of work done


by

Mr./Ms. of

Department in the

Laboratory

and submitted for University Practical Examination conducted on

at RRASE COLLEGE OF ENGINEERING -601301.

Lab In-charge Principal Head


of the Department

External Examiner
Internal Examiner
S.NO
DATE CONTENT SIGN

1 PROGRAMUSINGI/OSTATEMENTSANDEXPRESSIONS

2(a) PROGRAMTODISPLAYBIGGESTOFTWONUMBERS
EX1

PROGRAMUSINGI/OSTATEMENTSANDEXPRESSIONS
DATE:

AIM:

i] Programtodisplayyourpersonaldetails

ALGORITHM:

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

PROGRAM:

#
i
n
c
l
u
d
e
<
s
t
d
i
o
.
h
>
v
o
i
d
m
a
i
n
(
)
{
charname[20]="SAIRAM";
char address[80]= "west
tambharam,chennai";
intdate=20;
i
n
t

m
o
n
t
h
=
1
0
;
i
n
t
y
e
a
r
=
1
9
9
0
;
i
n
t
m
o
b
il
e
=
9
8
7
4
5
6
3
2
1
;
i
n
ta
g
e
=
2
5
;
printf("\n=====================");
printf("\
nNAME:
%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==================
===");
}
OUTPUT:

NAME:SAIRAM
ADDRESS :west
tambaram,chennaiDOB:20:10:199
0
MOBILE NUMBER:987456321
AGE:25

RESULT

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

ii] Program to get the user detail sand display it.

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];
char address[80];
intdate;
int month;
intyear;
long
intmobile;
char gender[20];
intage;
printf("\nENTERYOURNAME:=");
gets(name);
printf("\nENTERYOURADDRESS=");
gets(address);
printf("\nENTERYOURdate/month/year=");
scanf("%d/%d/%d",&date,&month,&year);
printf("\nENTERYOURAGE=");
scanf("%d",&age);
printf("\nENTERYOURGENDER(MALE/FEMALE)=");
scanf("%s",gender);
printf("\nENTERYOURMOBILENUMBER=");
scanf("%ld",&mobile);
printf("\n=====================");
printf("\nNAME:%s",name);
printf("\nADDRESS:%s",address);
printf("\n DOB:%d:%d:%d", date , month, year);
printf("\nAGE:%d",age);
printf("\nGENDER:%s",gender);
printf("\nMOBILENUMBER:%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:west
tambharam,chennai.DOB:3:12:1992
AGE:28GENDE
R:MALE
MOBILENUMBER:987654321
========================

RESULT:

Thus the C Program to read and display the user detail she been executed and the
output was verified.
EX2A
PROGRAMTODISPLAYBIGGESTOFTWONUMBERS

DATE:

AIM:

ii]Programtocheckbiggestofthreenumbers

ALGORITHM:

Step1:Start

Step 2:Read three numbers A,B &

CStep3:IfA>B,thengotostep6

Step 4:If B>C,then print B & go to step

8Step5:printCisgreatest&goto step8

Step6:IfA>C,thenprintAisgreatest&gotostep8Step7:

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);
}
}
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.
EX2B PROGRAM TO CHECK WHETHER THE
ENTEREDCHARACTERISVOWELORNOT(USESWITC
DATE:
HCASE)

AIM:

ii]Programtocheckwhethertheenteredcharacter isvowelornot(Useswitchcase)

ALGORITHM:

Step1: Start
Step2:Declareandinitializethevariables
Step3:Gettheinputfromtheuserandcompare witheachcasesStep 4:
if match found, print vowel otherwise print consonantStep5: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);
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.
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);
}
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.
EX4 PROGRAM TO PERFORM THE CALCULATOR
OPERATIONS,NAMELY,ADDITION,SUBTRACTION,MULTIPLICATI
DATE: ON,DIVISIONANDSQUAREOFANUMBER

AIM:

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

ALGORITHM:

Step1: Start the programStep

2 : Declare the

functionsStep3:

Gettheinputvalues

Step4:PerformtheoperationsusingfunctionsSte

p5:Printtheresults

Step6:Stoptheprogram

PROGRAM:

#include<stdio.h>

// functions

declarationint add(int

n1,intn2);

int subtract(int n1, int

n2);intmultiply(intn1,intn

2);int

divide(intn1,intn2);intsqua

re(intn1);

// main

functionintmain

()
{

int num1,num2;

printf("Entertwonumbers:");
scanf("%d%d",&num1,&num2);

printf("%d + %d = %d\n", num1, num2, add(num1,

num2));printf("%d - %d = %d\n", num1, num2, subtract(num1,

num2));printf("%d * %d = %d\n", num1, num2, multiply(num1,

num2));printf("%d / %d = %d\n", num1, num2, divide(num1,

num2));printf(“%d^%d=%d\n”,num1,num1,square(num1));

return0;

//

functiontoaddtwointegernumbersintad

d(intn1,intn2)

int result;

result=n1+n2;return

result;

//

functiontosubtracttwointegernumbersintsu

btract(intn1,intn2)

int result;

result = n1 -

n2;returnresult;

//

functiontomultiplytwointegernumbersintm
ultiply(intn1,intn2)

{
int result;

result = n1 *

n2;returnresult;

//

functiontodividetwointegernumbersintdi

vide(intn1,intn2)

int result;

result = n1 /

n2;returnresult;

//functionto

findsquareofanumberintsquare(intn1)

intresult;result

n1*n1;returnre

sult;

}
OUTPUT:

Entertwonumbers: 205

20+5=25

20–5=15

20*5=100

20/5=4

20^20=400

RESULT

ThustheCProgramtoperformtheCalculatoroperations,namely,addition,subtraction,
multiplication, division and square of a number has been executed and results areverified.
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 Until num&gt;=0 5.1 sum=sum + cube of last digit


i.e[(num%10)*(num%10)*(num%10)]5.2 num=num/10

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

Step7:Stop

PROGRAM:

#include<stdio.h>
intmain()
{
int num,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);
}
OUTPUT:

Enteranumber: 370
370isanArmstrongNumber

RESULT:
Thus the C Program to check whether a given number is Armstrong or not has
beenexecutedandtheoutputwas verified.
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;
}
OUTPUT:

Enteraninteger:-7

-7isodd.

Enter an integer :

88is even

RESULT

ThustheCProgramtofindwhetherthegivennumberisoddorevennumberhasbeensuccessfullyexecut
edandverified
EX7
PROGRAMTOFINDFACTORIALOFAGIVENNUMBER

DATE:

AIM:

Tofindfactorialofa givennumber

ALGORITHM:

Step 1. Start the

programStep2.Getthe

number

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

factorial”Step4.ElseInitializevariablesfactorial←1i←1

Step 5. Readvalueofn

Step6. Repeatthestepsuntili=n6.1:factorial←factorial,

i←i+1Step 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
{

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.
EX8
PROGRAMTOFIND OUTTHEAVERAGEOF4INTEGERS

DATE:

AIM:
Tofindaverageof4 integers

ALGORITHM:

Step1.Start

Step2.DeclarevariablesStep3

.Read the 4

numbersStep4.Calculateavg

=sum/nStep 5. Display the

outputStep6.Stop

PROGRAM:

#include<stdio.h>
voidmain()

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

clrscr();

printf("\nEnterthenumbers\n");

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

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

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

OUTPUT:

Enter the

numbers32

45

54

22

Average is38.25

RESULT

ThustheCProgramtofindtheaverageof4numbershasbeenexecutedandverified.
EX9
PROGRAMTODISPLAYARRAYELEMENTSUSING2DARRAYS
DATE:

AIM:

Todisplayarrayelementsusing2Darrays

ALGORITHM:

Step1:Starttheprogram

Step2: Gettheelementsofthe

arrayStep 3 : Display the array

elementsStep4:Stoptheprogram

PROGRAM:

#include<stdio.h>

intmain(){

/* 2D array

declaration*/intdisp[2]

[3];

/*Counter variables for the

loop*/inti,j;

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

{for(j=0;j<3;j++){

printf("Entervaluefordisp[%d]

[%d]:",i,j);scanf("%d",&disp[i][j]);

//Displayingarrayelements

printf("Two Dimensional array elements:\


n");for(i=0;i<2;i++){
for(j=0;j<3;j++)

{printf("%d",disp[i]

[j]);if(j==2){

printf("\n");

return0;

OUTPUT:

Enter value for disp[0]

[0]:1Enter value for disp[0]

[1]:2Enter value for disp[0]

[2]:3Enter value for disp[1]

[0]:4Enter value for disp[1]

[1]:5Entervaluefordisp[1]

[2]:6

TwoDimensionalarrayelements:

123

456

RESULT:

Thus the C Program to display the array elements of the 2D array has been
executedandtheresultwas verified
EX10
PROGRAM TOPERFORMSWAPPINGUSINGFUNCTIONS
DATE:

AIM:

Toperformswappingusing functions

ALGORITHM:

Step1. Starttheprogram
Step2.

Declareandgetthetwointegervariablesaandb.Step3.
calltheswap()function
Inswapdefinitionusethetemporaryvariableandassigntemp =ab=temp

Step4. Print the a and b


valuesStep5. Stoptheprogram

PROGRAM:

#include<stdio.h>

voidmain()

void
swap(int,int);inta,
b,r;
clrscr();
printf("enter value for a&b:
");scanf("%d
%d",&a,&b);swap(a,b);
getch();

void swap(inta,int

b)inttemp;
temp=a;
a=b;
b=temp;
printf("afterswappingthevaluefora&bis:%d%d",a,b);

OUTPUT:

Enterthevalueofa&b:3478

afterswappingthe valuefora&b is78,34

RESULT:
ThustheCProgramtoswaptwonumbersusingfunctionshasbeenexecutedandverified
EX11
PROGRAM TO DISPLAY ALL PRIME NUMBERS
DATE: BETWEENTWOINTERVALSUSINGFUNCTIONS

AIM:

Todisplayallprimenumbersbetweentwointervalsusingfunctions

ALGORITHM:

Step1: Start the

ProgramStep2:Gettheint

ervals

Step3:Find and Displaytheprimenumbers ie.,thenumbersthataredivisibleby1anditself


betweentheintervals

Step4:StoptheProgram

PROGRAM:

#include<stdio.h>

/* Function declarations

*/intisPrime(intnum);

voidprintPrimes(intlowerLimit,intupperLimit);in

tmain()

int lowerLimit,upperLimit;

printf("Enterthelowerandupperlimit tolist primes:");scanf("%d

%d",&lowerLimit,&upperLimit);

/* Call function to print all primes between the given

range*/printPrimes(lowerLimit,upperLimit);

return0;
}

/*Printallprimenumbersbetweenlowerlimitand

upperlimit*/voidprintPrimes(intlowerLimit,intupperLimit)

printf("All prime number between %d to %d are: ", lowerLimit,

upperLimit);while(lowerLimit<=upperLimit)

/*Printifcurrentnumber

isprime*/if(isPrime(lowerLimit))

printf("%d,",lowerLimit);

lowerLimit++;

/*Checkwhether anumberisprimeornot*/

/*Returns 1 if the number is prime otherwise

0*/intisPrime(intnum)

inti;

for(i=2;i<=num/2;i++)
{

/*Ifthenumberisdivisiblebyanynumber*/

/*otherthan1andselfthenitisnotprime*/

if(num%i==0)

return0;

return1;

OUTPUT:

Enterthelowerandupperlimit tolistprimes:

1100

Allprimenumberbetween1 100 are 2,3,5,7,11,13, 17,19, 23,29,31, 37,41, 43,


47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97

RESULT:

ThustheCProgramtofindtheprime numbersbetweentwointervals
hasbeenexecutedandverified.
EX12
PROGRAMTOREVERSEASENTENCEUSINGRECURSION
DATE:

AIM:

Toreverseasentenceusingrecursion

ALGORITHM:

Step1: Start
Step2:Declarethe
functionreverseStep3: Callthe
reversefunction
Step 4: Get the sentence from the user and reverse it
recursivelyStep5:stopthe execution.

PROGRAM:

#include<stdio.h>void
reverseSentence();intm
ain(){
printf("Enterasentence:");reverseSentenc
e();
return0;
}

void reverseSentence()
{char c;
scanf("%c",&c);
if (c != '\n')
{reverseSentence(
);printf("%c", c);
}
}

OUTPUT:
Enter a sentence: margorp
emosewaawesomePROGRAM:

RESULT
ThustheCProgramtoreverseasentencehasbeenexecutedandverified
EX13
PROGRAMTOGETTHELARGESTELEMENTOFANARRAY
DATE: USINGFUNCTION

AIM:

Toget thelargestelementofanarrayusingfunction

ALGORITHM:

Step1:Starttheprogram
Step3:Initializethearrayelements
Step 4: Find the largest number of the
arrayStep5: Displaythelargestnumber
Step6:Stoptheprogram

PROGRAM:

#include

<stdio.h>#include

<conio.h>max(int[

],int);voidmain()

inta[]={10,5,45,12,19};

int

n=5,m;clr

scr();

m=max(a,n);

printf("\nmaximum number is

%d",m);getch();

max(intx[],intk)
{
intt,i;t

=x[0];

for(i=1;i<k;i++)

if(x[i]>t)

t=x[i];

return(t);

OUTPUT:

Maximumnumberis45

RESULT:

ThustheCProgramtodisplaythelargestnumberinanarrayusingfunctionhasbeenexecutedan
dverified.
EX14
PROGRAMTOCONCATENATETWOSTRINGS
DATE:

AIM:

Toconcatenatetwo strings

ALGORITHM:

Step1:Start
Step2:GetthetwoStringstobeconcatenated.
Step3: DeclareanewStringto
storetheconcatenatedString.Step4: Insert the firststringinthe
new string.
Step5:Insertthesecondstringinthenewstring.Step
6:Print the concatenatedstring.
Step7:Stop

PROGRAM:

#include
<stdio.h>#include
<string.h>intmain(
)
{

char destination[] = "Hello


";charsource[]="World!";
printf("Concatenated String: %s\n",
strcat(destination,source));return0;
}

OUTPUT:

ConcatenatedString:HelloWorld!
RESULT:

ThustheCProgramtoconcatenatetwostringshasbeenexecutedandtheresultwasverified.
www.Vidyarthiplus.com 51

EX15
PROGRAM TOFINDTHELENGTHOFSTRING
DATE:

AIM:

To find the length of the given

stringALGORITHM:

Step 1 : Start the

programStep2: Getthe

string

Step 3: Find the length of the

stringStep4:Displaythelengthofthestrin

gStep5:Stoptheprogram

PROGRAM:

i) UsingLibraryFunction

#include
<stdio.h>#include
<string.h>intmain(
)
{
char
a[100];intle
ngth;
printf("\n Enter a string to calculate its
length=");gets(a);
length=strlen(a);
printf("\nLength of the string = %d\n",
length);return0;
}

ii) WithoutUsingLibraryFunction
www.Vidyarthiplus.com 52

#include
<stdio.h>#include
<string.h>intmain( www.Vidyarthiplus.com
)
www.Vidyarthiplus.com 53

{
char
i=0;a[100];intle
ngth;
printf("\nEnter a string to calculate its
length=");scanf(“%s”,str);
while(string1[i] !='\0')
{i++;
}
length=i;
printf (“\n Length of the string = %d\
n",length);return0;
}

OUTPUT:

Enterastringtocalculateitslength=IntroductionLengt

hofthestring:12

RESULT:

ThustheCProgramtofindthelengthofthestringhasbeenexecuted andverified.

www.Vidyarthiplus.com
www.Vidyarthiplus.com 54

EX16
PROGRAMTOFINDTHEFREQUENCYOFACHARACTERIN
ASTRING
DATE:

AIM:

Tofind thefrequencyofacharacter inastring.

ALGORITHM:

Step 1 : Start the

programStep2:Get

thestring

Step3 :GetthecharacterforwhichfrequencyneedstobefoundStep4:

Displaythefrequency

Step5:Stoptheprogram

PROGRAM:

#include
<stdio.h>intmain(
){
char str[1000],
ch;intcount=0;

printf("Enter a string:
");fgets(str,sizeof(str),stdin
);

printf("Enter a character to find its frequency:


");scanf("%c",&ch);

for(inti=0;str[i]!='\0';++i)
{if(ch==str[i])
++count;

www.Vidyarthiplus.com
www.Vidyarthiplus.com 55
}

printf("Frequency of %c = %d", ch,


count);return0;

www.Vidyarthiplus.com
www.Vidyarthiplus.com 56

OUTPUT:

Enter a string: This website is

awesome.Enter a character to find its

frequency: eFrequencyofe=4

RESULT:

ThustheCProgramtofindthefrequencyofacharacterinastringhas beenexecutedandverified.

www.Vidyarthiplus.com
www.Vidyarthiplus.com 57

EX17
PROGRAMTOSTORESTUDENTINFORMATIONINSTRUCTURE
DATE: AND DISPLAYIT

AIM:

Tostorestudentinformationinstructureanddisplayit

ALGORITHM:

Step1:START
Step2:Readstudentdetailslikename,mark1,2,3Step3:
Calculate total,and average
Step 4: Display the
gradeStep5:STOP

PROGRAM:
#include<stdio.h>
structstudent
{
int roll_no, mark1, mark2, mark3,
total;floataverage;
charname[10],grade;
};
void struct_funct_student(struct student
stu);intmain()
{
structstudent stud;printf("\
nRoll
No.=");scanf("%d",&stud.r
oll_no);printf("Name=");
scanf("%s",stud.name);pri
ntf("Mark1=");scanf("%d"
,&stud.mark1);printf("Ma
rk2=");scanf("%d",&stud.
mark2);printf("Mark3=");

www.Vidyarthiplus.com
www.Vidyarthiplus.com 58

scanf("%d",&stud.mark3);
struct_funct_student(stud)
;return0;
}
voidstruct_funct_student(structstudentstu)
{
stu.total = stu.mark1 + stu.mark2 +
stu.mark3;stu.average=stu.total/3;
if(stu.average >=
90)stu.grade='S';
else if(stu.average >=
80)stu.grade='A';
else if(stu.average >=
70)stu.grade='B';
else if(stu.average >=
60)stu.grade='C';
else if(stu.average >=
50)stu.grade='D';
elsestu.grade
='F';
printf("\n ROLL NO. \t NAME \t TOTAL \t AVG \
tGRADE\n");
printf("%d\t%s\t%d\t%f\t
%c",stu.roll_no,stu.name,stu.total,stu.average,stu.gr
ade);
}

www.Vidyarthiplus.com
www.Vidyarthiplus.com 59

OUTPUT:

RollNo.= 1

Name=a

Mark1=95

Mark2=94

Mark3=96

ROLLNO. NAME TOTAL AVG GRADE

1 a 285 95.000000 S

RESULT:

ThustheCProgramtostoreanddisplaystudentdetailsusingstructureshasbeenexecutedandth
eresultwas verified.

www.Vidyarthiplus.com
www.Vidyarthiplus.com 60

EX18
PROGRAMTOREADTHESTUDENTDATAANDCALCULATETH
DATE: ETOTAL MARKS

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;

www.Vidyarthiplus.com
www.Vidyarthiplus.com 61

clrscr();for(i=0;i

<=9;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

RESULT:

ThustheCProgramtoprintthestudentdetailshasbeenexecutedandtheresultwasverified.

www.Vidyarthiplus.com
www.Vidyarthiplus.com 62

EX:19

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("telephone.dat","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:
www.Vidyarthiplus.com 63
display(fp); break;case 5:
search(fp);
break;default:;
}
www.Vidyarthiplus.com
}
www.Vidyarthiplus.com 64

fclose(fp);
return0;
}

voidinsert(FILE*fp)
{

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

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

voiddel(FILE*fp)
{
char name[20],
number[10];intresult,
record=0;
struct dir contact, blank = {"",
""};printf("Entername:");
scanf("%s",
name);rewind(fp);
www.Vidyarthiplus.com 65
while(!feof(fp))
{
result = fread(&contact, sizeof(struct dir), 1,
w w w
fp);if(result!=0&&strcmp(na m e ,
. V i d y a r th i pl u s .c om
c o n t a c t. n a m e ) = = 0)
{
www.Vidyarthiplus.com 66

fseek(fp, record*sizeof(struct dir),


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)
{
struct dir
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(struct dir), 1,
fp);if(result != 0 && strlen(contact.name) >
0)printf("%20s%10s\
n",contact.name,contact.number);
}
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(struct dir), 1,
fp);if(result!=0 &&strcmp(contact.name,name)==
0)
{
printf("\n%20s %10s\n",contact.name,
contact.number);return;
}
}
printf("Recordnotfound\n");

}
www.Vidyarthiplus.com 67

OUTPUT:

1insert 2update
68

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
69
3delete 4display
5search 6Exit
70

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.
71

EX:20
PROGRAMTOCOUNTTHENUMBEROFACCOUNT HOLDERS
WHOSEBALANCE IS LESS THAN THE MINIMUM BALANCE
DATE:
USINGSEQUENTIAL ACCESS FILE

AIM:
Tocountthenumberofaccountholderswhosebalanceislessthantheminimum
balanceusingsequentialaccessfile.

ALGORITHM:

Step1:Starttheprogram
Step2:Readchoicetoinsertrecords&countminimumbalanceaccount
1. Ifchoiceis1,then
 Openadatfileinwrite mode
 ReadtheNo. ofrecords
 Writetherecordsinto thefileusingfprintf()function
 Closethefile
2. IfChoiceis2,then
 OpenthefileinReadmode
 Readtherecordsonebyoneusingfscanf(0functionuntilreachtheend offile.
 Checktheaccountbalancewithminbal.
 Ifaccountbalanceislessthanminbalance, thendisplaytheaccountdetails
 Close the
fileStep3:Stoptheprogra
m

PROGRAM:

#include

<stdio.h>voidinse

rt();
voidcount();

int main(void)
{
intchoice=0;while(
choice!=3)
{
printf("\n1insertrecords\n");
printf("2 Count min balance holders\
72
n");printf("3Exit\n");
printf("Enter
choice:");scanf("%d",
&choice);
73

switch(choice)
{
case 1: insert();
break;case2:count();b
reak;
}
}
}

voidinsert()
{
unsigned int
account,i;charname[3
0];doublebalance;FIL
E*cfPtr;

if((cfPtr=fopen("clients.dat", "w"))==NULL)
{puts("File couldnotbeopened");
}
else{
intrecords,i=0;
printf("Enter the No. of records
");scanf("%d",&records);
while(i<records)
{
printf("Entertheaccount,
name,andbalance.");scanf("%d%29s
%lf",&account,name,&balance);fprintf(cfPtr,"%d%s
%.2f\n",account,name,balance);i++;
}
fclose(cfPtr);
}
}

voidcount()
{
unsigned int
account;char
name[30];doublebala
nce;
float minBal =
5000.00;intcount=0;
FILE*cfPtr;
if((cfPtr=fopen("clients.dat","r"))==NULL)pri
ntf("Filecouldnot be opened");
74
else
75

{
printf("%-10s%-13s%s\
n","Account","Name","Balance");fscanf(cfPtr,"%d%29s
%lf",&account,name,&balance);

while(!feof(cfPtr))
{
if(balance<minBal)
{
printf("%-10d%-13s%7.2f\
n",account,name,balance);count++;
}
fscanf(cfPtr,"%d%29s%lf",&account,name,&balance);
}

fclose(cfPtr);
printf("Thenumberofaccountholderswhosebalanceislessthantheminimumbalance:
%d",count);
}
}
76

OUTPUT:

1 insertrecords
2 Count min balance
holders3 Exit
Enterchoice:1
EntertheNo.ofrecords2
Enter the account, name, and balance.1001 A
10000Entertheaccount,name,andbalance.1002B300

1 insertrecords
2 Count min balance
holders3 Exit
Enterchoice:2
AccountName
Balance1002 B
300.00
Thenumberofaccountholderswhosebalanceis lessthanthe
minimumbalance:11insertrecords
2 Count min balance
holders3 Exit
Enterchoice:

RESULT:

ThustheCProgramtocountthenumberofaccountholderswhosebalanceislessthanthemin
imumbalanceusingsequentialaccessfile

You might also like