0% found this document useful (0 votes)
30 views65 pages

CP-LAB Record

c-language lab record
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views65 pages

CP-LAB Record

c-language lab record
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 65

C Programming Lab Record

Exercise 1:
1. Write a C program to print a block F using hash (#), where
the F has a height of six characters and width of five and four
characters.
#include <stdio.h>
int main()
{
printf("######\n");
printf("#\n");
printf("#\n");
printf("#####\n");
printf("#\n");
printf("#\n");
printf("#\n");
return(0);}
Output:
######
#
#
#####
#
#
#
2. Write a C program to compute the perimeter and area of a
rectangle with a height of 7 inches and width of 5 inches.
#include <stdio.h>
/* height and width of a rectangle in inches */
int width;
int height;
int area;
int perimeter;
int main() {
height = 7;
width = 5;
perimeter = 2*(height + width);
printf("Perimeter of the rectangle = %d inches\n", perimeter);
area = height * width;
printf("Area of the rectangle = %d square inches\n", area);
return(0);
}
Output:
Perimeter of the rectangle = 24 inches
Area of the rectangle = 35 square inches
3. Write a C program to display multiple variables.

#include <stdio.h>
int main()
{
int a = 125, b = 12345;
long ax = 1234567890;
short s = 4043;
float x = 2.13459;
double dx = 1.1415927;
char c = 'W';
unsigned long ux = 2541567890;
printf("a + c = %d\n", a + c);
printf("x + c = %f\n", x + c);
printf("dx + x = %f\n", dx + x);
printf("((int) dx) + ax = %ld\n", ((int) dx) + ax);
printf("a + x = %f\n", a + x);
printf("s + b = %d\n", s + b);
printf("ax + b = %ld\n", ax + b);
printf("s + c = %hd\n", s + c);
printf("ax + c = %ld\n", ax + c);
printf("ax + ux = %lu\n", ax + ux);

return 0;
}
Output:
a + c = 212
x + c = 89.134590
dx + x = 3.276183
((int) dx) + ax = 1234567891
a + x = 127.134590
s + b = 16388
ax + b = 1234580235
s + c = 4130
ax + c = 1234567977
ax + ux = 3776135780

Exercise 2:
1. Write a C program to calculate the distance between the two
points.
#include<stdio.h>
#include<math.h>
int main()
{
float x1, y1, x2, y2, distance;
printf("Enter point 1 (x1, y1)\n");
scanf("%f%f", &x1, &y1);
printf("Enter point 2 (x2, y2)\n");
scanf("%f%f", &x2, &y2);
distance = sqrt( (x2 - x1)*(x2 - x1) + (y2 - y1)*(y2 - y1) );
printf("Distance between (%0.2f, %0.2f) and (%0.2f, %0.2f) is
%0.2f\n", x1, y1, x2, y2, distance);
return 0;
}
Output 1:
Enter point 1 (x1, y1)
0
0
Enter point 2 (x2, y2)
5
0
Distance between (0.00, 0.00) and (5.00, 0.00) is 5.00
Output 2:
Enter point 1 (x1, y1)
2
3
Enter point 2 (x2, y2)
10
8
Distance between (2.00, 3.00) and (10.00, 8.00) is 9.43
2. Write a C program that accepts 4 integers p, q, r, s from the
user where r and s are positive and p is even. If q is greater than r
and s is greater than p and if the sum of r and s is greater than the
sum of p and q print "Correct values", otherwise print "Wrong
values".
#include <stdio.h>
int main() {
int p, q, r, s;
printf("\nInput the first integer: ");
scanf("%d", &p);
printf("\nInput the second integer: ");
scanf("%d", &q);
printf("\nInput the third integer: ");
scanf("%d", &r);
printf("\nInput the fourth integer: ");
scanf("%d", &s);
if((q > r) && (s > p) && ((r+s) > (p+q)) && (r > 0) && (s > 0)
&& (p%2 == 0))
{
printf("\nCorrect values\n");
}
else {
printf("\nWrong values\n");
}
return 0;
}
Output
Input the first integer: 25
Input the second integer: 35
Input the third integer: 15
Input the fourth integer: 46
Wrong values
Excercise 3:
1. Write a C program to convert a string to a long integer.
#include<stdio.h>
#include<stdlib.h>
int main ()
{
char buffer[123];
unsigned long ul;
printf ("\nInput an unsigned number: ");
fgets (buffer,123,stdin);
ul = strtoul (buffer,NULL,0);
printf ("Output: %lu\n\n",ul);
return 0;
}
Output:
Input an unsigned number: 25
Output: 25
2. Write a program in C which is a Menu-Driven Program to
compute the area of the various geometrical shape.
#include <stdio.h>
void main()
{
int fig_code;
float side, base, length, breadth, height, area, radius;
printf("-------------------------\n");
printf(" 1 --> Circle\n");
printf(" 2 --> Rectangle\n");
printf(" 3 --> Triangle\n");
printf(" 4 --> Square\n");
printf("-------------------------\n");
printf("Enter the Figure code\n");
scanf("%d", &fig_code);
switch(fig_code)
{
case 1:
printf("Enter the radius\n");
scanf("%f", &radius);
area = 3.142 * radius * radius;
printf("Area of a circle = %f\n", area);
break;
case 2:
printf("Enter the breadth and length\n");
scanf("%f %f", &breadth, &length);
area = breadth * length;
printf("Area of a Reactangle = %f\n", area);
break;
case 3:
printf("Enter the base and height\n");
scanf("%f %f", &base, &height);
area = 0.5 * base * height;
printf("Area of a Triangle = %f\n", area);
break;
case 4:
printf("Enter the side\n");
scanf("%f", &side);
area = side * side;
printf("Area of a Square=%f\n", area);
break;
default:
printf("Error in figure code\n");
break;
}
}

Output:
1 --> Circle
2 --> Rectangle
3 --> Triangle
4 --> Square
-------------------------
Enter the Figure code
1
Enter the radius
30
Area of a circle = 2827.800049

-------------------------
1 --> Circle
2 --> Rectangle
3 --> Triangle
4 --> Square
-------------------------
Enter the Figure code
2
Enter the breadth and length
20 30
Area of a Reactangle = 600.000000

-------------------------
1 --> Circle
2 --> Rectangle
3 --> Triangle
4 --> Square
-------------------------
Enter the Figure code
3
Enter the base and height
45 80
Area of a Triangle = 1800.000000
-------------------------
1 --> Circle
2 --> Rectangle
3 --> Triangle
4 --> Square
-------------------------
Enter the Figure code
4
Enter the side
100
Area of a Square=10000.000000

3. Write a C program to calculate the factorial of a given number.


#include <stdio.h>
int main() {
int n, i;
unsigned long long fact = 1;
printf("Enter an integer: ");
scanf("%d", &n);
// shows error if the user enters a negative integer
if (n < 0)
printf("Error! Factorial of a negative number doesn't exist.");
else {
for (i = 1; i <= n; ++i) {
fact *= i;
}
printf("Factorial of %d = %llu", n, fact);
}

return 0;
}

Output
Enter an integer: 10
Factorial of 10 = 3628800
Exercise 4:
1. Write a program in C to display the n terms of even natural
number and their sum.
#include <stdio.h>
void main()
{
int i,n,sum=0;
printf("Input number of terms : ");
scanf("%d",&n);
printf("\nThe even numbers are :");
for(i=1;i<=n;i++)
{
printf("%d ",2*i);
sum+=2*i;
}
printf("\nThe Sum of even Natural Number upto %d terms : %d
\n",n,sum);
}

Output:
Input number of terms : 5
The even numbers are :2 4 6 8 10
The Sum of even Natural Number upto 5 terms : 30
2. Write a program in C to display the n terms of harmonic series
and their sum. 1 + 1/2 + 1/3 + 1/4 + 1/5 ... 1/n terms.
#include <stdio.h>
void main()
{
int i,n;
float s=0.0;
printf("Input the number of terms : ");
scanf("%d",&n);
printf("\n\n");
for(i=1;i<=n;i++)
{ if(i<n)
{
printf("1/%d + ", i);
s+=1/(float) i; } }
if(i==n)
{
printf("1/%d ",i);
s+=1/(float)i;
} }
printf("\nSum of Series upto %d terms : %f \n",n,s);
}

Output:
Input the number of terms : 5
1/1 + 1/2 + 1/3 + 1/4 + 1/5
Sum of Series upto 5 terms : 2.283334
3. Write a C program to check whether a given number is an
Armstrong number or not.
/*When the sum of the cube of the individual digits of a number
is equal to that number, the number is called Armstrong number. For
example 153.
Sum of its divisor is 13 + 53;+ 33; = 1+125+27 = 153*/
#include <stdio.h>
void main(){
int num,r,sum=0,temp;
printf("Input a number: ");
scanf("%d",&num);
for(temp=num;num!=0;num=num/10){
r=num % 10;
sum=sum+(r*r*r);
}
if(sum==temp)
printf("%d is an Armstrong number.\n",temp);
else
printf("%d is not an Armstrong number.\n",temp);
}

Output:
Input a number: 153
153 is an Armstrong number.
Exercise 5:
1. Write a program in C to print all unique elements in an array.
#include <stdio.h>
void main()
{
int arr1[100], n,ctr=0;
int i, j, k;
printf("\n\nPrint all unique elements of an array:\n");
printf("------------------------------------------\n");
printf("Input the number of elements to be stored in the array :");
scanf("%d",&n);
printf("Input %d elements in the array :\n",n);
for(i=0;i<n;i++)
{
printf("element - %d : ",i);
scanf("%d",&arr1[i]);
}
/*Checking duplicate elements in the array */
printf("\nThe unique elements found in the array are : \n");
for(i=0; i<n; i++)
{
ctr=0; /*Check duplicate bifore the current position and
increase counter by 1 if found.*/
for(j=0; j<i-1; j++)
{
/*Increment the counter when the seaarch value is duplicate.*/
if(arr1[i]==arr1[j])
{
ctr++;
}
}
/*Check duplicate after the current position and
increase counter by 1 if found.*/
for(k=i+1; k<n; k++)
{
/*Increment the counter when the seaarch value is duplicate.*/
if(arr1[i]==arr1[k])
{
ctr++;
}
}
/*Print the value of the current position of the array as
unique value
when counter remain contains its initial value.*/
if(ctr==0)
{
printf("%d ",arr1[i]);
}
}
printf("\n\n");
}

Output:
Print all unique elements of an array:
------------------------------------------
Input the number of elements to be stored in the array :3
Input 3 elements in the array :
element - 0 : 1
element - 1 : 5
element - 2 : 1
The unique elements found in the array are : 5
2. Write a program in C to separate odd and even integers in
separate arrays.
#include <stdio.h>
void main()
{
int arr1[10], arr2[10], arr3[10];
int i,j=0,k=0,n;
printf("\n\nSeparate odd and even integers in separate arrays:\n");
printf("------------------------------------------------------\n");
printf("Input the number of elements to be stored in the array :");
scanf("%d",&n);
printf("Input %d elements in the array :\n",n);
for(i=0;i<n;i++)
{
printf("element - %d : ",i);
scanf("%d",&arr1[i]);
}
for(i=0;i<n;i++)
{
if (arr1[i]%2 == 0)
{ arr2[j] = arr1[i];
j++; }
else
{
arr3[k] = arr1[i];
k++; }
}
printf("\nThe Even elements are : \n");
for(i=0;i<j;i++)
{
printf("%d ",arr2[i]);
}
printf("\nThe Odd elements are :\n");
for(i=0;i<k;i++)
{
printf("%d ", arr3[i]);
}
printf("\n\n");
}
Output:
Separate odd and even integers in separate arrays:
------------------------------------------------------
Input the number of elements to be stored in the array :5
Input 5 elements in the array :
element - 0 : 25
element - 1 : 47
element - 2 : 42
element - 3 : 56
element - 4 : 32
The Even elements are :
42 56 32
The Odd elements are :
25 47

3. Write a program in C to sort elements of array in ascending


order.
#include <stdio.h>
void main()
{
int arr1[100];
int n, i, j, tmp;
printf("\n\nsort elements of array in ascending order :\n ");
printf("----------------------------------------------\n");
printf("Input the size of array : ");
scanf("%d", &n);
printf("Input %d elements in the array :\n",n);
for(i=0;i<n;i++)
{ printf("element - %d : ",i);
scanf("%d",&arr1[i]);
}
for(i=0; i<n; i++)
{
for(j=i+1; j<n; j++)
{
if(arr1[j] <arr1[i])
{
tmp = arr1[i];
arr1[i] = arr1[j];
arr1[j] = tmp;
}
}
}
printf("\nElements of array in sorted ascending order:\n");
for(i=0; i<n; i++)
{
printf("%d ", arr1[i]);
}
printf("\n\n");
}

Output:
sort elements of array in ascending order :
----------------------------------------------
Input the size of array : 5
Input 5 elements in the array :
element - 0 : 2
element - 1 : 7
element - 2 : 4
element - 3 : 5
element - 4 : 9
Elements of array in sorted ascending order:
2 4 5 7 9

Exercise 6:
1. Write a program in C for multiplication of two square
Matrices.
#include <stdio.h>
void main()
{
int arr1[50][50],brr1[50][50],crr1[50][50],i,j,k,r1,c1,r2,c2,sum=0;
printf("\n\nMultiplication of two Matrices :\n");
printf("----------------------------------\n");
printf("\nInput the rows and columns of first matrix : ");
scanf("%d %d",&r1,&c1);
printf("\nInput the rows and columns of second matrix : ");
scanf("%d %d",&r2,&c2);
if(c1!=r2){
printf("Mutiplication of Matrix is not possible.");
printf("\nColumn of first matrix and row of second matrix must be
same.");
}
else
{
printf("Input elements in the first matrix :\n");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
printf("element - [%d],[%d] : ",i,j);
scanf("%d",&arr1[i][j]);
}
}
printf("Input elements in the second matrix :\n");
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
{
printf("element - [%d],[%d] : ",i,j);
scanf("%d",&brr1[i][j]);
}
}
printf("\nThe First matrix is :\n");
for(i=0;i<r1;i++)
{
printf("\n");
for(j=0;j<c1;j++)
printf("%d\t",arr1[i][j]);
}

printf("\nThe Second matrix is :\n");


for(i=0;i<r2;i++)
{
printf("\n");
for(j=0;j<c2;j++)
printf("%d\t",brr1[i][j]);
}
//multiplication of matrix
for(i=0;i<r1;i++)
for(j=0;j<c2;j++)
crr1[i][j]=0;
for(i=0;i<r1;i++) //row of first matrix
{
for(j=0;j<c2;j++) //column of second matrix
{
sum=0;
for(k=0;k<c1;k++)
sum=sum+arr1[i][k]*brr1[k][j];
crr1[i][j]=sum;
}
}
printf("\nThe multiplication of two matrices is : \n");
for(i=0;i<r1;i++)
{
printf("\n");
for(j=0;j<c2;j++)
{
printf("%d\t",crr1[i][j]);
}
}
}
printf("\n\n");
}
Output:
Multiplication of two Matrices :
----------------------------------
Input the rows and columns of first matrix : 2 2
Input the rows and columns of second matrix : 2 2

