Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
45 views84 pages

C Lab Manual Complete

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 84

CONTENTS

S.No Date Name of the Experiment/Exercise Page Marks Awarded Remarks


No.
CONTENTS
S.No Date Name of the Experiment/Exercise Page Marks Awarded Remarks
No.
CONTENTS
S.No Date Name of the Experiment/Exercise Page Marks Awarded Remarks
No.
EX.NO:1
I/O STATEMENTS, OPERATORS, EXPRESSIONS

1A. C PROGRAM TO IMPLEMENT ARITHMETIC OPERATORS.

AIM:

To write C program to implement Arithmetic Operators.

ALGORITHM:

Step 1: Declare integer variables.


Step 2: Read all variables at runtime.
Step 3: Perform arithmetic operations.
i. a+b
ii. a-b
iii. a*b
iv. b/a
v. a%b
Step 4: Print all computed values.
PROGRAM:
#include<stdio.h>
main()
{
int a,b;
Printf(("enter a,b:\n");
scanf("%d%d",&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",b/a);
printf("a+b=%d\n",a%b);
}
OUTPUT:
Enter a,b:
40 60
a+b=100
a-b=-20
a*b=2400
b/a=1
ab=40

RESULT:
Thus the C Program to perform Arithmetic operators has been successfully executed and
verified.
1B. C PROGRAM TO IMPLEMENT FORMATTED I/O STATEMENTS.

AIM:

To write C program to demonstrate the uses of various formatted and unformatted input and
output functions

ALGORITHM:

STEP 1: Start the program.


STEP 2: Declare all required variables and initialize them.
STEP 3: Get input values from the user for arithmetic operation.
STEP 4: Use input function scanf() and output function printf()to display the output after the
calculation.
STEP 5:Stop the program.

PROGRAM:

#include<stdio.h>
#include<conio.h>
main()
{
Char alphabh="A";
int number1= 55;
float number2=22.34;
printf(“char= %c\n”,alphabh);
printf(“int= %d\n”,number1);
printf(“float= %f\n”,number2);
getch();
clrscr();
retrun 0;
}
OUTPUT:

char =A
int= 55
float=22.340000

RESULT:

Thus the C program to demonstrate the uses of various formatted and unformatted input and
output functions has been successfully executed.
1C. PROGRAM TO ACCEPT CHARACTERS AND DISPLAY USING UNFORMATTED
I/O STATEMENTS

AIM:
To implement a C program to accept characters and display using unformatted I/O function.

ALGORITHM:

STEP 1: Start the program.


STEP 2: Declare all required variables ch and character array str for storage
STEP 3: Read the string in ‘str’ using gets().
STEP 4: Print the string character.
STEP 5: Stop the program.

PROGRAM:

#include<stdio.h>
#include<conio.h>
main()
{
char x,y,z;
clrscr();
printf("Enter 1st character: ");
x = getchar();
printf("Enter 2nd character: ");
y = getche();
printf("\nEnter 3rd character: ");
z = getch();
printf("\nFirst character is ");
putchar(x);
printf("\nSecond character is ");
putch(y);
printf("\nThird character is ");
putchar(z);
}
OUTPUT:

Enter 1st character: k


Enter 2nd character: l
Enter 3rd character:
First character is k
Second character is l
Third character is ;

RESULT:
Thus the C program to accept characters and display using unformatted I/O function has
been successfully executed and verified.
1D. PROGRAM TO EVALUATE THE EXPRESSIONS

AIM:
To implement a C program to evaluate the expression using datatypes.

ALGORITHM:

STEP 1: Start the program.


STEP 2: Declare all required variables data types.
STEP 3: Read the values of integer, float values
STEP 4: calculate the values using given arithmetic function and print the values
STEP 5: Stop the program.

PROGRAM:
#include<stdio.h>
main()
{
int a=9,b=13,c=3;
float x,y,z;
x = a-b/3.0+c*2-1;
y = a-(float)b/(3+c)*(2-1);
z = a-((float)b/(3+c)*2)-1;
printf("x = %f\t\ty = %f\t\tz = %f",x,y,z);
getch();
}
OUTPUT:

x = 9.666667
y = 6.833333
z = 3.666667

RESULT:
Thus the C program to evaluate the expression using datatypes has been successfully
executed and verified.
EX.NO:2 DECISION-MAKING CONSTRUCTS: IF-ELSE, GOTO, SWITCH-
CASE, BREAK-CONTINUE

2A. PROGRAM TO FIND THE GREATER NUMBER BETWEEN TWO NUMBERS USING IF-
ELSE STATEMENT

AIM:
To implement the C Program to find the greater number between two numbers.

ALGORITHM:
Step 1: Start.
Step 2: Take two inputs (a and b) from the user.
Step 3: If a is greater than b then go to step 4 otherwise go to step 5
Step 4: Print a greater than b
Step 5: Print b greater than a
Step 6: Stop.

PROGRAM:
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
printf("Enter two numbers :");
scanf("%d %d",&a,&b);
if (a>b)
printf("%d is greater",a);
else
printf("%d is greater",b);
getch();
}
OUTPUT:
Enter two numbers: 4 5
5 is greater

RESULT:
Thus the C Program to find the greater number between two numbers has been
successfully executed and verified.
2B. PROGRAM USING SWITCH CASE STATEMENT

AIM:

To implement the c program to calculate the area of a rectangle or circle or triangle by taking the
user’s choice.

ALGORITHM:

Step 1: Start

Step 2: Initialize variables

Step 3: Take input for choice and then for area variables from the user

Step 4: Case 1: Circle: 3.14*3.14*r

Case 2: Rectangle: ar=a*b

Case 3: Triangle: at=0.5*a*b

Step 5: Display output according to case

Step 6: Stop

PROGRAM:

#include<stdio.h>
#include<conio.h>
void main()
{
int ac,ar,at,r,a,b,choice;
printf("Enter your choice\n”);
prinft(“A for area of circle\n”);
printf(“B for area of rectangle\n”);
printf(“C for area of triangle\n");
scanf("%c",&choice);

switch(choice)
{
case A:
printf("Enter radius: ");
scanf("%d",&r);
ac=3.14*3.14*r;
printf("Area of circle is: %d",ac);
break;
case B:
printf("Enter length and breadth:");
scanf("%d %d",&a,&b);
ar=a*b;
printf("Area of rectangle is: %d",ar);
break;
case C:
printf("Enter base and height: ");
scanf("%d %d",&a,&b);
at=0.5*a*b;
printf("Area of triangle is: %d",at);
break;
}
getch();
}
OUTPUT:

Emter your choice


1 for area of circle
2 for area of rectangle
3 for area of triangle
1
Enter radius: 5
Area of circle is: 49

RESULT:

Thus the C program to calculate the area of a rectangle or circle or triangle by taking the
user’s choice has been successfully executed and verified.
2C. PROGRAM TO FIND SQUARES OF THE POSITIVE NUMBERS USING CONTINUE
STATEMENT

AIM:
To implement the C Program to find squares of the positive numbers.

ALGORITHM:
Step 1: Start.

Step 2: Take input from the user.

Step 3: Check the condition and take only positive numbers.

Step 4: Print the square number

Step 5: Stop

PROGRAM:

#include <stdio.h>
main()
{
int i, n, a, sq;
clrscr();
printf("\nHow many numbers you want to enter: ");
scanf("%d", &n);
for (i=1;i<=n; i++)
{
printf("\nEnter number: ");
scanf("%d", &a);
if(a<0)
continue;
sq = a * a;
printf("\nSquare = %d\n", sq);
}
getch();
}
OUTPUT:

How many numbers you want to enter: 3


Enter number: 2
Square = 4
Enter number: -1
Enter number: 6

RESULT:

Thus the program finds square of positive numbers only has been successfully executed and
verified.
2E. PROGRAM TO PRINT MULTIPLICATION TABLE USING GOTO STATEMENT

AIM:

To implement the C Program to print Multiplication Table using GOTO statements.

ALGORITHM:

Step 1: Start.

Step 2: Take input from the user.

Step 3: Declare the variable and Check the condition.

Step 4: print the multiplication table give value

Step 5: Stop

PROGRAM:

#include<stdio.h>
#include<conio.h>
main()
{
int a,i=1;
clrscr();
printf("Enter the value of a: ");
scanf("%d",&a);
printf("\nMultiplication Table for %d\n",a);
printf(" \n");
start:
printf("%d x %d = %d\n",a,i,a*i);
i=i+1;
if(i<=10)
goto start;
getch();
}
OUTPUT:

Enter the value of a: 5


Multiplication Table for 5

5x1=5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50

RESULT:

Thus the C Program to print Multiplication Table using GOTO statements has been
successfully executed and verified.
2F. PROGRAM TO IMPLEMENT BREAK STATEMENT

AIM:

To implement the C program using break statement.

ALGORITHM:

Step 1: Start.
Step 2: local variable definition.
Step 3: while loop execution
Step 4: terminate the loop using break statement
Step 5: Stop

PROGRAM:

#include <stdio.h>
int main ()
{
int a = 10;
while( a < 20 )
{
printf("value of a: %d\n", a);
a++;

if( a > 15)


{
break;
}

return 0;

}
OUTPUT:

Value of a: 10
Value of a: 11
Value of a: 12
Value of a: 13
Value of a: 14
Value of a: 15

RESULT:

Thus the C program using break statement has been successfully executed and verified.
EX.NO:3
LOOPS: FOR,WHILE, DO-WHILE

3A. PROGRAM TO FIND THE FACTORIAL OF A NUMBER USING FOR LOOP

AIM:

To implement the c program to find the factorial of a number.

ALGORITHM:

Step 1: Start.

Step 2: Initialize variables.

Step 3: Check FOR condition.

Step 4: If the condition is true, then go to step 5 otherwise go to step 7.

Step 5: f = f * i.

Step 6: Go to step 3.

Step 7: Print value of factorial.

PROGRAM:

#include <stdio.h>
#include <conio.h>
void main()
{
int i, a ,f = 1;
printf("Enter a number:\n");
scanf("%d", &a);
for (i = 1; i <= a; i++)
f=f*i;
printf("Factorial of %d is %d\n", a, f);
getch();
}
OUTPUT:

Enter factorial number 5


Factorial of 5 is 120

RESULT:

Thus the C program to find the factorial of a number has been successfully executed and
verified.
3B.PROGRAM TO FIND THE SUM OF 1 TO 10 USING DO-WHILE LOOP

AIM:

To implement the C program to find sum of 1 to 10 using the do-while loop statements.

ALGORITHM:

Step 1: Start.
Step 2: initializing the variable
Step 3: do-while loop execution
Step 4: incrementing operation of given variable
Step 5: Print the sum of the values
Step 6: Stop

PROGRAM:

#include<stdio.h>
#include<conio.h>
void main()
{
int i = 1,a = 0;
do
{
a = a + i;
i++;
}
while(i <= 10);
printf("Sum of 1 to 10 is %d",a);
getch();
}
OUTPUT:

Sum of 1 to 10 is 55

RESULT:

Thus the C program to find sum of 1 to 10 using the do-while loop statements has been
successfully executed and verified.
3C. PROGRAM TO PRINT 1 TO 10 NUMBERS USING WHILE STATEMENT

AIM:

To implement the C program to print 1 to 10 numbers using while statement.

ALGORITHM:

Step 1: Start.
Step 2: initializing the variable
Step 3: while loop execution
Step 4: incrementing operation of given variable
Step 5: Print the sum of the values
Step 6: Stop

PROGRAM:

#include<stdio.h>
#include<conio.h>

void main()
{
int n = 1;

while(n <= 10)


{
printf("%d\n\n", n);
n++;
}

getch();
}
OUTPUT:

1
2
3
4
5
6
7
8
9
10

RESULT:

Thus the C program to print 1 to 10 numbers using while statement has been successfully
executed and verified.
EX.NO:4 ARRAYS: 1D AND 2D, MULTI-DIMENSIONAL ARRAYS,
TRAVERSAL

4A . PROGRAM USING ONE-DIMENSIONAL ARRAY

AIM :
To implement a C program to populate an array with height of persons and finding how
many persons are above the average height.

ALGORITHM :

1. Define a symbolic constant MAX_SIZE with the value 100.


2. Declare the floating point variables avg, sum=0.0 and array ‘arr’ with MAX_SIZE.
3. Declare the integer variables i , n and count and initialize the count to zero.
4. Read the number of persons in ‘n’.
5. Read ‘n’ numbers of heights in the array ‘arr’.
6. Compute the sum of heights and avg by sum/n.
7. Compare n number of heights in the array with the avg height. If it is greater than
the avg height then increment the count value by 1.
8. Print the number of persons who are above the average height using count.

PROGRAM :

#define MAX_SIZE 100


#include<stdio.h>
#include<conio.h>
void main()
{
float arr[MAX_SIZE]; int i, n, count=0;
float sum=0.0,avg;
clrscr();
printf("Enter the number of persons:\n ");
scanf("%d", &n);
printf("\nEnter %d heights in the array: ", n);
for(i=0; i <n;i++)
{
scanf("%f",&arr[i]);
sum=sum+arr[i];
}
avg=sum/n;
for(i=0;i<n;i++)
{
if(arr[i]>avg)
count++;
}
printf("the average height is%f",avg);
printf("\nNumber of persons who are above the average height : %d", count++);
getch();
OUTPUT :

Enter the number of persons:


3
Enter 3 heights in the array: 123.2
127.3
142.6
the average height is131.033340
Number of persons who are above the average height : 1

RESULT:

Thus the implementation of a C program to populate an array with height of persons and
finding how many persons are above the average height has been successfully executed and
verified.
4B. BODY MASS INDEX OF THE INDIVIDUALS

AIM :

To implement a C program to multiply two matrices.

ALGORITHM :

STEP 1.Start
STEP 2. Declare the necessary variables and arrays.
STEP 3. Get the values for the two arrays
STEP 4. Multiply the matrices
STEP5. Print the result
STEP 6:Stop.

PROGRAM :

#include<stdio.h>
#include<stdlib.h>
int main(){
int a[10][10],b[10][10],mul[10][10],r,c,i,j,k;
system("cls");
printf("enter the number of row=");
scanf("%d",&r);
printf("enter the number of column=");
scanf("%d",&c);
printf("enter the first matrix element=\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("enter the second matrix element=\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",&b[i][j]);
}
}

printf("multiply of the matrix=\n");


for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
mul[i][j]=0;
for(k=0;k<c;k++)
{
mul[i][j]+=a[i][k]*b[k][j];
}
}
}
//for printing result
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf("%d\t",mul[i][j]);
}
printf("\n");
}
return 0;
}
OUTPUT :

