Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

C Programming Lab

Download as pdf or txt
Download as pdf or txt
You are on page 1of 51

C Program Using Simple Statement and Expressions

Ex.No : 1A Calculate Area and Circumference of Circle


Date :

Aim:
To write C program to calculate Area and Circumference of Circle.
Algorithm:

Step 1: Start
Step 2: Declare variables radius, area, circumference in float type
Step 3: Read radius of circle as radius
Step 4: Calculate area using the expression area = 3.14 * radius * radius
Step 5: Calculate circumference using the expression circumference=2*3.14*radius
Step 6: Print area and circumference
Step 7: Stop

Program:

#include<stdio.h>
int main() {
float radius, area,circumference;
printf("\nEnter the radius of Circle : ");
scanf("%f", &radius);
area = 3.14 * radius * radius;
circumference=2*3.14*radius;
printf("\nArea of Circle : %.2f", area);
printf("\nCircumference of Circle : %.2f", circumference);
return (0);
}

Output:

Enter the radius of Circle : 10


Area of Circle : 314
Circumference of Circle : 62.8

Result:

Thus, the C program to calculate Area and Circumference of Circle was


written executed and the output was verified successfully.

Page 1 of 51
Ex.No : 1B Simple Interest Calculation
Date :

Aim:
To write C program to calculate simple interest.
Algorithm:

Step 1: Start
Step 2: Declare Variables for Principal amount, Rate of interest, time
Step 3: Read Principal amount, Rate of interest, time
Step 4: Calculate interest amount using the expression amt=(p*r*t)/100
Step 5: Print amt
Step 6: Stop

Program:

#include<stdio.h>
int main()
{
int p,r,t,amt;
printf("Enter Principle amount, Rate of interest & time to find simple interest: \n");
scanf("%d%d%d",&p,&r,&t);
amt=(p*r*t)/100;
printf("Simple interest = %d",amt);
return 0;
}

Output:

Enter Principle amount, Rate of interest & time to find simple interest:
50000
7
3
Simple interest = 10500

Result:

Thus, the C program to calculate Simple Interest was written executed and
the output was verified successfully.

Page 2 of 51
Scientific Problem-Solving Using Decision Making and Looping

Ex No : 2A Largest of Three number


Date :

Aim:
To find the largest of three numbers using if...else if.

Algorithm:

Step 1: Start
Step 2: Read the values of x, y and z.
Step 3: If x is greater than y and x is greater than z then print x is greatest, otherwise
go to step 3.
Step 4: If y is greater than z then print y is greatest, otherwise go to step 4.
Step 5: Display z is greatest.
Step 6: Stop

Program:
#include<stdio.h>
void main()
{
int x,y,z;
printf("Enter the values for x,y and z \n");
scanf("%d%d%d",&x,&y,&z);
if((x>y)&& (x>z))
printf(" %d is greatest",x);
else if (y>z)
printf ("%d is greatest",y);
else
printf("%d is greatest",z);
}

Output:
Enter the values for x, y and z
32
12
20
32 is greatest

Result:

Thus, the C program to find the largest of three numbers using if...else if
was written executed and the output was verified successfully.

Page 3 of 51
Ex NO : 2B Leap Year or Not
Date :

Aim:
To find whether the given year is leap year or not.

Algorithm:

Step 1: Get the input year from the user to check for leap year.
Step 2: If the year is evenly divisible by 4, go to step 3. Otherwise, go to step 6.
Step 3: If the year is evenly divisible by 100, go to step 4. Otherwise, go to step 5.
Step 4: If the year is evenly divisible by 400, go to step 5. Otherwise, go to step 6.
Step 5: The year is a leap year (it has 366 days).
Step 6: The year is not a leap year (it has 365 days).

Program:

#include <stdio.h>
int main()
{
int year;
printf("Enter a year: ");
scanf("%d",&year);
if(year%4 == 0)
{
if( year%100 == 0)
{
// year is divisible by 400, hence the year is a leap year
if ( year%400 == 0)
printf("%d is a leap year.",
year); else
printf("%d is not a leap year.", year);
}
else
printf("%d is a leap year.", year );
}
else
printf("%d is not a leap year.", year);
return 0;
}
Output:
Enter a year: 2000
2000 is not a leap year.
Result:

Thus, the C program to find whether the given year is leap year or not was
written executed and the output was verified successfully.

Page 4 of 51
Ex No : 2C Armstrong Number or Not
Date :

Aim:
To check whether a given number is Armstrong number or not.

Algorithm:

Step 1: Initialize the value of res to 0.


Step 2: Read the three digit number in num variable to check for Armstrong number.
Step 3: Assign originalNum to the variable num.
Step 4: Extract the digits from the num.
Step 5: Find the cube of each digit in num and add them and store it in variable res.
Step 6: Repeat the step 5 untill the num is not equal to zero..
Step 7: Compare the res and originalNum, if it is equal display the number is an
Armstrong number, otherwise display the number is not an Armstrong
number.

Program:
#include <stdio.h>
int main()
{
int num, originalNum, rem, res = 0;
printf("Enter a integer: ");
scanf("%d", &originalNum);
num = originalNum;
while (num != 0)
{
rem = num%10;
res+= rem*rem*rem;
num /= 10;
}
if(res == originalNum)
printf("%d is an Armstrong number.",originalNum);
else
printf("%d is not an Armstrong umber.",originalNum);
return 0;
}
Output:

Enter a integer:
184
184 is not an Armstrong number
Result:

Thus, the C program check whether a given number is Armstrong number


or not was written executed and the output was verified successfully.

Page 5 of 51
Generating Different Patterns Using Multiple Control Statements

Ex No : 3A Generating Number Pattern


Date :

Aim:
To Generate following pattern in C Programing
1
123
12345
1234567
123456789
1234567
12345
123
1

