0% found this document useful (0 votes)
57 views48 pages

C Prog R19 Lab Manual

The document contains examples of C programs to print patterns, calculate areas of shapes, find distances between points, convert strings to integers, calculate factorials and series sums, and check if a number is Armstrong. It provides the code, inputs/outputs and explanations for each small programming problem to demonstrate basic C programming concepts. The problems cover printing patterns, calculations, data types, loops, functions, conditional statements and more. The document is intended as a learning exercise for a programming course.

Uploaded by

udayalugolu6363
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)
57 views48 pages

C Prog R19 Lab Manual

The document contains examples of C programs to print patterns, calculate areas of shapes, find distances between points, convert strings to integers, calculate factorials and series sums, and check if a number is Armstrong. It provides the code, inputs/outputs and explanations for each small programming problem to demonstrate basic C programming concepts. The problems cover printing patterns, calculations, data types, loops, functions, conditional statements and more. The document is intended as a learning exercise for a programming course.

Uploaded by

udayalugolu6363
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/ 48

Kakinada Institute Of Technology And Science Department Of CSE

EXERCISE-1
a. 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");
return(0);
}
(Or)

#include<stdio.h>
int main()
{
int row,col;
for(row=6;row>=1;row--){
for(col=1;col<=6;col++){
if(row==6 || col==1)
printf("#");
}
for(col=1;col<=4;col++){
if(row==4)
printf("#");
}
printf("\n");
}
return 0;
}

OUTPUT:-
#####
#
#
####
#
#

Page | 1
Programming for Problem Solving using C
Kakinada Institute Of Technology And Science Department Of CSE
b. Write a c program to compute the parameter and area of a rectangle with a height of 7
inches and width of 5 inches
Program:-
#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

Page | 2
Programming for Problem Solving using C
Kakinada Institute Of Technology And Science Department Of CSE

c. 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);
}
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

Page | 3
Programming for Problem Solving using C
Kakinada Institute Of Technology And Science Department Of CSE

Exercise-2
2(a).Write a program to print the distance between the two points

Program:
#include <stdio.h>
#include <math.h>

int main()
{
float x1, y1, x2, y2, gdistance;
printf("Input x1: ");
scanf("%f", &x1);
printf("Input y1: ");
scanf("%f", &y1);
printf("Input x2: ");
scanf("%f", &x2);
printf("Input y2: ");
scanf("%f", &y2);
gdistance = ((x2-x1)*(x2-x1))+((y2-y1)*(y2-y1));
printf("Distance between the said points: %.4f", sqrt(gdistance));
printf("\n");
return 0;
}

Output:

Input x1: 25
Input y1: 15
Input x2: 35
Input y2: 10
Distance between the said points: 11.1803

Page | 4
Programming for Problem Solving using C
Kakinada Institute Of Technology And Science Department Of CSE

2(b). Write a c program that accept 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 value",otherwise print "wrong values"

Program:
#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

Page | 5
Programming for Problem Solving using C
Kakinada Institute Of Technology And Science Department Of CSE

Exercise-3

a. Write a c program to convert a string to a long integer

#include<stdio.h>
#include<stdlib.h>
int main ()
{
char buffer[] = "2016 40a0b0 -1101110100110111100110 0x5abfff";
char * ptr_end;
long int i1, i2, i3, i4;

i1 = strtol (buffer,&ptr_end,10);
i2 = strtol (ptr_end,&ptr_end,16);
i3 = strtol (ptr_end,&ptr_end,2);
i4 = strtol (ptr_end,NULL,0);
printf ("\nIn decimals: %ld, %ld, %ld, %ld.\n\n", i1, i2, i3,i4);
return 0;
}
Output:
In decimals: 2016, 4235440, -3624422, 5947391.

Page | 6
Programming for Problem Solving using C
Kakinada Institute Of Technology And Science Department Of CSE

b. Write a program c which is a menu driven program to compute the area of the various
geometric shape

#include <stdio.h>
void main ()
{
int choice,r,l,w,b,h;
float area;
printf("Input 1 for area of circle\n");
printf("Input 2 for area of rectangle\n");
printf("Input 3 for area of triangle\n");
printf("Input your choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("Input radious of the circle : ");
scanf("%d",&r);
area=3.14*r*r;
break;
case 2:
printf("Input length and width of the rectangle :");
scanf("%d%d",&l,&w);
area=l*w;
break;
case 3:
printf("Input the base and hight of the triangle:");
scanf("%d%d",&b,&h);
area=.5*b*h;
break;
}
printf("The area is : %f\n",area);
}

Output :
for area of circle
Input 2 for area of rectangle
Input 3 for area of triangle
Input your choice : 1
Input radious of the circle : 5
The area is : 78.500000
Page | 7
Programming for Problem Solving using C
Kakinada Institute Of Technology And Science Department Of CSE

c. Write a c program to calculate the factorial of a given number

#include <stdio.h>
int main()
{
int n, i;
unsigned long long factorial = 1;

printf("Enter an integer: ");


scanf("%d",&n);

// show 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)
{
factorial *= i; // factorial = factorial*i;
}
printf("Factorial of %d = %llu", n, factorial);
}

return 0;
}

Output:
Enter an integer: 10
Factorial of 10 = 3628800

Page | 8
Programming for Problem Solving using C
Kakinada Institute Of Technology And Science Department Of CSE
Exercise-4
4a Calculate 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

Page | 9
Programming for Problem Solving using C
Kakinada Institute Of Technology And Science Department Of CSE

4b Calculate the harmonic series and their sum

#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

Page | 10
Programming for Problem Solving using C
Kakinada Institute Of Technology And Science Department Of CSE

4c Write a c program to check whether given number is Armstrong or not

#include<stdio.h>
int main()
{
int n,r,sum=0,temp;
printf("enter the number=");
scanf("%d",&n);
temp=n;
while(n>0)
{
r=n%10;
sum=sum+(r*r*r);
n=n/10;
}
if(temp==sum)
printf("armstrong number ");
else
printf("not armstrong number");
return 0;
}

Output:

enter the number=153

armstrong number

enter the number=5

not armstrong number

Page | 11
Programming for Problem Solving using C
Kakinada Institute Of Technology And Science Department Of CSE