enter the number of row=3


enter the number of column=3
enter the first matrix element=
111
222
333
enter the second matrix element=
111
222
333
multiply of the matrix=
666
12 12 12
18 18 18

RESULT:
Thus the implementation of a C program to multiply two matrices is executed successfully.
4C. WRITE A C PROGRAM TO PERFORM TRAVERSE OPERATION ON AN ARRAY.

AIM:
To implement the C program to traverse operation on an array

ALGORITHM:
Step 01: Start
Step 02: [Initialize counter variable. ] Set i = LB.
Step 03: Repeat for i = LB to UB.
Step 04: Apply process to arr[i].
Step 05: [End of loop. ]
Step 06: Stop

PROGRAM:
#include<stdio.h>
void main()
{
int i, size;
int arr[]={1, -9, 17, 4, -3};

size=sizeof(arr)/sizeof(arr[0]); printf("The array elements are: "); for(i=0;i<size;i++)


{
printf("\narr[%d]= %d", i, arr[i]);
}
}
OUTPUT:
The array elements are:
arr[0]= 1
arr[1]= -9
arr[2]= 17
arr[3]= 4
arr[4]= -3

RESULT:
Thus the C program to perform traverse operation on an array has been successfully
executed and verified.
EX.NO:5
STRINGS: OPERATIONS

5A. C PROGRAM TO REVERSE THE STRING

AIM :
To implement a C program to reverse the given string without changing the position of
special characters.

ALGORITHM :

STEP 1: Define a function reverse with an argument character array.


STEP 2: Create a temporary character variable say temp.
STEP 3: Find the l and r values as 0 and string length of str respectively.
STEP 4: Reverse only the alphabets from left end to right end using temp in the while loop by
taking the copy of the string ‘str’. Check the symbol is an alphabet or not using isAlphabet()
function.
STEP 5: Main() reads the actual input string and calls the reverse() function with ‘str’ as
argument.

PROGRAM :

#include<stdio.h>
#include<string.h>
#include<conio.h>
int isAlphabet(char);
void reverse(char str[]);
void main()
{
char str[20] ;
clrscr();
printf("Enter the Input string:\n");
scanf("%s", str);
reverse(str);
printf("Reversed string: %s",str);
}
int isAlphabet(char x)
{
return ( (x >= 'A' && x <= 'Z') || (x >= 'a' && x <= 'z') );
}
void reverse(char str[])
{
int r = strlen(str) - 1,
l = 0;
char temp;
while (l < r)
{
if (!isAlphabet(str[l]))
l++;
else if(!isAlphabet(str[r]))
r--;
else
{
temp=str[l];
s tr[l]=str[r];
str[r]=temp;l++;
r--;

}
}
}
OUTPUT:

Enter the Input string:

wel%come@

Reversed string: emo%clew@

RESULT:

Thus the implementation of a C program to reverse the given string has been successfully
executed and verified.
5B. C PROGRAM TO FIND THE TOTAL NUMBER OF WORDS IN A STRING.

AIM :
To implement a C program to find the total number of words in a string.

ALGORITHM :

1. Declare the character variable ‘ch’ and an array s with a size 200.
2. Declare the integer variables i, n and count. Initialize count to 0.
3. Read a string as input and store it in the array s[].
4. Using for loop search for a space ‘ ‘ in the string and consecutively increment a variable
count.
5. Repeat the step-2 until the end of the string.
6. Increment the variable count by 1 and then print the variable count as output.

PROGRAM :

#include <stdio.h>
#include <string.h>
#include<conio.h>
void main()
{
char s[200], ch;
int count = 0, i, n;
clrscr();
printf("\nEnter the string\n");
for(i=0;ch!='\n';i++)
{
ch=getchar();
s[i]=ch;
}
s[i]=’\0’;
n=strlen(s);
for (i = 0;s[i] >= n ;i++)
{
if (s[i] == ' ')
count++;
}
printf("\nNumber of words in given string is: %d\n", count + 1);
getch();
}
OUTPUT :

Enter the string


Welcome to all

Number of words in given string is: 3

RESULT:

Thus the implementation of a C programs to find the total number of words in a string has
been successfully executed and verified.
5C. C PROGRAM TO CAPITALIZE THE FIRST WORD OF EACH SENTENCE.

AIM :
To implement a C program to capitalize the first word of each sentence.

ALGORITHM :

1. Declare an array variable ‘sentence ‘.


2. Read the sentence in the array ‘sentence ‘.\
3. Convert the first letter of the sentence by toupper(sentence[0]).
4. Using for loop, capitalize all the first word of other sentences by toupper().
5. Print the output string .

PROGRAM :

#include <stdio.h>
#include <string.h>
#include<conio.h>
#define SIZE 100
void main()
{
char sentence[SIZE];
int i;
clrscr();

printf("\nPlease enter a sentence..\n");


gets(sentence);
sentence[0] = toupper(sentence[0]);
for (i = 1; i < SIZE; i++)
{
if ( sentence[i - 1] == '.' )
sentence[i] = toupper( sentence[i] );
}

printf(“\nOutput String : %s”, sentence );


getch();
}
OUTPUT :

Please enter a sentence..

string is an array of characters. c supports a large number of string handling functions.

Output String:

String is an array of characters. C supports a large number of string handling functions.

RESULT:
Thus the C program to capitalize the first word of each sentence has been
successfully executed and verified.
5D. C PROGRAM TO REPLACE A GIVEN WORD WITH ANOTHER WORD IN THE
STRING.

AIM :

To implement a C program to replace a given word with another word in the string.

ALGORITHM :

1. Define a function replaceWord() with three arguments the input string, oldWord and
newWord and performs as follows:
a) Compute the length of both the words.
b) Count the number of times old word occur in the input string by using for loop and
strstr() function. Count is stored in ‘cnt’.
c) Allocate a memory for the output string as result[ ].
d) Compare the substring with the result and copy the newWord in the place of oldWord
in the result[ ].
e) Print the result[ ].
2. Read the sentence in str[ ].
3. Read the word to be replaced in c[ ].
4. Read the word with which it is to be replaced in d[ ].
5. Call the replaceWord() function from the main() by passing the arguments str[ ], c[ ] and
d[ ].

PROGRAM :

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char *replaceWord(const char *s, const char *oldW,const char *newW)


{
char *result;
int i, cnt = 0;
int newWlen = strlen(newW);
int oldWlen = strlen(oldW);
// Counting the number of times old word occur in the string
for (i = 0; s[i] != '\0'; i++)
{
if (strstr(&s[i], oldW) == &s[i])
{
cnt++;
// Jumping to index after the old word.
i += oldWlen - 1;
}
}
// Making new string of enough length
result = (char *)malloc(i + cnt * (newWlen - oldWlen) + 1);
i = 0;

while (*s)
{
// compare the substring with the result
if (strstr(s, oldW) == s)
{
strcpy(&result[i], newW);
i += newWlen;
s += oldWlen;
}
else
result[i++] = *s++;
}
result[i] = '\0';
return result;
}

void main()
{
char str[100];
char c[25];
char d[50];
char *result = NULL;
printf("Enter the sentence :\n");
gets(str);
printf("\nEnter the word to be replaced:\n");
gets(c);
printf("\nEnter the word with which it is to be replaced:\n");
gets(d);
printf("\nGiven string: %s\n", str);
result = replaceWord(str, c, d);
printf("\nNew String: %s\n", result);
free(result);
}
OUTPUT :

Enter the sentence:


Cross compiler is a type of compiler.

Enter the word to be replaced:


compiler

Enter the word with which it is to be replaced.


platform

Given string: cross compiler is a type of compiler.


New String: cross platform is a type of platform.

RESULT:

Thus the implementation of C programs to replace a given word with another word
has been successfully executed and verified.
FUNCTIONS: CALL, RETURN, PASSING PARAMETERS BY
EX.NO:6
(VALUE, REFERENCE), PASSING ARRAYS TO FUNCTION.

6A.C PROGRAM TO SWAP THE VALUES USING FUNCTION CALL

AIM:
To implement the C program to swap the values using function call.

ALORITHM:
STEP1.Start
STEP2. Declare the function and local variable.
STEP3. Read the function call to swap function.
STEP4. Compute the value and print the value.
STEP 5:Stop.
PROGRAM:

#include <stdio.h>
void swap(int x, int y);
int main ()
{
int a = 100;
int b = 200;
printf("Before swap, value of a : %d\n", a );
printf("Before swap, value of b : %d\n", b );
swap(a, b);
printf("After swap, value of a : %d\n", a );
printf("After swap, value of b : %d\n", b );
return 0;
}
void swap(int x, int y)
{
int temp;
temp = x; /* save the value of x */
x = y; /* put y into x */
y = temp; /* put temp into y */
return;
}
OUTPUT:

Before swap, value of a : 100


Before swap, value of b : 200
After swap, value of a : 100
After swap, value of b : 200

RESULT:
Thus the C program to swap the values using function call has been successfully executed
and verified.
6B. C PROGRAM TO SORT LIST OF NUMBERS USING PASS BY REFERENCE

AIM :
To implement a C program to sort list of numbers using pass by reference.

ALGORITHM :

1. Define a function sort(int m, int x[]) , where m is the number of elements and x is the m
number of array elements to be sorted.
2. The function sort() will compare the nearby elements and sort the elements by swapping
them using a temporary variable ‘t’.
3. Read the number of elements in ‘n’ and also read ‘n’ number of array elements in arr[ ]
from main() function.
4. Print the actual array elements before sorting.
5. Call the sort(n, arr) function by passing the number of elements(n) and array elements
(arr[ ]). Here the reference of the array arr[ ] is automatically passed to the function sort().
6. Print the sorted array elements after sorting.

PROGRAM :

#include<stdio.h>
#include<conio.h>
void sort(int m, int x[]);
void main()
{
int arr[100],i,n,j,k;
clrscr();

printf("\nEnter the number of elements in the array: ");


scanf("%d",&n);

printf("\nEnter the elements of the array");


for(i=0 ; i < n ; i++)
{
printf("\n arr[%d] = ",i);
scanf("%d",&arr[i]);
}
printf("Elements before sorting\n\n");
for(i = 0; i < n; i++)
printf("%d\t", arr[i]);
printf("\n\n");

sort(n,arr);

printf("Elements after sorting\n\n");


for(i = 0; i < n; i++)
printf("%d\t", arr[i]);
printf("\n");
getch();
}

void sort(int m, int x[])


{
int i, j, t;
for(i = 1; i <= m-1; i++)
for(j = 1; j <= m-i; j++)
if(x[j-1] >= x[j])
{
t = x[j-1];
x[j-1] = x[j];
x[j] = t;
}
}
OUTPUT:

Enter the number of elements in the array: 5


Enter the elements of the array
arr[0] = 54

arr[1] = 2

arr[2] = 45

arr[3] = 13

arr[4] = 32

Elements before sorting 54


2 45 13 32

Elements after sorting


2 13 32 45 54

RESULT:

Thus the implementation of a C program to sort list of numbers using pass by reference has
been successfully executed and verified.
EX.NO:7
RECURSION

7A. PROGRAM FOR TOWER OF HANOI PROBLEM USING RECURSION PROBLEM.

AIM :
To implement a C program to solve the Tower of Hanoi problem using Recursion.

ALGORITHM :

1. Define function TOH() with 4 arguments as number of disks(n) and 3 towers .


2. Declare variable n.
3. Read the number of disc in ‘n’.
4. Call the function TOH() by passing n and three towers.
a) if n=1, print Move disc 1 from fr to tr
b) Call the function with n-1, fr, ar, tr
c) Move disc n from fr to tr
d) Call function with n-1, ar, tr, fr

PROGRAM :

#include <stdio.h>
#include<conio.h>
void TOH(int, char, char, char);
void main()
{
int n;// defined to store the number disc
clrscr();
printf("Enter the number of disks : ");
scanf("%d", &n);
printf("The sequence of moves involved in the Tower of Hanoi are :\n");
TOH(n, 'A', 'C', 'B'); // A, B, C are tower
getch();
}
void TOH(int n, char fr, char tr, char ar)
{
if (n == 1)
{
printf("\n Move disk 1 from rod %c to rod %c", fr, tr);
return;
}
towerfun(n - 1, fr, ar, tr);
printf("\n Move disk %d from rod %c to rod %c", n, fr, tr);
towerfun(n - 1, ar, tr, fr);
}
OUTPUT :

Enter the number of disks :

The sequence of moves involved in the Tower of Hanoi are :

Move disk 1 from rod A to rod C


Move disk 2 from rod A to rod B
Move disk 1 from rod C to rod B
Move disk 3 from rod A to rod C
Move disk 1 from rod B to rod A
Move disk 2 from rod B to rod C
Move disk 1 from rod A to rod C

RESULT:

Thus the implementation of a C program to solve the Tower of Hanoi problem using
recursion has beensuccessfully executed and verified.
POINTERS: POINTERS TO FUNCTIONS, ARRAYS, STRINGS,
EX.NO:8
POINTERS TO POINTERS, ARRAY OF POINTERS

8A. C PROGRAM USING POINTER TO FUNCTIONS

AIM:
To implement a C program using pointer to functions.

ALGORITHM:

STEP1:Start
STEP2: Declare the function and local variable.
STEP3: Call the swap () function by passing the address of the two
Variables.
STEP4: Save the content of the first variable pointed by ‘a’ in the
Temporary variable.
STEP 5: Update the second variable (pointed by b) by the value
STEP 6: Stop.

PROGRAM:
#include<stdio.h>
#include<conio.h>
void swap (int *a, int *b);
int main()
{
int m = 25;
int n = 100;
printf("m is %d, n is %d\n", m, n);
swap(&m, &n);
printf("m is %d, n is %d\n", m, n);
return 0;
}
void swap (int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
OUTPUT:

m is 25, n is 100
m is 100, n is 25

RESULT:

Thus the implementation of a C program to swap the value using Pointer to


function has been successfully executed and verified.
8B . C PROGRAM TO AN ARRAY OF POINTERS TO STRING.

AIM:
To implement a C program to an array of pointers to string.

ALGORITHM:

STEP1.Start
STEP2. Declaring the string pointer array as well as a char
array
STEP3. Taking inputs in char array as well.
STEP4. As copying them to the string pointer array.
STEP 5: used malloc to allocate dynamic memory. l+1 to
Store "\0".
STEP 6: Stop.

PROGRAM:

#include <String.h>
#include<stdio.h>
#include<stdlib.h>
int main()
{
char *names[5], a[5];
int l, i;
char *x;
printf(“Enter 5 strings:\n”);
for(i=0;i<5;i++)
{
for (i = 0; i < 5; i++)
scanf("%s", a);
l = strlen(a);
x = (char *)malloc(l + 1);
strcpy(x, a);
names[i] = x;
}
printf("The strings are:\n");
for (i = 0; i < 5; i++)
printf("%s\n", names[i]);
return 0:
}
OUTPUT:

Enter 5 strings:
Tree
Bowl
Hat
Mice
Toon

The strings are:


Tree
Bowl
Hat
Mice
Toon

RESULT:

Thus the implementation of C program to an array of pointers to string has been successfully
executed and verified.
EX.NO:9 STRUCTURES: NESTED STRUCTURES, POINTERS TO
STRUCTURES, ARRAYS OF STRUCTURES AND UNIONS.

9A.PROGRAM TO GENERATE SALARY SLIP OF EMPLOYEES USING STRUCTURES


AND POINTERS

AIM :

To implement a C program to generate salary slip of employees using structures and


pointers.

ALGORITHM :

1. Define a structure ‘employee’ with empId, name[ ], basic, hra, da, ma, pf, insurance, gross
and net members.
2. Read the number of employees in ‘num’.
3. Allocate the memory for the ‘num’ number of structure variable
4. Read the structure members values for empId, name[ ], basic, hra, da, ma, pf, insurance.
5. Compute the gross and net salary and deduction amount.
6. Call the printSalary() function to print the salary slip of employees.

PROGRAM :

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct employee
{
int empId; char
name[32];
int basic, hra, da, ma;
int pf, insurance; float
gross, net;
};
/* prints payslip for the requested employee */
void printSalary(struct employee e1)
{
printf("Salary Slip of %s:\n", e1.name);
printf("Employee ID: %d\n", e1.empId);
printf("Basic Salary: %d\n", e1.basic);
printf("House Rent Allowance: %d\n", e1.hra);
printf("Dearness Allowance: %d\n", e1.da);
printf("Medical Allowance: %d\n", e1.ma);
printf("Gross Salary: %.2f Rupees\n", e1.gross);
printf("\nDeductions:\n");
printf("Provident fund: %d\n", e1.pf);
printf("Insurance: %d\n", e1.insurance);
printf("\nNet Salary: %.2f Rupees\n\n", e1.net);
}
void main()
{
int i, ch, num, flag, empID;
struct employee *e1;
printf("Enter the number of employees:");
scanf("%d", &num);
e1 = (struct employee *)malloc(sizeof(struct employee) * num);
printf("Enter your input for every employee:\n");
for (i = 0; i < num; i++)
{
printf("Employee ID:");
scanf("%d", &(e1[i].empId));
getchar();
printf("Employee Name:");
fgets(e1[i].name, 32, stdin);
e1[i].name[strlen(e1[i].name) - 1] = '\0';
printf("Basic Salary, HRA:");
scanf("%d%d", &(e1[i].basic), &(e1[i].hra));
printf("DA, Medical Allowance:");
scanf("%d%d", &(e1[i].da), &(e1[i].ma));
printf("PF and Insurance:");
scanf("%d%d", &(e1[i].pf), &(e1[i].insurance));
printf("\n");
}

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


{
e1[i].gross = e1[i].basic + (e1[i].hra * e1[i].basic) / 100 +
(e1[i].da * e1[i].basic) / 100 + (e1[i].ma * e1[i].basic) / 100;
e1[i].net = e1[i].gross - (e1[i].pf + e1[i].insurance);
}
while (1)
{
printf("Enter employee ID to get payslip:");
scanf("%d", &empID);
flag = 0;
for (i = 0; i < num; i++)
{
if (empID == e1[i].empId)
{
printSalary(e1[i]);
flag = 1;
}
}
if (!flag)
{
printf("No Record Found!!\n");
}
printf("Do You Want To Continue(1/0):");
scanf("%d", &ch);
if (!ch)
{
break;
}
}
}
OUTPUT :

Enter the number of employees:


2
Enter your input for every employee:
Employee ID:
1001
Employee Name: Vignesh
Basic Salary, HRA: 30000 3000
DA, Medical Allowance: 500 700
PF and Insurance: 2500 2000

Employee ID:
1002
Employee Name: Hari
Basic Salary, HRA: 32000 3200
DA, Medical Allowance: 550 760
PF and Insurance: 3000 2400

Enter employee ID to get payslip: 1002


Salary Slip of Hari:
Employee ID: 1002
Basic Salary: 32000
House Rent Allowance: 3200
Dearness Allowance: 550
Medical Allowance: 760
Gross Salary: 31443.00 Rupees

Deductions:
Provident fund: 3000
Insurance: 2400

Net Salary: 26043.00 Rupees

Do You Want To Continue(1/0): 0

RESULT:

Thus the implementation of a C program to generate salary slip of employees using


structures and pointers has been successfully executed and verified.
9B. NESTED STRUCTURES: PRINTING EMPLOYEE PERSONAL DETAILS

AIM:

To write a C program to calculate the gross salary using structure within structure.

ALGORITHM:

1. Start
2. Struct employee e_code[4]=char e_name[20]=char e_bp=float
struct e_da=float e_hra=floatallo e_pf=float end struct.
3. Read the employee code, name, basic pay, da, hra, pf.
4. Print the employee code, name, basic pay, da, hra, pf.
5. Calculate gross salary=emp1.e_bp+emp1.allo.e_da+emp1.allo.e_hra+emp1.e_pf. Print the
gross salary.
6. Stop.

PROGRAM:

#include<stdio.h>
#include<conio.h>
void main()
{
struct employee
{
char e_code[4];
char e_name[20];
float e_bp;
struct
{
float e_da;
float e_hra;
}
float e_pf;
};
struct employee emp1;

float gross;
printf(“\nEnter the code:”);
gets(emp1.e_code);
printf(“\nEnter thename:”);
gets(emp1.e_name);
printf(“\nEnter the basic pay:”);
scanf(“%f”,&emp1.e_bp);
printf(“\nEnter the dearness allowance:”);
scanf(“%f”,&emp1.allo.e_da);
printf(“\nEnter the housrentallowance:”);
scanf(%f”,&emp1.allo.e_hra);
printf(“ \ nEnter the provident fund:”);
scanf (“%f”,&emp1.e_pf);
printf(“ \ nCode :”);
puts(emp1.e_code);
printf(“ \ nName :”);
puts(emp1.e_name);
printf(“ \ nBasicpay :%8.2f”,emp1.e_bp);
printf(“ \ nDearness allowance :%8.2f”,emp1.allo.e_da);
printf(“ \ nHouserent allowance:%8.2f”,emp1.allo.e_hra);
printf(“ \ nP rovidentfund :%8.2f”,emp1.e_pf);
gross=emp1.e_bp+emp1.allo.e_da+emp1.allo.e_hra+emp1.e_pf;
printf(“ \ nNetpay :%8.2f”,gross);
}
OUTPUT:

Enter the code :1990 Enter the name :


Ramesh Enter the basic pay:15000
Enter the dearness allowance:1500 Enter the house rent allowance:1000Enter the provident
fund:800
Code 1990
Name :Ramesh
Basic pay :15000.00
Dearness allowance :1500.00
House rent allowance :1000.00
Provident fund :800.00
Net Pay :18300.00

RESULT:

Thus the C program to calculate the gross salary using structure within structure was executed
successfully executed and output is verified.
9C. POINTERS TO STRUCTURES: PRINTING STUDENT DETAILS

AIM:

To write a C program to print student details using pointers and structures.

ALGORITHM:

1. Start
2. Declare student structure
3. Read student roll number, student name, branch, marks.
4. Print student roll number, student name, branch, marks.
5. Stop.

PROGRAM:

#include<stdio.h>
void main()
{
struct
{
int rollno;
char name[30];
char branch[4];
int marks;
}
*stud;
printf(“ \ n Enter Rollno :”);
scanf (“%d”, &stud - >rollno);
printf(“ \ n Enter Name :”);
scanf(“%s”,stud - >name);
printf(“ \ n Enter Branch:”);
scanf(“%s”,stud - >branch);
printf(“ \ n Enter Marks:”);
scanf(“%d”,&stud - >marks);
printf(“ \ n Roll Number:%d”,stud - >rollno);
printf(“ \ n Name:%s”,stud - >name);
printf(“ \ n Branch:%s”,stud - >branch);
printf(“ \ n Marks:%d”,stud - >marks);
getch();
OUTPUT:

Enter Rollno :1000


Enter Name :Ebisha
Enter Branch:CSE
Enter Marks:90

Roll Number:1000
Name:Ebisha
Branch:CSE
Marks:90

RESULT:

Thus the C program to print student details using pointers and structures was executed successfully
executed and output is verified.
9D. ARRAY OF STRUCTURES:CALCULATING STUDENT MARK DETAILS

AIM:

To write a C program to calculate the total marks using array of structures.

ALGORITHM:

1. Start
2. Declare the structure with members.
3. Initialize the marks of the students
4. Calculate the subject total by adding student
[i].sub1+student[i].sub2+student[i].sub3.
5. Print the total marks of the students
6. Stop.

PROGRAM:

#include<stdio.h>
#include<conio.h>
struct marks
{
int sub1;
int sub2;
int sub3;
int total;
};
void main()
{
int i;
struct marks student[3] = { {45, 67, 81, 0},{75, 53, 69, 0}, {57, 36, 71, 0}};
struct marks total;
for(i=0; i<=2; i++)
{
student[i]. total = student[i].sub1+ student[i].sub2+ student[i].sub3;
}
printf( “TOTAL MARKS \ n \ n”);
for(i=0; i<=2; i++)
printf(“student[%d]: %d \ n”, i+1, student[i].total);
}
OUTPUT:

TOTAL MARKS
student[1]: 193
student[2]: 197
student[3]: 164

RESULT:

Thus the C program to calculate the total marks using array of structures was executed successfully
executed and output is verified.
FILES: READING AND WRITING, FILE POINTERS, FILE
EX.NO:10
OPERATIONS, RANDOM ACCESS, AND PROCESSOR
DIRECTIVES.

10A. PROGRAM TO COUNT THE NUMBER OF CHARACTERS AND NUMBER OF LINES IN


A FILE USING FILE POINTERS

AIM:
To write a C program to count number of characters and number of lines in a file
using file pointer.

ALGORITHM:

1. Start
2. Create file pointers
3. Enter the file name
4. Open the file with read mode
5. Till the end of file reached read one character at a time
(a) If it is newline character „\n‟, then increment no_of_lines countvalue by one.
(b) if it is a character then increment no_of_characters count value byone.
6. Print no_of_lines and no_of_characters values
7. Stop.

PROGRAM:

#include<stdio.h>
#include <string.h>
main ()
{
FILE *fp;
int ch, no_of_characters = 0, no_of_lines = 1;
char filename[20];
printf(“ \ n Enter the filename: “);
fp = fopen(filename, “r”);
if(fp==NULL)
{
printf(“ \ n Error opening the File”);
exit (1);
}
ch= fgetc(fp);
while(ch!=EOF)
{
if(ch ==‟ \ n‟);
no_of_lines++;
no_of_characters++;
ch = fgetc(fp);
}
if (no_of_characters >0)
printf(“ \ n In the file %s, there are %d lines and %d characters”, filename, no_ of_lines,
no_of_characters);
else
printf(“ \ n File is empty”);
fclose(fp);
}
OUTPUT:

Enter the filename: Letter.txt

In the file Letter. txt, there is 1 line and 18 characters

RESULT:

Thus the C program to count number of characters and number of lines in a file using file pointer
was executed successfully executed and output is verified.
10B. PROGRAM TO COPY ONE FILE TO ANOTHER

AIM:

To write a C program to copy one file to another.

ALGORITHM:

1. Start

2. Create file pointers

3. Read two file names

4. Open first file with read mode

5. Open second file with write mode

6. Read first file character by character and write the characters in the second file till end of file
reached.

7. Close both file pointers

8. Stop.

PROGRAM:

#include <stdio.h>
#include <conio.h>
main ()
{

FILE *fp1, *fp2;


char filename1[20], filename[20];
str[30];
clrscr();
printf(“ \ n Enter the name of the first filename: “);
gets(filename1);
fflush(stdin);
printf(“ \ n Enter the name of the second filename: “);
gets(filename2); fflush(stdin);
if((fp1=fopen(filename1, “r”))==0)
{
printf(“ \ n Error opening the first file”); exit(1);
}
if((fp2=fopen(filename2, “w”))==0)
{
printf(“ \ n Error opening the second file”); exit(1);
}
while((fgets(str, sizeof(str), fp1))!=NULL) fputs(str, fp2);
fclose(fp1);
fclose(fp2);
getch();
return 0;
}
OUTPUT:

Enter the name of the first filename:a.txt


Enter the name of the second filename:b.txt
FILE COPIED

RESULT:

Thus the C program to copy one file to another was executed successfully executed and output is
verified.
10C. PROGRAM TO RANDOMLY READ THE NTH RECORD OF A FILE

AIM:

To read nth record in file using random access method.

ALGORITHM:

1. Start

2. Create employee structure with variables

3. Read the file name with „rb‟ mode

4. Read the record number to read

5. From the file pointed by fp read a record of the specified record starting fromthe beginning of
the file

6. Print the record values

7. Stop.

PROGRAM:

#include<stdio.h>
#include <conio.h>
main ()
{
typedef struct employee
{
int emp_code;
char name[20];
int hra;
int da;
int ta;
};
FILE *fp;
struct employee e;
int result, rec_no;
fp = fopen (“employee.txt”, “rb”);
if(fp==NULL)
{
printf (“ \ n Error opening file”);
exit(1);
}
printf(“ \ n \ n Enter the rec_no you want to read: ”);
scanf(“%d”, &rec_no);
if(rec_no >= 0)
{
fseek(fp, (rec_no - 1)*sizeof (e), SEEK_SET);
result = fread(&e, sizeof(e), 1, fp);
if (result == 1)
{
printf(“ \ n EMPLOYEE CODE: %d”, e. Emp_code);
printf(“ \ n Name: %S”, e.name);
printf(“ \ n HRA, TA and DA: %d %d %d”, e.hra, e.ta, e.da);
}
else
printf(“ \ n Record Not Found”);
}
fclose(fp);
getch();
return 0;
}
OUTPUT:

Enter the rec_no you want to read: 06


Employee CODE: 06
Name : Tanya
HRA, DA and TA: 20000 10000 3000

RESULT:

Thus the C program to read nth record in file using random access method was executed
successfully executed and output is verified.
10D. PROGRAM TO COMPUTE AREA OF A CIRCLE USING PREPROCESSOR DIRECTIVES

AIM:

To write a C program to compute area of a circle using pre-processor

directives.

ALGORITHM:

1. Start

2. Define pi as 3.1415

3. Define circle_area (or) as pi*r*r

4. Read radius

5. Call circle area function radius with to calculate area of a circle.

6. Print area

7. Stop.

PROGRAM:

#include <stdio.h>
#define PI 3. 1415
#definecircleArea(r) (PI*r*r)
int main()
{
float radius, area;
printf(“Enter the radius:”);
scanf(“%f”, &radius);
area = circleArea(radius);
printf(“Area = %.2f”, area);
return();
}
OUTPUT:

Enter the radius: 6


Area = 113.094002

RESULT:

Thus the C program to compute area of a circle using pre-processor directives was executed
successfully executed and output is verified.

You might also like