Algorithm:

Step 1: Start
Step 2: Read Number of Rows to print
Step 3: Use outer loop for maintaining Number of rows
Step 4: Use Inner Loop appropriately for required Coolum output
Step 5: Print required numbers
Step 6: Stop

Program:

#include<stdio.h>
#include<conio.h>
int main()
{
int n, x, y, k;
printf("Enter the number of rows to show number paatern:
"); scanf("%d",&n);
for(x = 1; x <= n; x++)
{
for(y = x; y <n; y++)
{
printf(" ");
}
for(k = 1; k < (x*2); k++)
{
printf("%d",k);
}
printf("\n");
}

Page 6 of 51
for(x = 4; x >= 1; x--)
{
for(y = n; y > x; y--)
{
printf(" ");
}
for(k = 1; k < (x*2); k++)
{
printf("%d",k);
}
printf("\n");
}
return 0;
}

Output:

Enter the number of rows to show number paatern: 5


1
123
12345
1234567
123456789
1234567
12345
123
1

Result:

Thus, the C program to generate mentioned pattern was written executed and the
output was verified successfully

Page 7 of 51
Ex No : 3B Generating Symbol Pattern
Date :

Aim:
To Generate following pattern in C Programing
*******
******
*****
****
***
**
*
**
***
****
*****
******
*******

Algorithm:

Step 1: Start
Step 2: Read Number of Column to print
Step 3: Use outer loop for maintaining Number of rows
Step 4: Use Inner Loop appropriately for required Coolum output
Step 5: Print required symbol link space or *
Step 6: Stop

Program:

#include <stdio.h>
int main(void) {
int n;
printf("Enter the number of columns");
scanf("%d",&n);
for(int i=0;i<n;i++)
{
for(int j=0;j<i;j++)
{
printf(" ");
}
for(int k=1;k<=n-i;k++)
{
printf("*");
}
printf("\n");
}

Page 8 of 51
for(int i=1;i<n;i++)
{
for(int j=1;j<n-i;j++)
{
printf(" ");
}
for(int k=1;k<=i+1;k++)
{
printf("*");
}
printf("\n");
}
return 0;
}

Output:

Enter the number of columns7


*******
******
*****
****
***
**
*
**
***
****
*****
******
*******

Result:

Thus, the C program to generate mentioned pattern was written executed


and the output was verified successfully.

Page 9 of 51
Ex No : 3C Generating Letters Pattern
Date :

Aim:
To Generate following pattern in C Programing
A
ABA
ABCBA
ABCDCBA
ABCDEDCBA

Algorithm:

Step 1: Start
Step 2: Read Number of lines to print
Step 3: Use outer loop for maintaining Number of rows
Step 4: Use Inner Loop appropriately for required Coolum output
Step 5: Print required letter
Step 6: Stop

Program:

#include<stdio.h>
void main()
{
int i,n,j;
printf("Enter the no of lines\n");
scanf("%d",&n);

for(i=1;i<=n;i++)
{
for(j=1;j<=n-i;j++)
{
printf(" ");
}
for(j=1;j<=i;j++)
{
printf("%c",(char)(j+64));
}
for(j=i-1;j>=1;j--)
{
printf("%c",(char)(j+64));
}
printf("\n");
}
}

Page 10 of 51
Output:

Enter the no of lines


5
A
ABA
ABCBA
ABCDCBA
ABCDEDCBA

Result:

Thus, the C program to generate mentioned pattern was written executed and the
output was verified successfully.

Page 11 of 51
Problem Solving Using One Dimensional Array

Ex No : 4A Finding the sum of Array Elements.


Date :
Aim:
Write C program to find sum of array elements.
Algorithm:
Step 1: Start
Step 2: Read Number of elements in the array as n
Step 3: Initialize a variable s=0 for summation purpose
Step 4: Read n elements and store it in a array called a, using for loop
Step 5: Add elements with s while reading.
Step 6: Print value of s
Step 7: Stop

Program:
#include<stdio.h>
void main()
{
int i,n, a[10],s;
printf("Enter the number of element :\n");
scanf("%d",&n);
s=0;
printf("Enter element:\n");
for(i=0;i<n;i++)
{
printf("a[%d]=",i);
scanf("%d",&a[i]);
s=s+a[i];
}
printf("Sum of array element:%d",s);
}
Output:
Enter the number of element :
5
Enter element:
a[0]=20
a[1]=30
a[2]=40
a[3]=50
a[4]=60
Sum of array element:200
Result:

Thus, the C program to find sum of array elements was written executed
and the output was verified successfully.

Page 12 of 51
Ex No : 4B Insert an Element in an Array
Date :

Aim:
Write C program to Insert an Element in an Array.

Algorithm:
Step 1: Start
Step 2: Read Number of elements in the array as n
Step 3: Read n elements and store it in a array called a, using for loop
Step 4: Read element to be insert and position in num and pos
Step 5: From the end of the array, Using for loop start moving the elements
one index ahead till the required index reach.
Step 6: increase number of elements n by one
Step 7: Insert the element in the required index.
Step 8: Print all the elements.
Step 9: Stop

Program:

#include<stdio.h>
void main()
{
int i,n,pos,num, a[10];
printf("Enter the number of element :\n");
scanf("%d",&n);
printf("Enter element:\n");
for(i=0;i<n;i++)
{
printf("a[%d]=",i);
scanf("%d",&a[i]);
}
printf("\nEnter the pos where the no. is to be inserted
:"); scanf("%d",&pos);
printf("\nEnter the the no. is to be inserted :");
scanf("%d",&num);
for(i=n-1;i>=pos;i--)
a[i+1]=a[i];
n=n+1;
a[pos]=num;
printf("\n Display array after insertion:\n");
for(i=0;i<n;i++)
{
printf("a[%d]=%d\n",i,a[i]);
}
}

Page 13 of 51
Output:

Enter the number of element :


6
Enter element:
a[0]=6
a[1]=8
a[2]=9
a[3]=7
a[4]=1
a[5]=10

Enter the pos where the no. is to be inserted :3

Enter the the no. is to be inserted :30

Display array after insertion:


a[0]=6
a[1]=8
a[2]=30
a[3]=9
a[4]=7
a[5]=1
a[6]=10

Result:

Thus, the C program to Insert an Element in an Array was written executed


and the output was verified successfully.

Page 14 of 51
Mathematical Problem Solving Using two Dimensional Array

Ex No : 5A Add two Matrix


Date :

Aim:

Write C program to Add two Matrix.

Algorithm:

Step 1: Start
Step 2: Declare variables m,n,p,q for storing number of rows and columns of two matrix.
Step 3: Read Number of rows and columns of first matrix as m,n
Step 4: Read Number of rows and columns of second matrix as p,q
Step 5: Check whether m==p and n==q if so go to step 6 else print matrix
addition not possible and stop the program.
Step 6: Using two nested for loop read elements of first matrix
Step 7: Using two nested for loop read elements of second matrix
Step 8: Using two nested for loop add first matrix element and second
matrix element and store it in third matrix.
Step 9: Using two nested for loop print third matrix.
Step 10: Stop.

Program:

#include<stdio.h>
#include <stdlib.h>
void main()
{
int i,j,m,n,p,q;
int a[10][10], b[10][10], c[10][10];
printf("\nEnter no of rows and column of matrixA:");
scanf("%d%d",&m,&n);
printf("\nEnter no of rows and column of matrixB:");
scanf("%d%d",&p,&q);
if(m!=p && n!=q)
{
printf("\n Matrix cannot be added.");
exit(0);
}
printf("\n Matrix can be added");
printf("\n Enter elements of matrix A:");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
printf("\n Enter elements of matrix B:");

Page 15 of 51
for(i=0;i<p;i++)
for(j=0;j<q;j++)
scanf("%d",&b[i][j]);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
c[i][j]=a[i][j]+b[i][j];
printf("\n Display matrix A:\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
printf("%d\t",a[i][j]);
printf("\n");
}
printf("\n Display matrix B:\n");
for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
printf("%d\t",b[i][j]);
printf("\n");
}
printf("\n Display matrix C:\n");
for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
printf("%d\t",c[i][j]);
printf("\n");
}
}