Exercise-5
5(a). 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++;
}
Page | 12
Programming for Problem Solving using C
Kakinada Institute Of Technology And Science Department Of CSE
}
/*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

Page | 13
Programming for Problem Solving using C
Kakinada Institute Of Technology And Science Department Of CSE

5(b). 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]);
}
Page | 14
Programming for Problem Solving using C
Kakinada Institute Of Technology And Science Department Of CSE
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

Page | 15
Programming for Problem Solving using C
Kakinada Institute Of Technology And Science Department Of CSE

5(c).Write a C program to accept N numbers and arrange them in an ascending order

#include <stdio.h>
void main()
{
int i, j, a, n, number[30];
printf("Enter the value of N \n");
scanf("%d", &n);
printf("Enter the numbers \n");
for (i = 0; i < n; ++i)
scanf("%d", &number[i]);
for (i = 0; i < n; ++i)
{
for (j = i + 1; j < n; ++j)
{
if (number[i] > number[j])
{
a = number[i];
number[i] = number[j];
number[j] = a;
}
}
}

printf("The numbers arranged in ascending order are given below \n");


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

Output:
Enter the value of N
6
Enter the numbers
3 78 90 456 780 200
The numbers arranged in ascending order are given below
3
78
90
200
456
780
Page | 16
Programming for Problem Solving using C
Kakinada Institute Of Technology And Science Department Of CSE

Exercise-6
a. Write a program in c for multiplication of two square matrices.

Program:-

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]);
}
}
Page | 17
Programming for Problem Solving using C
Kakinada Institute Of Technology And Science Department Of CSE
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");
}
Multiplication of two Matrices :
Page | 18
Programming for Problem Solving using C
Kakinada Institute Of Technology And Science Department Of CSE
----------------------------------

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] : 1
element - [0],[1] : 2
element - [1],[0] : 3
element - [1],[1] : 4

The First matrix is :


1 2
3 4
The Second matrix is :

1 2
3 4
The multiplication of two matrices is :

7 10
15 22

Page | 19
Programming for Problem Solving using C
Kakinada Institute Of Technology And Science Department Of CSE
b. Write a program in c to find transpose of a given matrix

#include <stdio.h>
int main()
{
int a[10][10], transpose[10][10], r, c, i, j;
printf("Enter rows and columns of matrix: ");
scanf("%d %d", &r, &c);
// Storing elements of the matrix
printf("\nEnter elements of matrix:\n");
for(i=0; i<r; ++i)
for(j=0; j<c; ++j)
{
printf("Enter element a%d%d: ",i+1, j+1);
scanf("%d", &a[i][j]);
}
// Displaying the matrix a[][] */
printf("\nEntered Matrix: \n");
for(i=0; i<r; ++i)
for(j=0; j<c; ++j)
{
printf("%d ", a[i][j]);
if (j == c-1)
printf("\n\n");
}
// Finding the transpose of matrix a
for(i=0; i<r; ++i)
for(j=0; j<c; ++j)
{
transpose[j][i] = a[i][j];
}
// Displaying the transpose of matrix a
printf("\nTranspose of Matrix:\n");
for(i=0; i<c; ++i)
for(j=0; j<r; ++j)
{
printf("%d ",transpose[i][j]);
if(j==r-1)
printf("\n\n");
}
return 0;
}
Page | 20
Programming for Problem Solving using C
Kakinada Institute Of Technology And Science Department Of CSE

Output:
Enter rows and columns of matrix: 2 3

Enter elements of matrix:


Enter element a11: 2
Enter element a12: 4
Enter element a13: 6
Enter element a21: 3
Enter element a22: 6
Enter element a23: 9
Entered Matrix:
2 4 6

3 6 9

Transpose of Matrix:
2 3

4 6

6 9

Page | 21
Programming for Problem Solving using C
Kakinada Institute Of Technology And Science Department Of CSE
Exercise-7
7(a). 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");
Page | 22
Programming for Problem Solving using C
Kakinada Institute Of Technology And Science Department Of CSE
}
//------------------------------------------------------
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 given element not found in the 2D array.

Page | 23
Programming for Problem Solving using C
Kakinada Institute Of Technology And Science Department Of CSE
7b) C Program To Print Individual Characters Of A String In A Reverse Order

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

void printReverse(char str[])


{
int length = strlen(str);

// Traverse string from end


int i;
for (i = length - 1; i >= 0; i--) {
if (str[i] == ' ') {

// putting the NULL character at the


// position of space characters for
// next iteration.
str[i] = '\0';

// Start from next charatcer


printf("%s ", &(str[i]) + 1);
}
}

// printing the last word


printf("%s", str);
}

// Driver code
int main()
{
char str[] = "I AM A GEEK";
printReverse(str);
return 0;
}

Output:

GEEK A I AM

Page | 24
Programming for Problem Solving using C
Kakinada Institute Of Technology And Science Department Of CSE
Exercise-8
a. Write a c program to compare two strings without using string library function.

#include<stdio.h>

int main() {
char str1[30], str2[30];
int i;

printf("\nEnter two strings :");


gets(str1);
gets(str2);

i = 0;
while (str1[i] == str2[i] && str1[i] != '\0')
i++;
if (str1[i] > str2[i])
printf("str1 > str2");
else if (str1[i] < str2[i])
printf("str1 < str2");
else
printf("str1 = str2");

return (0);
}

Output:-
Enter two strings :siva
venkata
str1 < str2

Page | 25
Programming for Problem Solving using C
Kakinada Institute Of Technology And Science Department Of CSE

8(b). Write a c program to copy one string to another string.


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

int main() {
char str1[100];
char str2[100];

printf("\nEnter the String 1 : ");


gets(str1);

strcpy(str2, str1);
printf("\nCopied String : %s", str2);

return (0);
}

Output:-

Enter the String 1 : kits

Copied String : kits

Page | 26
Programming for Problem Solving using C
Kakinada Institute Of Technology And Science Department Of CSE

Exercise-9
a. Write a c program to store information using structures with dynamically memory
allocation

#include<stdio.h>
#include<stdlib.h>
struct course
{
int marks;
charsubject[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);
return0;
}

Output:

Enter number of records: 2


Enter name of the subject and marks respectively:
maths 55
Enter name of the subject and marks respectively:
cp 75
Displaying Information:
maths 55
cp 75

Page | 27
Programming for Problem Solving using C
Kakinada Institute Of Technology And Science Department Of CSE
9b: Write a program in c to demonstrate how to handle the pointers in the program
#include<iostream.h>
int main()
{
int* ab;
int 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 : 0x7ffc52733d74
Value of m : 29
Now ab is assigned with the address of m.
Address of pointer ab : 0x7ffc52733d74
Content of pointer ab : 29
The value of m assigned to 34 now.
Address of pointer ab : 0x7ffc52733d74
Content of pointer ab : 34
The pointer variable ab is assigned the value 7 now.
Address of m : 0x7ffc52733d74
Value of m : 7
Page | 28
Programming for Problem Solving using C
Kakinada Institute Of Technology And Science Department Of CSE
Exercise 10:
a. Write a program in c to demonstrate the use of &(address of)and*(value at address
operator
#include<stdio.h>
int main()
{
int first, second, *p, *q, sum;
printf("Enter two integers to add\n");
scanf("%d%d", &first, &second);
p = &first;
q = &second;
sum = *p + *q;
printf("Sum of the numbers = %d\n", sum);
return 0;
}

#include <stdio.h>
void main()
{
int m=300;
float fx = 300.60;
char cht = 'z';
printf("\n\n Pointer : Demonstrate the use of & and * operator :\n");
printf("--------------------------------------------------------\n");
int *pt1;
float *pt2;
char *pt3;
pt1= &m;
pt2=&fx;
pt3=&cht;
printf ( " m = %d\n",m);
printf ( " fx = %f\n",fx);
printf ( " cht = %c\n",cht);
printf("\n Using & operator :\n");
printf("-----------------------\n");
printf ( " address of m = %p\n",&m);
printf ( " address of fx = %p\n",&fx);
printf ( " address of cht = %p\n",&cht);
printf("\n Using & and * operator :\n");
printf("-----------------------------\n");
printf ( " value at address of m = %d\n",*(&m));
printf ( " value at address of fx = %f\n",*(&fx));
Page | 29
Programming for Problem Solving using C
Kakinada Institute Of Technology And Science Department Of CSE
printf ( " value at address of cht = %c\n",*(&cht));
printf("\n Using only pointer variable :\n");
printf("----------------------------------\n");
printf ( " address of m = %p\n",pt1);
printf ( " address of fx = %p\n",pt2);
printf ( " address of cht = %p\n",pt3);
printf("\n Using only pointer operator :\n");
printf("----------------------------------\n");
printf ( " value at address of m = %d\n",*pt1);
printf ( " value at address of fx= %f\n",*pt2);
printf ( " value at address of cht= %c\n\n",*pt3);
}
Output:
Pointer : Demonstrate the use of & and * operator :
--------------------------------------------------------
m = 300
fx = 300.600006
cht = z

Using & operator :


-----------------------
address of m = 0x7fff71cd0b38
address of fx = 0x7fff71cd0b3c
address of cht = 0x7fff71cd0b37

Using & and * operator :


-----------------------------
value at address of m = 300
value at address of fx = 300.600006
value at address of cht = z

Using only pointer variable :


----------------------------------
address of m = 0x7fff71cd0b38
address of fx = 0x7fff71cd0b3c
address of cht = 0x7fff71cd0b37

Using only pointer operator :


----------------------------------
value at address of m = 300
value at address of fx= 300.600006
value at address of cht= z

Page | 30
Programming for Problem Solving using C
Kakinada Institute Of Technology And Science Department Of CSE
b. Write a program in c to add two numbers using pointers.

#include <stdio.h>

int main()
{
int first, second, *p, *q, sum;
printf("Enter two integers to add\n");
scanf("%d%d", &first, &second);
p = &first;
q = &second;
sum = *p + *q;
printf("Sum of the numbers = %d\n", sum);
return 0;
}

Output:-

Enter two integers to add


4
5
Sum of the numbers = 9

Page | 31
Programming for Problem Solving using C
Kakinada Institute Of Technology And Science Department Of CSE
Exercise-11
a. Write a program in c to add numbers using call by reference.

#include <stdio.h>
long addTwoNumbers(long *, long *);

int main()
{
long fno, sno, *ptr, *qtr, sum;

printf("\n\n Pointer : Add two numbers using call by reference:\n");


printf("-------------------------------------------------------\n");

printf(" Input the first number : ");


scanf("%ld", &fno);
printf(" Input the second number : ");
scanf("%ld", &sno);
sum = addTwoNumbers(&fno, &sno);
printf(" The sum of %ld and %ld is %ld\n\n", fno, sno, sum);
return 0;
}
long addTwoNumbers(long *n1, long *n2)
{
long sum;
sum = *n1 + *n2;
return sum;
}

Output:
Pointer: add two numbers using call by reference:
Input the first number: 2
Input the second number: 3
The sum of 2 and 3 is 5

Page | 32
Programming for Problem Solving using C
Kakinada Institute Of Technology And Science Department Of CSE

b. Write a program in c to find the largest elements using Dynamic memory Allocation.

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

intmain()
{
inti, num;
float*data;

printf("Enter total number of elements(1 to 100): ");


scanf("%d",&num);

// Allocates the memory for 'num' elements.


data =(float*)calloc(num,sizeof(float));

if(data == NULL)
{
printf("Error!!! memory not allocated.");
exit(0);
}

printf("\n");

// Stores the number entered by the user.


for(i=0;i< num;++i)
{
printf("Enter 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("Largest element = %.2f",*data);

Page | 33
Programming for Problem Solving using C
Kakinada Institute Of Technology And Science Department Of CSE
return0;
}
Output:

Enter total number of elements (1 to 100): 5


Enter number 1: 3
Enter number 2:9
Enter number 3:6
Enter number 4:3
Enter number 5: 18
Largest element =18.00

Page | 34
Programming for Problem Solving using C
Kakinada Institute Of Technology And Science Department Of CSE
Exercise-12
a. Write a program in c to swap elements using call by reference

#include<stdio.h>
void cyclicSwap(int *a,int *b,int *c);

int main()
{
int a, b, c;

printf("Enter a, b and c respectively: ");


scanf("%d %d %d",&a,&b,&c);
printf("Value before swapping:\n");
printf("a = %d \nb = %d \nc = %d\n",a,b,c);

cyclicSwap(&a, &b, &c);

printf("Value after swapping:\n");


printf("a = %d \nb = %d \nc = %d",a, b, c);
return 0;
}
void cyclicSwap(int *a,int *b,int *c)
{
int temp;
// swapping in cyclic order
temp = *b;
*b = *a;
*a = *c;
*c = temp;
}
Output:
enter a,b and c respectively:1 3 6
Value before swapping:
a=1
b=3
c=6
value after swapping:
a=6
b=1
c=3

Page | 35
Programming for Problem Solving using C
Kakinada Institute Of Technology And Science Department Of CSE

b. Write a c program to count number of vowels and consonants in a string using a pointer

#include <string.h>

int main()
{
char s[1000];
int i,vowels=0,consonants=0;

printf("Enter the string : ");


gets(s);

for(i=0;s[i];i++)
{
if((s[i]>=65 && s[i]<=90)|| (s[i]>=97 && s[i]<=122))
{

if(s[i]=='a'|| s[i]=='e'||s[i]=='i'||s[i]=='o'||s[i]=='u'||s[i]=='A'||s[i]=='E'||s[i]=='I'||s[i]=='O'
||s[i]=='U')
vowels++;
else
consonants++;
}

printf("vowels = %d\n",vowels);
printf("consonants = %d\n",consonants);

return 0;
}

Output:
Enter a string:aeidfg
Vowels=3
Consonents=3

Page | 36
Programming for Problem Solving using C
Kakinada Institute Of Technology And Science Department Of CSE
Exercise-13
a.Write a program in c to show how a function return in pointer?

#include <stdio.h>
int* findLarger(int*, int*);
void main()
{
int numa=0;
int numb=0;
int *result;
printf("\n\n Pointer : Show a function returning pointer :\n");
printf("--------------------------------------------------\n");
printf(" Input the first number : ");
scanf("%d", &numa);
printf(" Input the second number : ");
scanf("%d", &numb);

result=findLarger(&numa, &numb);
printf(" The number %d is larger. \n\n",*result);
}

int* findLarger(int *n1, int *n2)


{
if(*n1 > *n2)
return n1;
else
return n2;
}

Output:
Pointer : Show a function returning pointer :
--------------------------------------------------
Input the first number : 5
Input the second number : 3
The number 5 is larger.

Page | 37
Programming for Problem Solving using C
Kakinada Institute Of Technology And Science Department Of CSE

b. Write a program find sum of n elements entered by user to perform this program to
allocate memory dynamically using malloc() function?

#include <stdio.h>
#include <stdlib.h>
int main()
{

// This pointer will hold the


// base address of the block created
int* ptr;
int n, i, sum = 0;

// Get the number of elements for the array


n = 5;
printf("Enter number of elements: %d\n", n);

// Dynamically allocate memory using malloc()


ptr = (int*)malloc(n * sizeof(int));

// Check if the memory has been successfully


// allocated by malloc or not
if (ptr == NULL) {
printf("Memory not allocated.\n");
exit(0);
}
else {
// Memory has been successfully allocated
printf("Memory successfully allocated using malloc.\n");
// Get the elements of the array
for (i = 0; i < n; ++i) {
ptr[i] = i + 1;
}
// Print the elements of the array
printf("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
}
return 0;

Page | 38
Programming for Problem Solving using C
Kakinada Institute Of Technology And Science Department Of CSE
}

Output:

Enter number of elements: 5


Memory successfully allocated using malloc.

The elements of the array are: 1, 2, 3, 4, 5,

Page | 39
Programming for Problem Solving using C
Kakinada Institute Of Technology And Science Department Of CSE
Exercise-14
a. Write a program in c to convert decimal number to binary number using the function

#include<stdio.h>
#include<stdlib.h>
int main(){
int a[10],n,i;
system ("cls");
printf("Enter the number to convert: ");
scanf("%d",&n);
for(i=0;n>0;i++)
{
a[i]=n%2;
n=n/2;
}
printf("\nBinary of Given Number is=");
for(i=i-1;i>=0;i--)
{
printf("%d",a[i]);
}
return 0;
}

Output:
Enter the number to convert: 5

Binary of Given Number is=101

Page | 40
Programming for Problem Solving using C
Kakinada Institute Of Technology And Science Department Of CSE
b. Write a c program to find sum of n elements entered by user . to perform this program
allocate memory dynamically using calloc () function . Understand the difference b/w the
above two programs

#include<stdio.h>

#include<stdlib.h>
int main(){
int n,i,*ptr,sum=0;
printf("Enter number of elements: ");
scanf("%d",&n);
ptr=(int*)calloc(n,sizeof(int)); //memory allocated using calloc
if(ptr==NULL)
{
printf("Sorry! unable to allocate memory");
exit(0);
}
printf("Enter elements of array: ");
for(i=0;i<n;++i)
{
scanf("%d",ptr+i);
sum+=*(ptr+i);
}
printf("Sum=%d",sum);
free(ptr);
return 0;
}

Output:

Enter number of elements: 3


Enter elements of array: 20 6 33
Sum=59

Page | 41
Programming for Problem Solving using C
Kakinada Institute Of Technology And Science Department Of CSE
Exercise-15
a. Write a c programming to check whether a number is a prime number or not using the
function

#include<stdio.h>
int check_prime(int);
main()
{
int n, result;
printf("Enter an integer to check whether it is prime or not.\n");
scanf("%d",&n);
result = check_prime(n);
if ( result == 1 )
printf("%d is prime.\n", n);
else
printf("%d is not prime.\n", n);
return 0;
}

int check_prime(int a)
{
int c;
for ( c = 2 ; c <= a - 1 ; c++ )
{
if ( a%c == 0 )
return 0;
}
return 1;
}

Output:

Enter an integer to check whether it is prime or not.


6
6 is not prime.

Enter an integer to check whether it is prime or not.


7
7 is prime.

Page | 42
Programming for Problem Solving using C
Kakinada Institute Of Technology And Science Department Of CSE

b. Write a program in c to get the largest element of an array using the function

#include <stdio.h>

int main()
{
int array[100], maximum, size, c, location = 1;

printf("Enter the number of elements in array\n");


scanf("%d", &size);

printf("Enter %d integers\n", size);

for (c = 0; c < size; c++)


scanf("%d", &array[c]);

maximum = array[0];

for (c = 1; c < size; c++)


{
if (array[c] > maximum)
{
maximum = array[c];
location = c+1;
}
}

printf("Maximum element is present at location %d and it's value is %d.\n", location,


maximum);
return 0;
}

Output:
Enter the number of elements in array
4
Enter 4 integers
10 11 12 13
Maximum element is present at location 4 and its value is 13.

Page | 43
Programming for Problem Solving using C
Kakinada Institute Of Technology And Science Department Of CSE
Exercise-16
a. Write a program in C 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("\n\n Append multiple lines at the end of a text file :\n");


printf("------------------------------------------------------\n");
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);
}
Page | 44
Programming for Problem Solving using C
Kakinada Institute Of Technology And Science Department Of CSE
printf("\n\n");
fclose (fptr);
//------- End of reading ------------------
return 0;
}

Output:
Append multiple lines at the end of a text file :
------------------------------------------------------
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

Page | 45
Programming for Problem Solving using C
Kakinada Institute Of Technology And Science Department Of CSE

b. Write a program in C 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("\n\n Copy a file in another name :\n");


printf("----------------------------------\n");

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);

Page | 46
Programming for Problem Solving using C
Kakinada Institute Of Technology And Science Department Of CSE
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:
Copy a file in another name :
----------------------------------
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.

Page | 47
Programming for Problem Solving using C
Kakinada Institute Of Technology And Science Department Of CSE
c. Write a program in C to remove a file from the disk.

/*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>

void main()
{
int status;
char fname[20];
printf("\n\n Remove a file from the disk :\n");
printf("----------------------------------\n");
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:
Remove a file from the disk :
----------------------------------
Input the name of file to delete : test.txt
The file test.txt is deleted successfully..!!

Page | 48
Programming for Problem Solving using C

You might also like