Input elements in the first matrix :


element - [0],[0] : 1
element - [0],[1] : 2
element - [1],[0] : 3
element - [1],[1] : 4
Input elements in the second matrix :
element - [0],[0] : 5
element - [0],[1] : 6
element - [1],[0] : 7
element - [1],[1] : 8

The First matrix is :


1 2
3 4
The Second matrix is :
5 6
7 8
The multiplication of two matrices is :
19 22
43 50

2. Write a program in C to find transpose of a given matrix.


#include <stdio.h>
void main()
{
int arr1[50][50],brr1[50][50],i,j,r,c;
printf("\n\nTranspose of a Matrix :\n");
printf("---------------------------\n");
printf("\nInput the rows and columns of the matrix : ");
scanf("%d %d",&r,&c);
printf("Input elements in the first matrix :\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf("element - [%d],[%d] : ",i,j);
scanf("%d",&arr1[i][j]);
}
}

printf("\nThe matrix is :\n");


for(i=0;i<r;i++)
{
printf("\n");
for(j=0;j<c;j++)
printf("%d\t",arr1[i][j]);
}

for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
brr1[j][i]=arr1[i][j];
}
}

printf("\n\nThe transpose of a matrix is : ");


for(i=0;i<c;i++){
printf("\n");
for(j=0;j<r;j++){
printf("%d\t",brr1[i][j]);
}
}
printf("\n\n");
}

Output:
Transpose of a Matrix :
---------------------------
Input the rows and columns of the matrix : 2 2
Input elements in the first matrix :
element - [0],[0] : 1
element - [0],[1] : 2
element - [1],[0] : 3
element - [1],[1] : 4

The matrix is :
1 2
3 4
The transpose of a matrix is :
1 3
2 4

Exercise 7:
1. Write a program in C to search an element in a row wise and
column wise sorted matrix.
#include <stdio.h>
int searchElement(int arr2D[4][4], int n, int x)
{
int i = 0, j = n-1;
while ( i < n && j >= 0 )
{
if ( arr2D[i][j] == x )
{
printf("\nThe element Found at the position in the matrix is:
%d, %d", i, j);
return 1;
}
if ( arr2D[i][j] < x )
j--;
else
i++;
}
printf("\nThe given element not found in the 2D array.");
return 0;
}

int main()
{
int arr2D[4][4] = { {15, 23, 31, 39},
{18, 26, 36, 43},
{25, 28, 37, 48},
{30, 34, 39, 50},
};
int i,j,v;
v=37;
//------------- print original array ------------------
printf("The given array in matrix form is : \n");
for(i = 0; i < 4; i++)
{
for (j=0;j<4;j++)
{
printf("%d ", arr2D[i][j]);
}
printf("\n");
}
//------------------------------------------------------
printf("The given value for searching is: %d",v);
searchElement(arr2D, 4, v);
return 0;
}
Output:
The given array in matrix form is :
15 23 31 39
18 26 36 43
25 28 37 48
30 34 39 50
The given value for searching is: 37
The element Found at the position in the matrix is: 2, 2

2. Write a program in C to print individual characters of string in


reverse order.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void main()
{
char str[100]; /* Declares a string of size 100 */
int l=0;
printf("\n\nPrint individual characters of string in reverse order
:\n");
printf("------------------------------------------------------\n");
printf("Input the string : ");
fgets(str, sizeof str, stdin);
l=strlen(str);
printf("The characters of the string in reverse are : \n");
for(str[l]='\0';l>=0;l--)
{
printf("%c ", str[l]);
}
printf("\n");
}

Output:
Print individual characters of string in reverse order :
-----------------------------------------------------------
Input the string : raja
The characters of the string in reverse are : ajar

Exercise 8:
1. Write a program in C to compare two strings without using
string library functions.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define str_size 100 //Declare the maximum size of the string
void main()
{
char str1[str_size], str2[str_size];
int flg=0 , i=0;
printf("\n\nCompare two string whether they are equal or not
:\n");
printf("------------------------------------------------------\n");
printf("Input the 1st string : ");
fgets(str1, sizeof str1, stdin);
printf("Input the 2nd string : ");
fgets(str2, sizeof str2, stdin);
/* Runs till both strings are equal */
while(str1[i] == str2[i])
{
if(str1[i] == '\0' || str2[i] == '\0')
break;

i++;
}
if(str1[i-1] == '\0' && str2[i-1]=='\0')
flg=0;
else if(str1[i] > str2[i])
flg=1;
else if(str1[i] < str2[i])
flg=-1;

if(flg == 0)
{
printf("\nThe length of both strings are equal and \nalso both
strings are equal.\n\n");
}
else if(flg == -1)
{
printf("\nThe length of the first string is smaller than
second.\n\n");
}
else
{
printf("\nThe length of the first string is greater than
second.\n\n");
}
}
Output:
Compare two string whether they are equal or not :
------------------------------------------------------
Input the 1st string : This is first string
Input the 2nd string : This is first string
The length of both strings are equal and
also both strings are equal.
2. Write a program in C to copy one string to another string.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void main()
{
char str1[100], str2[100];
int i;
printf("\n\nCopy one string into another string :\n");
printf("-----------------------------------------\n");
printf("Input the string : ");
fgets(str1, sizeof str1, stdin);

/* Copies string1 to string2 character by character */


i=0;
while(str1[i]!='\0')
{
str2[i] = str1[i];
i++;
}

//Makes sure that the string is NULL terminated


str2[i] = '\0';
printf("\nThe First string is : %s\n", str1);
printf("The Second string is : %s\n", str2);
printf("Number of characters copied : %d\n\n", i);
}

Output:
Copy one string into another string :
-----------------------------------------
Input the string : This is a string to be copied.

The First string is : This is a string to be copied.

The Second string is : This is a string to be copied.

Number of characters copied : 31


Exercise 9:
1. Write a C program to store information using structures
with dynamic memory allocation.
#include <stdio.h>
#include<stdlib.h>
struct course
{
int marks;
char subject[30];
};
int main()
{
struct course *ptr;
int i, noOfRecords;
printf("Enter number of records: ");
scanf("%d", &noOfRecords);
// Allocates the memory for noOfRecords structures with pointer ptr
pointing to the base address.
ptr = (struct course*) malloc (noOfRecords * sizeof(struct course));
for(i = 0; i < noOfRecords; ++i)
{
printf("Enter name of the subject and marks respectively:\n");
scanf("%s %d", &(ptr+i)->subject, &(ptr+i)->marks);
}
printf("Displaying Information:\n");
for(i = 0; i < noOfRecords ; ++i)
printf("%s\t%d\n", (ptr+i)->subject, (ptr+i)->marks);
return 0;
}

Output
Enter number of records: 2
Enter name of the subject and marks respectively:
mathematics
22
Enter name of the subject and marks respectively:
physics
33
Displaying Information:
mathematics 22
physics 33
2. Write a C program to demonstrate how to handle the
pointers in the program.
#include <stdio.h>
int main()
{
int* ab;
int m;
m=29;
printf("\n\n Pointer : How to handle the pointers in the program
:\n");
printf("------------------------------------------------------------\n");
printf(" Here in the declaration ab = int pointer, int m= 29\n\n");
printf(" Address of m : %p\n",&m);
printf(" Value of m : %d\n\n",m);
ab=&m;
printf(" Now ab is assigned with the address of m.\n");
printf(" Address of pointer ab : %p\n",ab);
printf(" Content of pointer ab : %d\n\n",*ab);
m=34;
printf(" The value of m assigned to 34 now.\n");
printf(" Address of pointer ab : %p\n",ab);
printf(" Content of pointer ab : %d\n\n",*ab);
*ab=7;
printf(" The pointer variable ab is assigned the value 7 now.\n");
printf(" Address of m : %p\n",&m);//as ab contain the address of m
//so *ab changed the value of m and now m become 7
printf(" Value of m : %d\n\n",m);
return 0;
}
Output:
Pointer : How to handle the pointers in the program :
------------------------------------------------------------
Here in the declaration ab = int pointer, int m= 29
Address of m : 0x7fff24a3f8bc
Value of m : 29
Now ab is assigned with the address of m.
Address of pointer ab : 0x7fff24a3f8bc
Content of pointer ab : 29
The value of m assigned to 34 now.
Address of pointer ab : 0x7fff24a3f8bc
Content of pointer ab : 34
The pointer variable ab is assigned the value 7 now.
Address of m : 0x7fff24a3f8bc
Value of m : 7

Exercise 10
1. Write a C program to demonstrate the use of & (address of)
and * (value at address operator).
#include <stdio.h>
int main(void)
{
//normal variable
int num = 100;
//pointer variable
int *ptr;
//pointer initialization
ptr = &num;
//printing the value
printf("value of num = %d\n", *ptr);
//printing the addresses
printf("Address of num: %x\n", &num);
printf("Address of ptr: %x\n", &ptr);
return 0;
}
Output
value of num = 100
Address of num: 9505c134
Address of ptr: 9505c138
2. Write a C program to add two numbers using pointers.
#include<stdio.h>
int main() {
int *ptr1, *ptr2;
int num;
printf("\nEnter two numbers : ");
scanf("%d %d", ptr1, ptr2);
num = *ptr1 + *ptr2;
printf("Sum = %d", num);
return (0);
}
Output:
Enter two numbers: 2 3
Sum = 5
Exercise 11:
1. Write a C program to add numbers using call by reference.
#include <stdio.h>
int addTwoNumbers(int *, int *);
int main()
{
int fno, sno, sum;
printf(" Input the first number : ");
scanf("%d", &fno);
printf(" Input the second number : ");
scanf("%d", &sno);
sum = addTwoNumbers(&fno, &sno);
printf(" The sum of %d and %d is %d\n\n", fno, sno, sum);
return 0;
}
int addTwoNumbers(int *n1, int *n2)
{
int sum;
sum = *n1 + *n2;
return sum;
}

Output:
Input the first number : 5
Input the second number : 6
The sum of 5 and 6 is 11
2. Write a C program to find the largest element using
dynamic memory allocation.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i, num;
float *data;
printf("How many elements u want to enter :: ");
scanf("%d", &num);
// Allocates the memory for 'num' elements.
data = (float*) calloc(num, sizeof(float));
if(data == NULL)
{
printf("\nError!!! memory not allocated.");
exit(0);
}
// Stores the number entered by the user.
for(i = 0; i < num; ++i)
{
printf("\nEnter Number %d :: ", i + 1);
scanf("%f", data + i);
}
// Loop to store largest number at address data
for(i = 1; i < num; ++i)
{
// Change < to > if you want to find the smallest number
if(*data < *(data + i))
*data = *(data + i);
}
printf("\nLargest element = %.2f\n", *data);
return 0;
}
Output
How many elements u want to enter :: 6
Enter Number 1 :: 3
Enter Number 2 :: 1
Enter Number 3 :: 5
Enter Number 4 :: 7
Enter Number 5 :: 3
Enter Number 6 :: 8
Largest element = 8.00
Excercise 12:
1. Write a C program to swap elements using call by reference.
#include <stdio.h>
void swap(int*, int*);
int main()
{
int x, y;
printf("Enter the value of x and y\n");
scanf("%d%d",&x,&y);
printf("Before Swapping\nx = %d\ny = %d\n", x, y);
swap(&x, &y);
printf("After Swapping\nx = %d\ny = %d\n", x, y);
return 0;
}
void swap(int *a, int *b)
{
int temp;
temp = *b;
*b = *a;
*a = temp;
}

Output
Enter the value of x and y 10 20
Before Swapping
x =10
y = 20
After Swapping
x =20
y =10
2. Write a C program to count number of vowels and
consonants in a string using a pointer.
#include <stdio.h>
int main()
{
char str[100];
char *ptr;
int cntV,cntC;
printf("Enter a string: ");
gets(str);
//assign address of str to ptr
ptr=str;
cntV=cntC=0;
while(*ptr!='\0')
{
if(*ptr=='A' ||*ptr=='E' ||*ptr=='I' ||*ptr=='O' ||*ptr=='U'
||*ptr=='a' ||*ptr=='e' ||*ptr=='i' ||*ptr=='o' ||*ptr=='u')
cntV++;
else
cntC++;
//increase the pointer, to point next character
ptr++;
}
printf("Total number of VOWELS: %d, CONSONANT:
%d\n",cntV,cntC);
return 0;
}
Output
Enter a string: This is a test string
Total number of VOWELS: 5, CONSONANT: 16
Excercise 13:
1. Write a C program to show how a function returning
pointer.
#include<stdio.h>
int *return_pointer(int *, int); // this function returns a pointer of
int main()
{
int i, *ptr;
int arr[] = {11, 22, 33, 44, 55};
i = 4;
printf("Address of arr = %u\n", arr);
ptr = return_pointer(arr, i);
printf("\nAfter incrementing arr by 4 \n\n");
printf("Address of ptr = %u\n\n" , ptr);
printf("Value at %u is %d\n", ptr, *ptr);
return 0;
}
int *return_pointer(int *p, int n)
{
p = p + n;
return p;
}
Output:
Address of arr = 2686736
After incrementing arr by 4
Address of ptr = 2686752
Value at 2686752 is 55

2. Write a C program to find sum of n elements entered by


user. To perform this program allocate memory dynamically
using malloc function.
#include<stdio.h>
#include<stdlib.h>
int main()
{
int num, i, *ptr, sum=0;
printf("Enter number of elements ");
scanf("%d",&num);
ptr= (int*) malloc (num*sizeof(int)); //memory allocated using
malloc()
printf("Enter elements :\n");
for(i=0;i<num;i++)
{
scanf("%d",ptr+i);
sum += *(ptr+i);
}
printf("Sum= %d",sum);
free(ptr);
return 0;
}

Output
Enter number of elements : 3
Enter elements :
10
20
30
Sum= 60
Excercise 14
1. Write a C program to find sum of n elements entered by
user. To perform this program allocate memory dynamically
using calloc function.
#include<stdio.h>
#include<stdlib.h>
int main()
{
int num, i, *ptr, sum=0;
printf("Enter number of elements: ");
scanf("%d",&num);
ptr= (int*) calloc (num,sizeof(int)); //memory allocated using
malloc()
printf("Enter elements :\n");
for(i=0;i<num;i++)
{
scanf("%d",ptr+i);
sum += *(ptr+i);
}
printf("Sum= %d",sum);
free(ptr);
return 0;
}
Output:
Enter number of elements: 4
Enter elements :
1
20
3
5
Sum= 29
2. Write a C program to convert decimal to binary using
function.
#include <stdio.h>
#include <math.h>
long decimalToBinary(int decimalnum)
{
long binarynum = 0;
int rem, temp = 1;
while (decimalnum!=0)
{
rem = decimalnum%2;
decimalnum = decimalnum / 2;
binarynum = binarynum + rem*temp;
temp = temp * 10;
}
return binarynum;
}
int main()
{
int decimalnum;
printf("Enter a Decimal Number: ");
scanf("%d", &decimalnum);
printf("Equivalent Binary Number is: %ld",
decimalToBinary(decimalnum));
return 0;
}
Output:
Enter a Decimal Number: 234
Equivalent Binary Number is: 11101010

Exercise 15:
1. Write a C program to check whether a number is prime
number or not using the function.
#include<stdio.h>
int PrimeOrNot(int);
int main()
{
int n1,prime;
printf(" Input a positive number : ");
scanf("%d",&n1);
prime = PrimeOrNot(n1);
if(prime==1)
printf(" The number %d is a prime number.\n",n1);
else
printf(" The number %d is not a prime number.\n",n1);
return 0;
}
int PrimeOrNot(int n1)
{
int i=2;
while(i<=n1/2)
{
if(n1%i==0)
return 0;
else
i++;
}
return 1;
}
Output
Input a positive number : 5
The number 5 is a prime number.
2. Write a C program to get the largest element of array using
function.
int find_largest(int [],int);
int main()
{
int arr[30],size,largest,i;
printf("Enter the size of the array maximum up to 30: ");
scanf("%d",&size);
printf("Enter the %d integer numbers: ",size);
for(i=0;i<size;i++)
scanf("%d",&arr[i]);
largest = find_largest(arr,size);
printf("\nThe largest element is: %d\n",largest);
return 0;
}
int find_largest(int arr1[],int size1)
{
int temp_larg,i;
temp_larg=arr1[0];
for(i=1;i<size1;i++)
{
if(arr1[i]>temp_larg)
temp_larg=arr1[i];
}
return(temp_larg);
}

Output
Enter the size of the array maximum up to 30: 4
Enter the 4 integer numbers: 2 5 1 4
The largest element is: 5
Exercise 16:
1. Write a C program to append multiple lines at the end of a
text file.
Assume that the content of the file test.txt is :
test line 1
test line 2
test line 3
test line 4
#include <stdio.h>
int main ()
{
FILE * fptr;
int i,n;
char str[100];
char fname[20];
char str1;
printf(" Input the file name to be opened : ");
scanf("%s",fname);
fptr = fopen(fname, "a");
printf(" Input the number of lines to be written : ");
scanf("%d", &n);
printf(" The lines are : \n");
for(i = 0; i < n+1;i++)
{
fgets(str, sizeof str, stdin);
fputs(str, fptr);
}
fclose (fptr);
//----- Read the file after appended -------
fptr = fopen (fname, "r");
printf("\n The content of the file %s is :\n",fname);
str1 = fgetc(fptr);
while (str1 != EOF)
{
printf ("%c", str1);
str1 = fgetc(fptr);
}
printf("\n\n");
fclose (fptr);
//------- End of reading ------------------
return 0;
}

Output:
Input the file name to be opened : test.txt
Input the number of lines to be written : 3
The lines are :
test line 5
test line 6
test line 7
The content of the file test.txt is :
test line 1
test line 2
test line 3
test line 4
test line 5
test line 6
test line 7
2. Write a C program to copy a file in another name.
Assume that the content of the file test.txt is :
test line 1
test line 2
test line 3
test line 4
#include <stdio.h>
#include <stdlib.h>
void main()
{
FILE *fptr1, *fptr2;
char ch, fname1[20], fname2[20];
printf(" Input the source file name : ");
scanf("%s",fname1);
fptr1=fopen(fname1, "r");
if(fptr1==NULL)
{
printf(" File does not found or error in opening.!!");
exit(1);
}
printf(" Input the new file name : ");
scanf("%s",fname2);
fptr2=fopen(fname2, "w");
if(fptr2==NULL)
{
printf(" File does not found or error in opening.!!");
fclose(fptr1);
exit(2);
}
while(1)
{
ch=fgetc(fptr1);
if(ch==EOF)
{
break;
}
else
{
fputc(ch, fptr2);
}
}
printf(" The file %s copied successfully in the file %s.
\n\n",fname1,fname2);
fclose(fptr1);
fclose(fptr2);
getchar();
}

Output:
Input the source file name : test.txt
Input the new file name : test1.txt
The file test.txt copied successfully in the file test1.txt.
3. Write a C program to remove a file from a disk.
#include <stdio.h>
void main()
{
int status;
char fname[20];
printf(" Input the name of file to delete : ");
scanf("%s",fname);
status=remove(fname);
if(status==0)
{
printf(" The file %s is deleted successfully..!!\n\n",fname);
}
else
{
printf(" Unable to delete file %s\n\n",fname);
}
}
Output:
Input the name of file to delete : test.txt
The file test.txt is deleted successfully..!!

You might also like