Output:

Enter no of rows and column of matrixA:2


2

Enter no of rows and column of matrixB:2


2

Matrix can be added


Enter elements of matrix A:1
1
2
3

Enter elements of matrix B:5


4
5

Page 16 of 51
6

Display matrix A:
1 2
3 4

Display matrix B:
5 6
7 8

Display matrix C:
6 8
10 12

Result:

Thus, the C program to Add two Matrix was written executed and the
output was verified successfully.

Page 17 of 51
Ex No : 5B Multiply two Matrix
Date :

Aim:

Write C program to Multiply two Matrix.

Algorithm:

Step 1: Start
Step 2: Declare variables m,n,p,q for storing number of rows and columns of two matrix.
Step 3: Read Number of rows and columns of first matrix as m,n
Step 4: Read Number of rows and columns of second matrix as p,q
Step 5: Check whether n==p if so go to step 6 else print matrix multiplication
not possible and stop the program.
Step 6: Using two nested for loop read elements of first matrix
Step 7: Using two nested for loop read elements of second matrix
Step 8: Using three nested for loop multiply first matrix element and second
matrix element and store it in third matrix.
Step 9: Using two nested for loop print third matrix.
Step 10: Stop.

Program:

#include<stdio.h>
#include <stdlib.h>
void main()
{
int i,j,m,n,p,q,k;
int a[10][10], b[10][10], c[10][10];
printf("\nEnter no of rows and column of matrixA:");
scanf("%d%d",&m,&n);
printf("\nEnter no of rows and column of matrixB:");
scanf("%d%d",&p,&q);
printf("\n Enter elements of matrix A:\n");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
printf("\n Enter elements of matrix B:\n");
for(i=0;i<p;i++)
for(j=0;j<q;j++)
scanf("%d",&b[i][j]);
if(n==p)
{
for(i=0;i<m;i++)
for(j=0;j<q;j++)

Page 18 of 51
{
c[i][j]=0;
for(k=0;k<n;k++)
c[i][j]=c[i][j]+(a[i][k]*b[k][j]);
}
}
else
{
printf("\n Matrix cannot be multiplied");
exit(1);
}
printf("\n Display matrix A:\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
printf("%d\t",a[i][j]);
printf("\n");
}
printf("\n Display matrix B:\n");
for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
printf("%d\t",b[i][j]);
printf("\n");
}
printf("\n Display Product:\n");
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
printf("%d\t",c[i][j]);
printf("\n");
}
}

Output:

Enter no of rows and column of matrixA:2


3

Enter no of rows and column of matrixB:3


2

Enter elements of matrix A:


1
2
3

Page 19 of 51
4
5
6

Enter elements of matrix B:


7
8
9
10
11
12

Display matrix A:
1 2 3
4 5 6

Display matrix B:
7 8
9 10
11 12

Display Product:
58 64
139 154

Result:

Thus, the C program to Multiply two Matrix was written executed and the
output was verified successfully.

Page 20 of 51
Solving Problems Using String Functions

Ex No : 6Ai Length of a String without String Function


Date :

Aim:

Write C program to Find Length of a string without string function

Algorithm:

Step 1: Start
Step 2: Read a String and store it in s
Step 3: Initialize i=0 in for loop
Step 4: Use a for loop to iterate over all character of the string and check for
‘\0’ character, also increment i value
Step 5: When ‘\0’ found stop for loop and print i value as length of string
Step 6: Stop

Program:

#include <stdio.h>
int main()
{
char s[100];
int i;

printf("Enter a string: ");


scanf("%[^\n]", s);

for(i = 0; s[i] != '\0'; ++i);

printf("Length of string: %d", i);


return 0;
}

Output:

Enter a string: C Programming Lab


Length of string: 17

Result:

Thus, the C program to Find Length of a string without string function was
written executed and the output was verified successfully.

Page 21 of 51
Ex No : 6Aii Length of a String with String Function
Date :

Aim:

Write C program to Find Length of a string with string function

Algorithm:

Step 1: Start
Step 2: Read a String and store it in s
Step 3: Using strlen() function find the length of s and print
Step 4: Stop

Program:

#include <stdio.h>
#include<string.h>
int main()
{
char s[100];
printf("Enter a string: ");
scanf("%[^\n]", s);
printf("Length of string: %ld", strlen(s));
return 0;
}

Output:

Enter a string: C Programming Lab


Length of string: 17

Result:

Thus, the C program to Find Length of a string with string function was
written executed and the output was verified successfully.

Page 22 of 51
Ex No : 6Ai Copy of a String without String Function
Date :

Aim:

Write C program to copy a string without string function

Algorithm:

Step 1: Start
Step 2: Declare two character array named str, copystr
Step 3: Read a String and store it in str
Step 4: Using a for loop copy all the characters of str to copystr
Step 5: Add ‘\0’ at the end of Copystr
Step 6: Print copystr
Step 7: Stop

Program:

#include <stdio.h>
#include <string.h>
int main()
{
char Str[100], CopyStr[100];
int i;
printf("\n Please Enter any String : ");
gets(Str);
for (i = 0; Str[i]!='\0'; i++)
{
CopyStr[i] = Str[i];
}
CopyStr[i] = '\0';
printf("\n String that we coped into CopyStr = %s",
CopyStr); return 0;
}

Output:

Please Enter any String : Programming in C

String that we coped into CopyStr = Programming in C

Result:

Thus, the C program to copy a string without string function was written
executed and the output was verified successfully.

Page 23 of 51
Ex No : 6Bii Copy of a String with String Function
Date :

Aim:

Write C program to copy a string with string function

Algorithm:

Step 1: Start
Step 2: Declare two character array named str, copystr
Step 3: Read a String and store it in str
Step 4: Using strcpy() function copy content of str to copystr
Step 5: Print copystr
Step 6: Stop

Program:

#include <stdio.h>
#include <string.h>
int main()
{
char Str[100], CopyStr[100];
int i;
printf("\n Please Enter any String : ");
gets(Str);
strcpy(CopyStr,Str);
printf("\n String that we coped into CopyStr = %s",
CopyStr); return 0;
}

Output:

Please Enter any String : Programming in C

String that we coped into CopyStr = Programming in C

Result:

Thus, the C program to copy a string with string function was written
executed and the output was verified successfully.

Page 24 of 51
Ex No : 6Ci Compare two String without String Function
Date :

Aim:

Write C program to compare two string without string function

Algorithm:

Step 1: Start
Step 2: Define a user defined function called compare it will take two input strings
and return 0 if both strings are same, return 1 if both strings are different.
Step 3: Inside compare function using a while loop check both the strings index
by index, if all index elements are same then return 0 or else return 1
Step 4: In Main function Declare two character array named str1, str2
Step 5: Read two Strings and store it in str1, str2
Step 6: Call user defined compare function by passing str1,str2 as input
Step 7: If the function return 0 then print both strings are same else print both
strings are different
Step 8: Stop

Program:

#include <stdio.h>
int compare(char[],char[]);
int main()
{
char str1[20];
char str2[20];
printf("Enter the first string : ");
gets(str1);
printf("Enter the second string : ");
gets(str2);
int c= compare(str1,str2);
if(c==0)
printf("strings are same");
else
printf("strings are not same");

return 0;
}

int compare(char a[],char b[])


{
int flag=0,i=0;
while(a[i]!='\0' &&b[i]!='\0')

Page 25 of 51
{
if(a[i]!=b[i])
{
flag=1;
break;
}
i++;
}
if(flag==0)
return 0;
else
return 1;
}

Output:

Run 1:

Enter the first string : C Programming


Enter the second string : Language
strings are not same

Run2:

Enter the first string : C Programming Lab


Enter the second string : C Programming Lab
strings are same

Result:

Thus, the C program to compare two string without string function was
written executed and the output was verified successfully.

Page 26 of 51
Ex No : 6Cii Compare two String with String Function
Date :

Aim:

Write C program to compare two string with string function

Algorithm:

Step 1: Start
Step 2: Declare two character array named str1, str2
Step 3: Read two Strings and store it in str1, str2
Step 4: Call strcmp() function by passing str1,str2 as input
Step 5: If the function return 0 then print both strings are same else print both
strings are different
Step 6: Stop

Program:

#include <stdio.h>
#include<string.h>
int main()
{
char str1[20];
char str2[20];
int value;
printf("Enter the first string : ");
gets(str1);
printf("Enter the second string : ");
gets(str2);
value=strcmp(str1,str2);
if(value==0)
printf("strings are same");
else
printf("strings are not same");
return 0;
}

Output:
Enter the first string : C Programming Lab
Enter the second string : C Language
strings are not same

Result:

Thus, the C program to compare two string with string function was written
executed and the output was verified successfully.

Page 27 of 51
Solving Problems Using User Defined Functions

Ex No : 7A Swap Two Numbers using call by Value Method


Date :
Aim:
Write C program to Swap Two Numbers using call by Value Method.
Algorithm:
Step 1: Start
Step 2: Define a swap function such that it will accept two integer values
Step 3: Inside swap function interchange the values of both integers
Step 4: In main function Read two integers
Step 5: Call swap function using the integers read from user
Step 6: Print the value of both integers
Step 7: Stop

Program:
#include <stdio.h>
void swap(int , int);
int main()
{
int a,b;
printf("Enter Two Values:\n");
scanf("%d%d",&a,&b);
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);
}

Output:
Enter Two Values:
10
20
Before swapping the values in main a = 20, b = 40
After swapping values in function a = 40, b = 20
After swapping values in main a = 40, b = 20

Result:
Thus, the C program to Swap Two Numbers using call by Value Method
was written executed and the output was verified successfully.

Page 28 of 51
Ex No : 7B Swap Two Numbers using call by Reference Method
Date :

Aim:
Write C program to Swap Two Numbers using call by Reference Method.
Algorithm:
Step 1: Start
Step 2: Define a swap function such that it will accept two integer pointers
Step 3: Inside swap function interchange the values of both integers using pointer
Step 4: In main function Read two integers
Step 5: Call swap function using the address of integers read from user
Step 6: Print the value of both integers
Step 7: Stop

Program:

#include <stdio.h>
void swap(int *, int *);
int main()
{
int a,b;
printf("Enter Two Values:\n");
scanf("%d%d",&a,&b);
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);
}

Output:
Enter Two Values:
10
20
Before swapping the values in main a = 20, b = 10
After swapping values in function a = 10, b = 20
After swapping values in main a = 10, b = 20

Result:
Thus, the C program to Swap Two Numbers using call by Reference
Method was written executed and the output was verified successfully.

Page 29 of 51
Ex No : 7C Sort an Array of Elements using Functions
Date :

Aim:

Write C program to Sort an Array of Elements using Functions.

Algorithm:

Step 1: Start
Step 2: Define a function named mySort(), It will take a integer array and number
of values in a array as input
Step 3: Inside mySort() function Using two nested for loops check elements and
swap elements to sort array.
Step 4: Print the sorted array
Step 5: In main function declare a array
Step 6: Read total number of elements in the array as n
Step 7: Using for loop read n elements one by one
Step 8: call mySort() function to sort array
Step 9: Stop

Program:

#include<stdio.h>
void mySort(int[],int);
void main ()
{
int arr[10],n,i;
printf("Enter Number of elements in the array\n");
scanf("%d",&n);
printf("Enter Elements one by one\n");
for(i=0;i<n;i++)
scanf("%d",&arr[i]);
mySort(arr,n);
}
void mySort(int a[],int n)
{
int i, j,temp;
for(i = 0; i<n; i++)
{
for(j = i+1; j<n; j++)
{
if(a[j] < a[i])
{
temp = a[i];
a[i] = a[j];

Page 30 of 51
a[j] = temp;
}
}
}
printf("Printing Sorted Element List ...\n");
for(i = 0; i<n; i++)
{
printf("%d\n",a[i]);
}
}

Output:

Enter Number of elements in the array


5
Enter Elements one by one
8
2
7
5
1
Printing Sorted Element List ...
1
2
5
7
8

Result:

Thus, the C program to Sort an Array of Elements using Functions was


written executed and the output was verified successfully.

Page 31 of 51
Solving Problems using Recursive Functions

Ex No : 8A Factorial of a Number using Recursive Functions


Date :

Aim:

Write C program to find Factorial of a Number using Recursive Functions.

Algorithm:

Step 1: Start
Step 2: Read N value from user
Step 3: Call recursive function factorial(), by passing N and store the return value to fact
Step 4: In factorial() function if N==0 then return 1 else return N*factorial(N-1)
Step 5: Print fact value
Step 6: Stop

Program:

#include<stdio.h>
long factorial(int n)
{
if (n == 0)
return 1;
else
return(n * factorial(n-1));
}
void main()
{
int number;
long fact;
printf("Enter a number: ");
scanf("%d", &number);

fact = factorial(number);
printf("Factorial of %d is %ld\n", number, fact);
}

Output:
Enter a number: 4
Factorial of 4 is 24
Result:

Thus, the C program to find Factorial of a Number using Recursive


Functions was written executed and the output was verified successfully.

Page 32 of 51
Ex No : 8B Fibonacci Series using Recursive Functions
Date :

Aim:
Write C program to generate Fibonacci Series using Recursive Functions.

Algorithm:

Step 1: Start
Step 2: Read Number of terms from user as n
Step 3: Using a for loop call recursive function fibonacci(), n times and each
time print the return value
Step 4: In fibonacci() function if n==0 or n==1 then return n else return fibonacci(n-1)
+ fibonacci(n-2)
Step 5: Stop

Program:
#include<stdio.h>
int fibonacci(int);
int main()
{
int n, m= 0, i;
printf("Enter Total terms:\n");
scanf("%d", &n);
printf("Fibonacci series terms are:\n");
for(i = 1; i <= n; i++)
{
printf("%d\n", fibonacci(m));
m++;
}
return 0;
}
int fibonacci(int n)
{
if(n == 0 || n == 1)
return n;
else
return(fibonacci(n-1) + fibonacci(n-2));
}

Output:
Enter Total terms:
5
Fibonacci series terms are:
0 1 1 2 3

Result:
Thus, the C program to generate Fibonacci Series using Recursive Functions
was written executed and the output was verified successfully.

Page 33 of 51
Ex No : 8C Tower of Hanoi using Recursive Functions
Date :

Aim:

Write C program to solve Tower of Hanoi using Recursive Functions.

Algorithm:

Step 1: Start
Step 2: Read Number of disks from user as num
Step 3: Call recursive function towers(),by passing number of disks num and name
of the source, destination, auxiliary towers
Step 4: In towers() function if n==1 then print move disk 1 from source to destination
and go to step 8 else go to step 5
Step 5: Call recursive function towers() with arguments num-1, source, auxiliary, destination
Step 6: Print Move num from source to destination
Step 7: Call recursive function towers() with arguments num-1,
auxiliary, destination, source
Step 8: Stop

Program:

#include <stdio.h>
void towers(int, char, char, char);
int main()
{
int num;
printf("Enter the number of disks : ");
scanf("%d", &num);
printf("The sequence of moves involved in the Tower of Hanoi are :\n");
towers(num, 'A', 'C', 'B');
return 0;
}
void towers(int num, char frompeg, char topeg, char auxpeg)
{
if (num == 1)
{
printf("\n Move disk 1 from peg %c to peg %c", frompeg, topeg);
return;
}
towers(num - 1, frompeg, auxpeg, topeg);
printf("\n Move disk %d from peg %c to peg %c", num, frompeg, topeg);
towers(num - 1, auxpeg, topeg, frompeg);
}

Page 34 of 51
Output:

Enter the number of disks : 4


The sequence of moves involved in the Tower of Hanoi are :
Move disk 1 from peg A to peg B
Move disk 2 from peg A to peg C
Move disk 1 from peg B to peg C
Move disk 3 from peg A to peg B
Move disk 1 from peg C to peg A
Move disk 2 from peg C to peg B
Move disk 1 from peg A to peg B
Move disk 4 from peg A to peg C
Move disk 1 from peg B to peg C
Move disk 2 from peg B to peg A
Move disk 1 from peg C to peg A
Move disk 3 from peg B to peg C
Move disk 1 from peg A to peg B
Move disk 2 from peg A to peg C
Move disk 1 from peg B to peg C

Result:

Thus, the C program to solve Tower of Hanoi using Recursive Functions was
written executed and the output was verified successfully.

Page 35 of 51
Solving Problems using Dynamic Memory Allocation

Ex No : 9A Print Text using Dynamic Memory


Date :

Aim:

Write C program to Print Text using Dynamic Memory.


Algorithm:

Step 1: Start
Step 2: Declare a character pointer named text
Step 3: Read number of character in the string from user as n
Step 4: Allocate n bytes in memory using malloc() function and store the
starting address in the pointer variable text
Step 5: Read and store the string in text
Step 6: print entered string and length of the string
Step 7: Delete the allocated memory using free() function
Step 8: Stop

Program:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n;
char *text;
printf("Enter limit of the text: ");
scanf("%d",&n);
text=(char*)malloc(n*sizeof(char));
printf("Enter text: ");
scanf(" ");
gets(text);
printf("Inputted text is: %s\n",text);
printf("\nLength is:%ld",strlen(text));
free(text);
return 0;
}
Output:
Enter limit of the text: 25
Enter text: This is C Programming Lab
Inputted text is: This is C Programming Lab
Length is : 25
Result:

Thus, the C program to Print Text using Dynamic Memory was written
executed and the output was verified successfully.

Page 36 of 51
Ex No : 9B One Dimensional array Dynamic Memory
Date :

Aim:

Write C program to process One Dimensional array using Dynamic


Memory method.

Algorithm:

Step 1: Start
Step 2: Declare a integer pointer named arr
Step 3: Read total number of elements in the array from user as limit
Step 4: Allocate n*size(int) bytes in memory using malloc() function and store the
starting address in the pointer variable arr
Step 5: Check whether the memory is allocated or not, if not allocated print error
message and stop, if allocated then proceed to next step
Step 6: Using a for loop read elements and store in allocated memory using pointer
notation, also calculate sum of the elements
Step 7: Using for loop and pointer notation print the elements
Step 8: Print sum
Step 9: Stop

Program:

#include <stdio.h>
#include <stdlib.h>
int main()
{
int *arr;
int limit,i;
int sum=0;
printf("Enter total number of elements: ");
scanf("%d",&limit);
arr=(int*)malloc(limit*sizeof(int));
if(arr==NULL)
{
printf("Insufficient Memory, Exiting... \n");
return 0;
}
printf("Enter %d elements:\n",limit);
for(i=0; i<limit; i++)
{
printf("Enter element %3d: ",i+1);
scanf("%d",(arr+i));
sum=sum + *(arr+i);

Page 37 of 51
}
printf("Array elements are:");
for(i=0; i<limit; i++)
printf("%3d ",*(arr+i));
printf("\nSum of all elements: %d\n",sum);
return 0;
}

Output:

Enter total number of elements: 5


Enter 5 elements:
Enter element 1: 6
Enter element 2: 3
Enter element 3: 8
Enter element 4: 9
Enter element 5: 2
Array elements are: 6 3 8 9 2
Sum of all elements: 28

Result:

Thus, the C program to process One Dimensional array using Dynamic


Memory method was written executed and the output was verified successfully.

Page 38 of 51
Real-time Application Using Structure and Union

Ex No : 10A Creating Employee Payslip Using Structure


Date :

Aim:

Write C program to Create Employee Payslip Using Structure.

Algorithm:

Step 1: Start
Step 2: Define a Employee structure with required fields using struct keyword
Step 3: Declare a employee structure pointer
Step 4: Read total number of employees as n
Step 5: Allocate memory of n*sizeof(emplyeestructure) using malloc() function
Step 6: If memory not allocated stop else proceed to next step
Step 7: Using a for loop read n number of employees details and store them
in respective structure variable using -> operator
Step 8: Calculate net pay of each employee by adding basic pay and allowance
and reducing deduction
Step 9: Using a for loop iterate each employee structure and print all data present in it.
Step 10: Stop

Program:

#include <stdio.h>
#include <stdlib.h>
struct emp
{
int empno ;
char name[10] ;
int bpay, allow, ded, npay ;
};
int main()
{
struct emp *pemp;
int n,i;
printf("Enter total number of Employes: ");
scanf("%d",&n);
pemp=(struct emp*)malloc(n*sizeof(struct emp));
if(pemp==NULL)
{
printf("Insufficient Memory, Exiting... \n");
return 0;
}
for(i = 0 ; i < n ; i++)

Page 39 of 51
{
printf("\nEnter the employee number : ") ;
scanf("%d", &(pemp+i)->empno) ;
printf("\nEnter the name : ") ;
scanf("%s", (pemp+i)->name) ;
printf("\nEnter the basic pay, allowances & deductions : ") ;
scanf("%d %d %d", &(pemp+i)->bpay, &(pemp+i)->allow, &(pemp+i)->ded)
; (pemp+i)->npay = (pemp+i)->bpay + (pemp+i)->allow - (pemp+i)->ded ;
}
printf("\nEmp. No. Name \t Bpay \t Allow \t Ded \t Npay \n\n") ;
for(i = 0 ; i < n ; i++)
{
printf("%d \t %s \t %d \t %d \t %d \t %d \n", (pemp+i)->empno, (pemp+i)-
>name, (pemp+i)->bpay, (pemp+i)->allow, (pemp+i)->ded, (pemp+i)-
>npay) ;
}
}

Output:

Enter total number of Employes: 3


Enter the employee number : 101
Enter the name : Raja
Enter the basic pay, allowances & deductions : 40000
2000
1500
Enter the employee number : 102
Enter the name : Sai
Enter the basic pay, allowances & deductions : 35000
2000
1000
Enter the employee number : 103
Enter the name : Tony
Enter the basic pay, allowances & deductions : 25000
1000
500
Emp. No. Name Bpay Allow Ded Npay
101 Raja 40000 2000 1500 40500
102 Sai 35000 2000 1000 36000
103 Tony 25000 1000 500 25500

Result:

Thus, the C program to Create Employee Payslip Using Structure was


written executed and the output was verified successfully.

Page 40 of 51
Ex No : 10B Creating Student Details using Structure and Union
Date :

Aim:

Write C program to Create Student Details using Structure and Union.

Algorithm:

Step 1: Start
Step 2: Define a structure student with a nested union
Step 3: Ask whether need to read name or roll number
Step 4: Based on that either read name or roll number and store it in nested union
Step 5: Read mark and store it in structure variable
Step 6: Print the details
Stop 7: Stop

Program:

#include<stdio.h>
struct student {
union {
char name[10];
int roll;
};
int mark;
};
int main()
{
struct student stud;
char choice;
printf("\n You can enter your name or roll number ");
printf("\n Do you want to enter the name (y or n): ");
scanf("%c",&choice);
if(choice=='y'||choice=='Y')
{
printf("\n Enter name: ");
scanf("%s",stud.name);
printf("\n Name:%s",stud.name);
}
else
{
printf("\n Enter roll number");
scanf("%d",&stud.roll);
printf("\n Roll:%d",stud.roll);
}

Page 41 of 51
printf("\n Enter marks");
scanf("%d",&stud.mark);
printf("\n Marks:%d",stud.mark);
return 0;
}

Output:

Run 1:

You can enter your name or roll number


Do you want to enter the name (y or n): Y
Enter name: Tony
Name:Tony
Enter marks95
Marks:95

Run 2:

You can enter your name or roll number


Do you want to enter the name (y or n): N
Enter roll number101
Roll:101
Enter marks79
Marks:79

Result:

Thus, the C program to Create Student Details using Structure and Union
was written executed and the output was verified successfully.

Page 42 of 51
Real-Time Problem Solving Sequential and Random Access File

Ex No : 11A Calculating Sum and Average of n Numbers Present in a File


Date :

Aim:

Write C program to Calculate Sum and Average of n Numbers Present in a


File.

Algorithm:

Step 1: Start
Step 2: Declare a file pointer fp, sum=0 and i=0, average
Step 3: Open a file in read mode which consist of numbers
Step 4: Using a while loop, until end of file reach, read each number and add it
with sum variable and also increment i
Step 5: Calculate average=sum/i
Step 6: Print sum and average
Step 7: Stop

Program:

#include <stdio.h>
#include <stdlib.h>
#define DATAFILE "numbers.dat"
int main() {
FILE* fp;
int n[50], i = 0;
float sum = 0,average;
if ((fp = fopen(DATAFILE, "r")) == NULL) {
printf("Unable to open %s...\n", DATAFILE);
exit(0);
}
puts("Reading numbers from num.dat");
while (!feof(fp)) {
fscanf(fp, "%d ", &n[i]);
printf("%d : %d\n", i, n[i]);
sum += n[i];
i++;
}
fclose(fp);
if (i == 0)
printf("No data available in %s", DATAFILE);
average = sum / i;
printf("The Sum is %.3f for %d numbers\n", sum, i);
printf("The average is %.3f for %d numbers\n", average, i);

Page 43 of 51
return 0;
}

Output:

Result:

Thus, the C program to Calculate Sum and Average of n Numbers Present in


a File was written executed and the output was verified successfully.

Page 44 of 51
Ex No : 11B Transaction Processing using Random Access File
Date :

Aim:

Write C program to do Transaction Processing using Random Access File.

Algorithm:

Step 1: Start
Step 2: Define a structure account with number, amount and name fields
Step 3: Display Menu like Create Account, Display Account Details, and Transfer Amount
Step 4: Read the user option form menu
Step 5: If user wish to create account, then get number of account from user and read
each user details, and open a file in write mode then write the content to file.
Step 6: If user wish to view user details, then get the account number and open the file
in read mode and read the particular user details from file and display it
Step 7: If user wish to do account transfer, then get the details like from account
number, to account number and amount, then open the file in read write
mode, then read both account details, add the amount to, to account and
subtract the amount from, from account. And rewrite the new details to the file.
Step 8: Stop

Program:

#include<stdio.h>
#include<conio.h>
struct account
{
int number;
long amount;
char name[20];
};
void create()
{
FILE *fptr;
int i, n;
struct account acc;
if ((fptr = fopen("C:\\TURBOC3\\account.bin","wb")) == NULL)
{
printf("File Cannot Open!");
exit(1);
}
printf("Enter Total Number of Customers\n");
scanf("%d",&n);
for(i= 1; i <= n; i++)

Page 45 of 51
{
acc.number=i;
printf("Enter Name of User %d : ", i);
scanf("%s",acc.name);
printf("Enter Initial Amount of User %d : ",
i); scanf("%ld",&acc.amount);
fwrite(&acc, sizeof(struct account), 1, fptr);
}
fclose(fptr);
}
void view()
{
FILE *fptr;
int n;
struct account acc;
if ((fptr = fopen("C:\\TURBOC3\\account.bin","rb")) == NULL)
{
printf("File Cannot Open!");
exit(1);
}
while(1)
{
printf("\nEnter Customer Number to be view : -1 to stop \n");
scanf("%d",&n);
if(n==-1)
break;
fseek(fptr,(n-1)*sizeof(struct account),0);
fread(&acc, sizeof(struct account), 1, fptr);
printf("Customer Number: %d\t Customer Name: %s \tBalance:
%ld",
acc.number,acc.name,acc.amount);
}
fclose(fptr);
}
void transfer()
{
int fromno,tono;
long tamount;
struct account acc,fromacc,toacc;
FILE *fptr;
if ((fptr = fopen("C:\\TURBOC3\\account.bin","rb+")) == NULL)
{
printf("File Cannot Open!");
exit(1);
}
printf("\nEnter From Account No:\n");

Page 46 of 51
scanf("%d",&fromno);
printf("\nEnter To Account No:\n");
scanf("%d",&tono);
printf("\nEnter Amount to be transfer:");
scanf("%ld",&tamount);
fseek(fptr,(fromno-1)*sizeof(struct account),0);
fread(&fromacc, sizeof(struct account), 1, fptr);
fseek(fptr,(tono-1)*sizeof(struct account),0);
fread(&toacc, sizeof(struct account), 1, fptr);
fromacc.amount-=tamount;
toacc.amount+=tamount;
fseek(fptr,(fromno-1)*sizeof(struct account),0);
fwrite(&fromacc, sizeof(struct account), 1, fptr);
fseek(fptr,(tono-1)*sizeof(struct account),0);
fwrite(&toacc, sizeof(struct account), 1, fptr);
fclose(fptr);
}
void main()
{
int ch;
clrscr();
while(1)
{
printf("\n______MENU_______\n");
printf("1.Create Account\n2.View Account Detail \n3.Transfer
Amount\n4.Exit");
printf("\nEnter Your Choice: ");
scanf("%d",&ch);
switch(ch)
{
case 1:
create();
break;
case 2:
view();
break;
case 3:
transfer();
break;
case 4:
exit(0);
}
}
}

Page 47 of 51
Output:

Page 48 of 51
Result:

Thus, the C program to do Transaction Processing using Random Access File


was written executed and the output was verified successfully.

Page 49 of 51
Solving Problem Using Command Line Argument

Ex No : 12A Comparing Two Strings using Command Line Argument


Date :

Aim:

Write C program to Comparing Two Strings using Command


Line Argument.

Algorithm:

Step 1: Start
Step 2: Receive two strings through command line argument argv
Step 3: Use strcmp() function to compare two strings present in argv[1],argv[2]
Step 4: If strcmp() returns 0 then print both strings are same, otherwise print
strings are not same
Step 5: Stop

Program:

#include <stdio.h>
#include <string.h>
int main(int argc, char const *argv[]) {

if (strcmp(argv[1], argv[2]) == 0)
printf("Yes 2 strings are same\n");
else
printf("No, 2 strings are not same\n" );
return 0;
}

Output:

Run 1:
[root@vinu ~]# ./a.out Programming Programing
No, 2 strings are not same

Run 2:
[root@vinu ~]# ./a.out Programming Programming
Yes, 2 strings are same

Result:

Thus, the C program to Comparing Two Strings using Command Line


Argument was written executed and the output was verified successfully.

Page 50 of 51
Ex No : 12B Copying Content of One File to Another File using Command
Date : Line Argument
Aim:
Write C program to Copy Content of One File to Another File
using Command Line Argument.
Algorithm:
Step 1: Start
Step 2: Receive source and destination file names through command line argument argv
Step 3: Open argv[1] in read mode and argv[2] in write mode and store the
file pointers in sptr, dptr
Step 4: Check for the correct opening of source and destination file
Step 5: Using while loop read character by character from source file and write
the same to destination file
Step 6: Close the files
Step 7: Stop

Program:
#include<stdio.h>
#include<string.h>
int main(int argc,char*argv[])
{
FILE *sptr,*dptr; char ch;
if(argc!=3){
printf("Command Line Error. Need Two
argument"); return;
}
sptr=fopen(argv[1],"r");
dptr=fopen(argv[2],"w");
if(sptr==NULL || dptr==NULL) {
printf("Error in opening file!");
return;
}
while((ch=fgetc(sptr))!=EOF){
fputc(ch,dptr);
}
printf("File Copied Successfully.");
fclose(sptr);fclose(dptr);
}
Output:
[root@vinu ~]# vi sample.txt
[root@vinu ~]# vi filecopy.c
[root@vinu ~]# ./a.out sample.txt samplecopy.txt
File Copied Successfully.
Result:
Thus, the C program to Copy Content of One File to Another File using
Command Line Argument was written executed and the output was verified
successfully.

Page 51 of 51

You might also like