C Lab
C Lab
OBSERVATION
for
Name:……………………………………………………………..
Roll No:…………………………………………………………...
Class:………………………………………………………………
PSG POLYTECHNIC COLLEGE
DEPARTMENT OF COMPUTER NETWORKING
REGISTER NUMBER
2. Operators
a) Write a program to demonstrate arithmetic
operators and relational operators.
b) Write a program to demonstrate increment,
decrement, ternary and compound assignment
operators.
c) Write a program to calculate simple interest and
compound interest.
7. Strings
a) Write a program to illustrate how to initialize, read
and print the string.
b) Write a program to implement string manipulation
operations with library function.
i)length ii)copy iii)concatenate iv)compare
v)reverse.
8. Functions
a) Write a program to illustrate sum of two numbers
using all categories of user - defined function.
b) Write a program to find factorial of a given number
using recursion.
9. Storage Classes
a) Write a program to demonstrate storage classes.
b) Write a program to include your header file
Named “numops.h”.
Expt No Title
1 Basics
a) Write a program to print different data types in ‘C’ and their sizes.
10. Structures and Pointers
a) Write a program to create a structure called traveler
and members of the structure are train no, coach no,
seat no, source, destination, gender, age, name, and
departure date. Display the details of five passengers.
b) Write a program to swap two numbers using call by
value and call by reference.
c) Write a program to create a Linked List & display
the elements in the List.
Aim:
To write a program to print different data types in ‘C’ and their sizes.
Algorithm:
Program:
#include<stdio.h>
int main( )
{
int integerType;
float floatType;
double doubleType;
char charType;
getch( );
return 0;
}
Output:
Result:
Thus the C programming to Print the different data types and their size is written and executed
successfully.
Expt No Title
1 Basics
a) Write a program to declare variables of different data types get the value from the
user and print the values.
Aim:
To write a program to declare variables of different data types get the value from the user and print the
values.
Algorithm:
Step2: Read a, b, c
Step3: Print a, b, c
Program:
#include<stdio.h>
#include<conio.h>
void main( )
int a;
float b;
char c;
clrscr( );
printf("Enter three value of integer, float and char data type respectively");
getch( );
}
Output:
Result:
Thus the C program to declare variables of different data types get the value from the user and print the
Aim:
Algorithm:
Step1: Start the Program
Step 2: Read a,b
Step 3: calculate add=a+b
Step 4: calculate sub= a-b
Step 5: calculate mul= a*b
Step 6: calculate div=a/b
Step7: calculate mod=a%b
Step 8: Print add, sub, mul, div, mod
Step 9: Check if a = = b and print the result
Step10:Check if a! =b and print the result
Step11:Check if a > b and print the result
Step12:Check if a < b and print the result
Step13:Check if a > =b and print the result
Step14:Check if a < =b and print the result
Step 15:Stop the Program
Program:
#include<stdio.h>
#include<conio.h>
void main( )
{
inta,b,add,sub,mul,div,mod;
clrscr( );
printf("Enter any two values");
scanf("%d %d", Ca, Cb);
add=a+b;
sub = a-b;
mul = a*b;
div = a/b;
mod=a%b;
printf("Addition of a,b is:%d\n", add);
printf("Subtraction of a,b is:%d\n", sub);
printf("Multiplication of a,b is:%d\n", mul);
printf("Division of a,b is:%d\n", div);
printf("Modulus of a,b is:%d\n", mod);
//Relational Operations
printf("Relational operations:\n");
printf("a==b:%d\n", a==b);
printf("a!=b:%d\n", a!=b);
printf("a>b:%d\n", a>b);
printf("a<b:%d\n", a<b);
printf("a>=b:%d\n", a>=b);
printf("a<=b:%d\n", a<=b);
getch( );
}
Output:
Result:
Thus the c program to demonstrate arithmetic operators and relational operators were written
and executed successfully.
Expt No Title
2 b) Write a program to demonstrate increment, decrement, ternary and
compound assignment operators.
Aim:
Algorithm:
Step:1: Start the Program
Step:2: Declare the necessary header files and variables
Step:3: Get the input from the user
Step:4: Increment the value using increment operator
Step:5: Print the result
Step:6: Use pre-decrement and post-decrement operator
Step:7: Print the result
Step:8: Read the value of a and b,
Step:9: Print the large number using ternary operator
Step:10: Read the in value for compound assignment
Step:11: Calculate all the arithmetic operation using compound assignment
Step:12: Stop the Program
Program:
#include <stdio.h>
int main( )
{
int a, b, c, d;
// Increment Operator
printf("Enter any Intiger: ");
scanf("%d", &a);
a++;
printf("\nPost Increment value: %d\n", a);
++a;
printf("\nPre Increment value: %d\n", a);
// Decrement Operator
printf("\nEnter any Intiger: ");
scanf("%d", &a);
a--;
printf("\nPost Decrement value: %d\n", a);
--a;
printf("\nPre Decrement value: %d\n", a);
// Ternary Operator
printf("\nEnter two intiger: ");
scanf("%d %d", &a, &b);
c = (a > b ? a : b);
printf("\nLargest value (c) = %d\n", c);
// Compound Assignment Operators
printf("\nEnter any intiger: ");
scanf("%d", &d);
d += 10;
printf("Addition: %d\n", d);
d -= 10;
printf("Subtraction: %d\n", d);
d *= 10;
printf("Multiplication: %d\n", d);
d /= 10;
printf("Division: %d\n", d);
d %= 10;
printf("Modulus Division: %d\n", d);
d &= 10;
printf("Bitwise AND: %d\n", d);
d ^= 10;
printf("Bitwise XOR: %d\n", d);
return 0;
}
Output:
Result:
Aim:
Algorithm:
Step1: Start the Program
Step2: Input the Principal, Rate, and Time
Step3: Calculate simple interest using the formula SI=(P*R*T) / 100
Step4: Input the number of times interest is compounded per year(n)
Step5: Calculate compound interest using the formula CI=P*(1+R/(100*n))^(n*T)– P
Step5: Print the calculated simple interest
Step6: Print the calculated compound interest
Step 7: Stop the Program
Program:
#include<stdio.h>
#include<conio.h>
#include<math.h>
int main()
{
float P, R, T, SI, CI;
int n;
clrscr( );
printf("Enter the principal amount:"); //Input principal, rate, and time
scanf("%f",&P);
printf("Enter the annual interest rate (in percentage): ");
scanf("%f",&R);
printf("Enter the time period(in years): ");
scanf("%f",&T);
SI=(P*R*T)/100; //Calculate simple interest
printf("Enter the number of times interest is compounded per year:");
scanf("%d",&n);
CI=P*pow((1+R/(100*n)),n*T)-P; //Calculate compound interest
printf("Simple Interest:%.2f\n",SI);
printf("CompoundInterest:%.2f\n",CI); getch();
return0;
}
Expt No Title
Control Flow–I (Decision Making Statements)
3 a) Write programs to read marks of a student in six subjects and print whether pass or
Fail using if-else.
Output:
Result:
Thus a C program to calculate simple interest and compound interest was implemented
and executed successfully.
Aim:
To write a c program to read marks of a student in six subjects and print whether Pass or Fail using
if-else.
Algorithm:
Step1:Start the Program
Step2:Read the values m1,m2,m3,m4,m5,m6
Step3:calculate total=m1+m2+m3+m4+m5+m6
Step4:Calculate per=total*100/600
Step5:if((m1>40)CC(m2>40)CC(m3>40)CC(m4>40)CC(m5>40)CC(m6>40)) else goto
Step13
Step6:if(per>=60CCper<=100)
Step7:Print “FirstClass”
Step8:elseif(per>=50CCper<=60)
Step9:Print“SecondClass”
Step10:elseif(per>=40CCper<=50)
Step 11:Print" Thirdclass"
Step12:elsePrint“Youarefail”
Step13:Print“Youarefail”
Step14:Stop the Program
Program:
#include<stdio.h>
#include<conio.h>
Void main()
{
int m1,m2,m3,m4,m5,m6,total;
float per;
clrscr();
printf("Enter6subjectmarks."); scanf("%d%d%d%d%d
%d",Cm1,Cm2,Cm3,Cm4,Cm5,Cm6);total=m1+m2+m3+m4+m5+m6;
per=total*100/600;
if((m1>40)CC(m2>40)CC(m3>40)CC(m4>40)CC(m5>40)CC(m6>40))
{
if(per>=60CCper<=100)
printf("First Class:");
elseif(per>=50CCper<=60)
printf("Second Class");
elseif(per>=40CCper<=50)
printf("Third class");
else
printf("You are Fail");
}
else
printf("You are fail");
getch();
Output:
Result:
Thus a program to find solve quadratic equation was implemented and executed successfully.
Expt No Title
3 Control Flow–I (Decision Making Statements)
b)Consider the following rates charged by a mobile operator for data consumption in
integral units of GB.
S.No Data(GB) Rate
1 1GB Rs.150
2 2GB Rs.250
3 3GB Rs.350
4 4to6 GB Rs.450
5 7GB Onwards Rs.700
Aim:
To write a C program to read the data consumption in integral units of GB and print the
corresponding rate charged by a mobile operator using if-else decision-making statements.
Algorithm:
Step5:Else, go to Step4
Step8:Else, go to Step 5
Step11:Else, go to Step6
Step14:Else, go to Step 7
Step15:Check if the data consumption is 7 or more
Step17:Else, go to Step8
Step18:Print"Invalid data input" if none of the above conditions are met and end the program
Program:
#include<stdio.h>
#include<conio.h>
int main( )
{
int dataGB;
int rate;
printf("Enter the data consumption in GB:"); //Input the data consumption in GB
scanf("%d",&dataGB);
if(dataGB==1) //Determine the rate based on the data consumption
{
rate=150;
}
elseif(dataGB==2)
{
rate=250;
}
elseif(dataGB==3)
{
rate=350;
}
elseif(dataGB>=4&&dataGB<=6)
{
rate=450;
}
elseif(dataGB>=7)
{
rate=700;
}
else
{
printf("Invalid data input.\n");
return1;
}
printf("The rate for %d GB of data consumption is Rs.%d\n", dataGB, rate);
return0;
}
Output:
Result:
Thus, a c program to read the data consumption in integral units of GB and print the
corresponding rate charged by a mobile operator using if-else decision-making statements is
successfully executed.
Expt No Title
3 Control Flow–I (Decision Making Statements)
b) Write a C program using switch case that accepts an integer from the keyboard and
prints the corresponding rates after validation.
Aim:
To write a C program that accepts an integer representing data consumption in GB from the keyboard
and prints the corresponding rate charged by a mobile operator using a switch-case statement after
validating the input.
Algorithm:
Step1:Start the Program
Step2:Read the value of data consumption in GB from the keyboard
Step3:Use a switch-case statement to determine the rate based on the data consumption
Step4:Case1:If data GB is1,set rate to 150
Step5:Case2:If data GB is 2,set rate to 250
Step6:Case3:If data GB is 3,set rate to 350
Step7:Case4:If data GB is 4,5,or 6,set rate to 450
Step8:Default: If data GB is 7 or more, set rate to 700
Step9:Default: If data GB is less than1, print "Invalid data input" and exit
Step10:Print the rate for the given data consumption
Step11:Stop the Program
Program:
#include<stdio.h>
#include<conio.h>
int main( )
{
Int dataGB;
int rate;
scanf("%d",&dataGB);
switch(dataGB)
{
case1:
rate=150;
break;
case2:
rate=250;
break;
case3:
rate=350;
break;
case 4 :
case 5:
case 6:
rate=450;
break;
default:
if(dataGB>=7)
{
rate=700;
}
else
{
printf("Invalid data input.\n");
return1;
}
break;
}
//Output the rate
printf ("The rate for %d GB of data consumption is Rs.%d\n", dataGB, rate);
getch( );
return0;
}
Output:
Result:
Thus, a C program that accepts an integer representing data consumption in GB, validates
the input, and uses a switch case to print the corresponding rates was implemented and executed
successfully.
Ex No Title
4 Control Flow –II (Looping Statements)
a) Write a program to print all natural numbers and reverse of the natural numbers from 1
to n using while loop.
Aim:
To write a C program that prints all natural numbers from 1to n and the irreverse order using a while
loop.
Algorithm:
Step6:Increment i by1
Step7:Initialize a variable j to n
Step 10:Decrement j by 1
Program:
#include<stdio.h>
#include<conio.h>
int main()
{
int n,i=1,j;
clrscr();
printf("Enter the value of n:");
scanf("%d",&n);
printf("Natural numbers from 1 to %d:\n", n);
while(i<=n) //Use a while loop to print natural numbers from 1 to n
{
printf("%d",i);
i++;
}
printf("\n");
printf("Natural numbers from %d to 1:\n", n);
j = n;
while(j>=1) //Use a while loop to print natural numbers from n to 1
{
printf("%d", j);
j--;
}
printf("\n");
getch( );
return0;
}
Output:
Result:
Thus, a program to print all natural numbers and their reverse from 1 to n was implemented
and executed successfully.
Expt No Title
4 Control Flow –II (Looping Statements)
b) Write a program to find Fibonacci series of a given number
Aim:
To write a C program that finds and prints the Fibonacci series up to a given number.
Algorithm:
Step3: Initialize the first two terms of the Fibonacci series: a=0 and b=1
Step5: Use a while loop to generate and print the next terms of the Fibonacci series until
then-th term
Program:
#include<stdio.h>
#include<conio.h>
int main( )
{
int n, a=0, b=1, next,i=1;
printf("Enter the value of n:");
scanf("%d",Cn);
printf("Fibonacci series upto %d terms:\n", n);
if (n >= 1)
{
printf("%d",a);
}
if(n>=2)
{
printf("%d",b);
}
while(i<=n-2)
{
next = a + b;
printf("%d", next);
a=b;
b=next;
i++;
}
printf("\n");
return 0;
}
Output:
Result:
Thus, a program to find and print the Fibonacci series up to a given number was
implemented and executed successfully.
Expt No Title
4 Control Flow –II (Looping Statements)
C)Write a program to print multiplication table of any number
Aim:
To write a C program that prints the multiplication table of any given number.
Algorithm:
Step1: Start the Program
Step2: Read the value of n from the keyboard
Step3: Initialize a loop variable i to 1
Step4: Use a while loop to print the multiplication table of the given number up to 10
Step5: Print the result of the multiplication of the number with i
Step6: Increment i by1
Step7: Stop the Program
Program:
#include<std
io.h>
#include<co
nio.h>
int main( )
{
Int number, i=1;
printf("Enter the number to print its multiplication table:");
scanf("%d", &number);
printf("Multiplication table of %d:\n", number);
while (i <= 10)
{
printf("%dx%d=%d\n",number,i,number*i);
i++;
}
Return 0;
}
Output:
Result:
Thus a program to find and print the Fibonacci series up to a given number was
implemented and executed successfully.
Ex No Title
5 Control Flow–III (Looping Statements)
a) Write a program to print Pascal Triangle
Aim:
Algorithm:
Step 1: Start the Program
Step 2: Read rows
Step 3: Repeat for i=0 to <rows
Step 4: Repeat for space=1to<=rows
Step 5: print “ “
Step 6: Repeat step j=0 to <=i
Step 7: If(j==0||i==0)
Step 8: coef=1
Step 9: coef =coef*(i-j+1)/j;
Step 10: Print coef
Step 11: Print\n
Step 12: Stop the Program
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int rows, coef=1,space, i, j;
clrscr();
printf("Enter number of rows:");
scanf("%d",&rows);
for(i=0;i<rows;i++)
{
for(space=1;space<=rows-i;space++)
printf("");
for(j=0;j<=i; j++)
{
if(j==0||i==0)
coef = 1;
else
coef=coef*(i-j+1)/j;
printf("%4d",coef);
}
printf("\n");
}
getch();
}
Output:
Result:
Thus a Program to print Pascal Triangle was implemented and executed successfully.
Expt No Title
5 Control Flow –II(Looping Statements)
b)Write a program to find the sum of individual digits of a positive integer and test given
number is palindrome.
Aim:
To write a Program to find the sum of individual digits of a positive integer and test given number is
palindrome.
Algorithm:
Step4: Calculate digit, sum Of Digits, rn and number while number not equal to 0.
Step6: if rn==on
Program:
#include<stdio.h>
#include<conio.h>
#include<math.h>v
oidmain ()
intnumber=0,digit=0,sumOfDigits=0,rn=0,on; clrscr();
printf("Enteranynumber\n");
scanf("%d",Cnumber);
on=number;
while(number!=0)
digit=number%10;
sumOfDigits=sumOfDigits+digit;
rn=rn*10+digit;
number=number/10;
printf("Sumofindividualdigitsofagivennumberis%d\n",sumOfDigits); if(rn==on)
printf("%disapalindromenumber",on);
else
printf("%disnotapalindromenumber",on);
getch();
Output:
Result:
ThusaProgramtofindthesumofindividualdigitsofapositiveintegerandtest
givennumberispalindromewasimplementedandexecutedsuccessfully.
Expt No Title
6 Arrays(1D &2D)
a)Writeaprogramtostoreelementsinthe1-Darrayandprintthe elements in
ascending order.
Aim:
TowriteaProgramtostoreelementsinthe1-Darrayandprinttheelementsin
ascendingorder.
Algorithm:
Step1:StarttheProgram Step 2:
Read n
Step3:RepeatFori=0,1,2,3…n-1; Step
4: Readarr[i]
Step5:RepeatFori=0,1,2,3…n-1
RepeatForj=i+1,1,2,3…n-1
if(arr[i]>arr[j])
temp=arr[i]; arr[i]
=arr[j]; arr[j]
=temp;
Step6:RepeatFori=0,1,2,3…n-1
Step7:Printarr[i]
Step9:StoptheProgram
Program:
/*Cprogramtosortanonedimensionalarrayinascendingorder.*/ #include<stdio.h>
#include<conio.h>#d
intmain()
{
intarr[MAX],n,i,j;
inttemp; clrscr();
printf("Entertotalnumberofelements:");
scanf("%d",Cn);
//readarrayelements
printf("Enterarrayelements:\n");
for(i=0;i<n;i++)
printf("Enterelement%d:",i+1);
scanf("%d",Carr[i]);
//sortarray
for(i=0;i<n;i++)
for(j=i+1;j<n;j++)
if(arr[i]>arr[j])
temp=arr[i]; arr[i]
=arr[j]; arr[j]
=temp;
}
printf("\nArrayelementsaftersorting:\n");
for(i=0;i<n;i++)
printf("%d\n",arr[i]);
getch();
Output:
Result:
Thusaprogramtostoreelementsinthe1-Darrayandprinttheelementsin
ascendingorderwasimplementedandexecutedsuccessfully.
Expt No Title
6 Arrays(1D &2D)
b)Writeaprogramtoprintthetransposeofamatrix.
Aim:
TowriteaProgramtoprintthetransposeofamatrix.
Algorithm:
Step1:StarttheProgram Step 2:
Read r,c
Step3:RepeatForI=0,1,2,3…r-1;
RepeatForj=0,1,2,3…c-1;
Reada[i][j]
Step4:RepeatForI=0,1,2,3…r-1;
RepeatForj=0,1,2,3…c-1;
Reada[i][j]
Step5:RepeatForI=0,1,2,3…r-1;
RepeatForj=0,1,2,3…c-1;
transpose[j][i]=a[i][j]
Step6:RepeatForI=0,1,2,3…r-1;
RepeatForj=0,1,2,3…c-1;
Printtranspose[i][j]
Step7:StoptheProgram
Program:
#include<stdio.h>#i
nclude<conio.h>int
main()
{
inta[10][10],transpose[10][10];
intr,c,i,j;
clrscr();
printf("Enterrowsandcolumnsofmatrix:");
printf("\nEnterelementsofmatrix:\n");//Storingelementsofthematrix for(i=0;i<r;++i)
for(j=0;j<c;++j)
printf("Enterelementa%d%d:",i+1,j+1);
scanf("%d",Ca[i][j]);
+i)
for(j=0;j<c;++j)
printf("%d",a[i][j]);
printf("\n");
for(i=0;i<r;++i) //FindingTransposeMatrix
{
for(j=0;j<c;++j)
transpose[j][i]=a[i][j];
printf("\nTransposeofMatrix:\n");//Displayingthetransposeofmatrixa for(i=0;i<c;++i)
for(j=0;j<r;++j)
printf("%d ",transpose[i][j]);
printf("\n");
getch();//Waitforuserinputbeforeclosingtheprogram return0;
Output:
Result:
Thus,aprogramtoprintthetransposeofamatrixwasimplementedandexecuted successfully.
Expt No Title
7 Strings
a)Writeaprogramtoillustratehowtoinitialize,readandprintthe string.
Aim:
TowriteaProgramtoillustratehowtoinitialize,readandprintthestring.
Algorithm:
Step1:StarttheProgram
Step2:Initializestr
Step4:Readname
Step5:Readstr1(usinggets)
Step6:Printstr1(usingputs) Step
7: Stop theProgram
Program:
#include<stdio.h>
#include<conio.h>v
oidmain()
charname[20], str1[20];
charstr[6]={'H','E','L','L','O'};
clrscr();
printf("InitializedStringis%s\t",str);
printf("Enteranystring:\n");
gets(name);
printf("Enteredstringis%s.\n",name);
printf("Enteranothername\n");
gets(str1);
printf("Theenteredstringisreadandwrittenthroughgetsandputsstring funtions\n");
puts(str1);
getch();
Output:
Result:
Aim:
TowriteaProgramtoimplementstringmanipulationoperationswithvariouslibrary
functions.
Algorithm:
Step1:StarttheProgram Step 2:
Read ch
Step3:switch(ch)
Step 4: case 1:
Readstr1
Performi=strlen(str1)
Printi
Step5:case2:
Readstr1
Performstrrev(str1)
Printstr1
Step 6: case 3:
Performstrcat(str1,str2)
Printstr1
Step 7: case 4:
Readstr1
Performstrcpy(str1,str2)
Printstr1
Step8: case 5:
Readstr1,str2
Performstrcmp(str1,str2)
Iftrue
Printstringsareequal else
Printstringsarenotequal
Step 9: case 6
Exit();
Step10:StoptheProgram
Program:
#include<stdio.h>#i
nclude<string.h>
#include<stdlib.h>v
oidmain()
charstr1[20],str2[20];
intch,i,j;
do
printf("\tMENU");
printf("\n \n");
printf("1:FindLengthofString"); printf("\
n2:FindReverseofString"); printf("\
n3:ConcatenateStrings"); printf("\
n5:CopyString"); printf("\
n5:CompareStrings"); printf("\n6:Exit");
printf("\n \n");
printf("\nEnteryourchoice:");
scanf("%d",Cch);
switch(ch)
case1:
printf("EnterString:");
scanf("%s",str1);
i=strlen(str1);
printf("LengthofString:%d\n\n",i); break;
case2:
printf("EnterString:");
scanf("%s",str1);
strrev(str1);
printf("Reversestring:%s\n\n",str1);
break;
case3:
scanf("%s",str1);
printf("EnterSecondstring:");
scanf("%s",str2);
strcat(str1,str2);
printf("StringAfterConcatenation:%s\n\n",str1); break;
case4:
printf("Enter a String1:");
scanf("%s",str1); printf("Enter
a String2:"); scanf("%s",str2);
printf("\nStringBeforeCopied:\nString1=\"%s\",String2=\"%s\"\n",str1,str2);
strcpy(str2,str1);
printf(" \n");
printf("\"WearecopyingstringString1toString2\"\n");
printf(" \n");
printf("StringAfterCopied:\nString1=\"%s\",String2=\"%s\"\n\n",str1,str2); break;
case5:
scanf("%s",str1);
printf("EnterSecondString:");
scanf("%s",str2);
j=strcmp(str1,str2);
if(j==0)
printf("StringsareSame\n\n");
}
else
printf("StringsareNotSame\n\n");
break;
case6:
exit(0);
break;
default:
printf("InvalidInput.PleaseEntervalidInput.\n\n");
}while(ch!=6);
getch();
Output:
Result:
Thusaprogramtoimplementstringmanipulationoperationswithlibraryfunction.
waswrittenandexecutedsuccessfully.
Expt No Title
8 Functions
a) Write a program to illustrate sum of two numbers using all categories ofuser
defined function.
Aim:
TowriteaProgramtoillustratesumoftwonumbersusingallcategoriesofuser
definedfunction.
Algorithm:
Step1:StarttheProgram Step 2:
sumwoa()
Step3:Reada,b
Step4:calculatec=a+b
Step 5: print c
Step7:sumwa(a,b)
Step8:calculatec=a+b
Step 9: print c
Step10:callsumwr(); Step
11: Read a, b
Step12:calculatec=a+b Step
13: return c
Step15:Reada,b
Step16:calculatec=a+b Step
17: return c
Step18:printc
Step19:StoptheProgram
Program:
#include<stdio.h>
#include<conio.h>v
oidsumwoa();
voidsumwa(int,int);
intsumwr();
int sumwawr(int,int);
voidmain()
inta,b,c,d,m,n;
clrscr();
sumwoa();
printf("Entertwonumbers");
scanf("%d%d",Ca,Cb); sumwa(a,b);
c=sumwr();
printf("Sumperformedusingwithoutargumentsandwithreturnvalue:%d\n",c);
printf("Entertwonumbers");
scanf("%d%d",Cm,Cn);
d=sumwawr(m,n);
printf("Sumperformedusingwithargumentsandwithreturnvalue:%d\n",d); getch();
voidsumwoa()
intx,y,z;
printf("Entertwonumbers");
z=x+y;
printf("Sumperformedusingwithoutargumentsandwithoutreturnvalue
%d\n",z);
voidsumwa(intx,inty)
intz;
z=x+y;
printf("Sumperformedusingwithargumentsandwithoutreturnvalue
%d\n",z);
intsumwr()
intx,y,z;
printf("Entertwonumbers");
z=x+y;
returnz;
intsumwawr(intx,inty)
intz;
z=x+y;
returnz;
}
Output:
Result:
ThusaProgramtoillustratesumoftwonumbersusingallcategoriesofuserdefined
functionwasimplementedandexecutedsuccessfully.
Expt No Title
8 Functions
b)Writeaprogramtofindfactorialofagivennumberusingrecursion.
Aim:
TowriteaProgramtofindfactorialofagivennumberusingrecursion.
Algorithm:
Step1:StarttheProgram Step 2:
Read num
Step3:if(num<0)
Step4:Printfactorialnotpossible Step
5: else
Step6:calculateresult=fact(num)
Step7:ifnum==0||num==1 return1
Step8:else
return(num*fact(num-1)) Step
9:Print result
Step10:StoptheProgram
Program:
#include<stdio.h>
#include<conio.h>in
tfactorial(int);
voidmain()
intnum;
intresult;
clrscr();
printf("Enteranumbertofindit'sFactorial:");
scanf("%d",Cnum);
if(num<0)
printf("Factorialofnegativenumbernotpossible\n");
else
result=factorial(num);
printf("TheFactorialof%dis%d.\n",num,result);
getch();
intfactorial(intnum)
if(num==0||num==1)
return1;
else
return(num*factorial(num-1));
Output:
Result:
Aim:
TowriteaProgramtodemonstratestorageclasses.
Algorithm:
Step1:Start
Step2:initializex=9(asexternvariable)
Step3:initializez=10(asglobalvariable)
Step4:initializea=32(asautomaticvariable)
Step5:initializeb=’G’(asregistervariable)
Step6:initializeb=’G’(asregistervariable)
Step7:Print‘HelloWorld’
Step 8: print a
Step10:printx,z Step
11: print b
Step12:Modifyx=2
Step13:Modifyz=5
` Step14:print x,z
Step15:Repeat(x>0)
Initializestaticvariabley=5 y++
printy
x—
Step16:Print“Bye!Seeyouagain”
Step17:Stop
Program:
#include<stdio.h>
#include<conio.h>
intmain()
autointa=32;//Automaticvariable
registercharb='G';//Registervariable inti;
clrscr();
printf("HelloWorld!\n");
printf("Valueof'a'(autointeger):%d\n",a);
printf("Valuesof'x'and'z'(externintegers):%dand%d\n",x,z);
printf("Valueof'b'(registercharacter):%c\n",b);
x = 2; //Modifyglobalvariable'x'z=5;
//Modifyglobalvariable'z'
printf("Modifiedvaluesof'x'and'z':%dand%d\n",x,z);
printf("'y'isastaticvariableanditsvalueisnotinitializedto5afterthefirst iteration:\n");
for(i=0;i<2;++i)
staticinty=5;//Staticvariable y++;
printf("Valueof'y'initeration%d:%d\n",i+1,y);
}
printf("Bye!Seeyousoon.:)\n");
getch();
return0;
Output:
Result:
Thus,aProgramtodemonstratestorageclasseswasimplementedandexecuted successfully.
Expt No Title
9 StorageClasses
b)Writeaprogramtoincludeyourheaderfilenamed“NUMOPS.H”.
Aim:
TowriteaProgramtoincludeyourheaderfilenamed“NUMOPS.H”.
Algorithm:
Step1:Start
Step2:CreateheaderfilenamedNUMOPS.H
theProgram
Program:
HeaderFileProgram:
//NUMOPS.H
#ifndefNUMOPS_H//Includeguard
#defineNUMOPS_H
intadd(inta,intb);//Functionprototype #endif //
NUMOPS_H
SaveCode
SaveAboveCodewith[.H]Extension.
Letnameofourheaderfilebename[NUMOPS.H]
MainProgramusingheaderfile#inc
lude<stdio.h>#include"NU
MOPS.H" voidmain()
{
intnum1=10,num2=10,num3; num3
= add(num1, num2);
printf("AdditionofTwonumbers:%d",num3); getch();
Output:
AdditionofTwonumbers:20
Result:
Thus,aProgramtoincludeyourheaderfilenamed“NUMOPS.H”wasimplemented
andexecutedsuccessfully.
Expt No Title
10 StructuresandPointers
a)Writeaprogramtocalculatethedifferencebetweentwotime periods.
Aim:
Towriteaprogramtocalculatethedifferencebetweentwotimeperiods.
Algorithm:
Step1:StarttheProgram
Step2:Declarestructure
readt2.hours,t2.minutes,t2.seconds
Step5:Difference(t1,t2,Cdiff)//Functioncall
calculate diff->seconds=t1.seconds-t2.seconds
Step8:If(t2.minutes>t2.minutes)--t2t2.minutes+=60 Step 9:
calculate differ->minutes=t1.minutes-t2.minutes;
Step10:calculatediffer->hours=t1.hours-t2.hours;
Step11:Stoptheprogram.
Program:
#include<stdio.h>
#include<conio.h>st
ructTIME
intseconds;
intminutes;
inthours;
};
voidDifference(structTIMEt1,structTIMEt2,structTIME*diff);
voidmain()
struct TIMEt1,t2,diff;
clrscr();
printf("Enterstarttime:\n");
printf("Enterhours,minutesandsecondsrespectively:"); scanf("%d
%d%d",Ct1.hours,Ct1.minutes,Ct1.seconds);
printf("Enterstoptime:\n");
printf("Enterhours,minutesandsecondsrespectively:"); scanf("%d%d
%d",Ct2.hours,Ct2.minutes,Ct2.seconds);
Difference(t1,t2,Cdiff);
printf("\nTIMEDIFFERENCE:%d:%d:%d -",t1.hours,t1.minutes,t1.seconds);
printf("%d:%d:%d",t2.hours,t2.minutes,t2.seconds);
printf("=%d:%d:%d\n",diff.hours,diff.minutes,diff.seconds); getch();
voidDifference(structTIMEt1,structTIMEt2,structTIME*differ)
if(t2.seconds>t1.seconds)
--t1.minutes;
t1.seconds+=60;
differ->seconds=t1.seconds-t2.seconds;
if(t2.minutes>t1.minutes)
{
--t1.hours;
t1.minutes+=60;
differ->minutes=t1.minutes-t2.minutes;
differ->hours=t1.hours-t2.hours;
Output:
Result:
Thus,aProgramtocountthelines,wordsandcharactersinagiventextusing
pointerswasimplementedandexecutedsuccessfully.
Expt No Title
10 StructuresandPointers
b)Writea program tomaintain a recordofn studentdetailsusinganarrayof structures
with four fields (Roll number, Name, Marks, and Grade). Assume
appropriatedatatype foreachfield.Printthemarksofthestudent,giventhe
student’snameasinput.
Aim:
TowriteaCProgramtomaintainarecordofnstudentdetailsusinganarrayof
structureswithfourfields(Rollnumber,Name,Marks,andGrade).
Algorithm:
Step1:StarttheProgram
Step2:DeclareStructure
Step3:Defineastructurestudentwithfieldsrollno(integer),name(string),and marks(integer)
Step3:Definefunctionprototypesforaccept,displayandsearch.Step4:Declarean
arraydataofstructstudenttoholdstudentrecords.
Step5:Declarevariablesn(numberofrecords),choice(menuchoice)andname1.
Step6:Prompttheusertoenterthenumberofrecords.
Step7:Callacceptfunctiontoinputstudentdetails.
Step8:Useadowhileloopfordisplayingamenuuntiltheuserchoosestoexit.
Step9:Useaswitchstatementbasedonchoice
11:Stop theProgram.
Program:
#include<stdio.h>
#include<conio.h>st
ructstudent
{
introllno;
charname[80];
intmarks;
};
voidaccept(structstudent[],int);
voiddisplay(structstudent[],int);
voidsearch(structstudent[],ints,charname1); intmain()
structstudentdata[20];
intn,choice;
charname1[80];
clrscr();
printf("Numberofrecordsyouwanttoenter?:");
scanf("%d",Cn);
accept(data,n); do
printf("\nResultMenu:\n");
printf("Press1todisplayallrecords.\n");
printf("Press2tosearcharecord.\n");
printf("Press0toexit\n");
scanf("%d",Cchoice);
switch(choice)
{
case1:
display(data,n);
break;
case2:
printf("Enternametosearch:");
gets(name1); search(data[],n,name1);
break;
while(choice!=0);
return0;
voidaccept(structstudentlist[80],ints)
inti;
for(i=0;i<s;i++)
printf("\nEnterdataforRecord#%d",i+1); printf("\
nEnterrollno:");
scanf("%d",Clist[i].rollno);
fflush(stdin);
printf("Entername:");
gets(list[i].name);
printf("Entermarks:");
scanf("%d",Clist[i].marks);
}
voiddisplay(structstudentlist[80],ints)
inti; printf("\n\nRollno\tName\tMarks\n");
for(i=0;i<s;i++)
printf("%d\t%s\t%d\n",list[i].rollno,list[i].name,list[i].marks);
voidsearch(structstudentlist[80],ints,charname1)
inti;
for(i=0;i<s;i++)
if(list[i].name==name1)
printf("Rollno:%d\nMarks:%d\n",list[i].rollno,list[i].marks); return;
printf("RecordnotFound\n");
}
Result:
Thusaprogramtomaintainarecordofnstudentdetailsusinganarrayofstructures
withfourfields(Rollnumber,Name,Marks,andGrade)wasimplementedandexecuted.
Expt No Title
10 Structuresand Pointers
C)WriteaprogramtocreateaLinkedList&displaythe elementsintheList.
Aim:
ToCreateaLinkedListCdisplaytheelementsintheList.
Algorithm:
Step1:StarttheProgram
Step2:Declarestructure
Step3:initialize*head,*first,*temp=0;
Step4:initializecount=0,choice=1 Step 5:
While (choice)
Step6:readhead->num
Step7:while(temp!=0)
Step8:printtemp->num
Step10:Stop
Program:
/*Cprogramtocreatealinkedlistanddisplaytheelementsinthelist*/
#include<stdio.h>
#include<conio.h>
#include<malloc.h>#i
nclude<stdlib.h>
voidmain()
structnode
{
intnum;
structnode*ptr;
};
NODE*head,*first,*temp=0; int
count = 0;
intchoice=1;
clrscr();
first=0;
while(choice)
head=(NODE*)malloc(sizeof(NODE));
printf("Enterthedataitem\n"); scanf("%d",
Chead-> num);
if(first!=0)
temp->ptr=head;
temp=head;
else
first=temp=head;
fflush(stdin);
printf("Doyouwanttocontinue(Type0or1)?\n");
scanf("%d",Cchoice);
}
temp->ptr=0;/*resettemptothebeginning*/ temp=first;
printf("\nstatusofthelinkedlistis\n");
while(temp!=0)
printf("%d=>",temp->num); count+
+;
temp=temp->ptr;
printf("NULL\n");
printf("No.ofnodesinthelist=%d\n",count); getch();
Output:
Result: