0% found this document useful (0 votes)
376 views136 pages

PPS Lab Manual

The document provides information about Keshav Memorial Institute of Technology (KMIT), including its vision, mission, and details about the Computer Science and Engineering department. KMIT aims to produce highly skilled engineers through hands-on learning and industry collaboration. The Computer Science department seeks to provide quality education and research opportunities to help students become successful professionals through lifelong learning.

Uploaded by

sandeep bhukya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
376 views136 pages

PPS Lab Manual

The document provides information about Keshav Memorial Institute of Technology (KMIT), including its vision, mission, and details about the Computer Science and Engineering department. KMIT aims to produce highly skilled engineers through hands-on learning and industry collaboration. The Computer Science department seeks to provide quality education and research opportunities to help students become successful professionals through lifelong learning.

Uploaded by

sandeep bhukya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 136

KESHAV MEMORIAL INSTITUTE OF

TECHNOLOGY
(KMIT)
(Approved by AICTE, New Delhi and Affiliated to JNTUH)
Narayanaguda, Hyderabad – 500029

(Autonomous)

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


LAB MANUAL
PROGRAMMING FOR PROBLEM SOLVING LAB
B.Tech I YEAR I SEM (KR21 REGULATIONS)
ACADEMIC YEAR 2021-22
INDEX

S.NO TOPIC

I List of Experiments

II V/M /POs/PSOs/PEOs

IV Course Objectives & Course Outcomes


List of Experiments
1. Write a simple program that prints the results of all the operators available in C
(including pre/ post increment, bitwise and/or/not, etc.). Read required operand
values from standard input.
2. Write a simple program that converts one given data type to another using auto
conversion and casting. Take the values from standard input.
3. Write a program for finding the max and min from the three numbers.
4. Write the program for the simple, compound interest.
5. Write program that declares Class awarded for a given percentage of marks,
where mark <40%= Failed, 40% to <60% = Second class, 60% to <70%=First
class, >= 70% = Distinction. Read percentage from standard input.
6. Write a C program to find the roots of a Quadratic equation.
7. Write a C program, which takes two integer operands and one operator from the
user, performs the operation and then prints the result. (Consider the operators
+,-,*, /, % and use Switch Statement)
8. Write a program that prints a multiplication table for a given number and the
number of rows in the table. For example, for a number 5 and rows = 3, the output
should be:
5x1=5
5 x 2 = 10
5 x 3 = 15
9. Write a program that finds if a given number is a prime number
10. Write a C program to find the sum of individual digits of a positive integer and
test given number is palindrome.
11. A Fibonacci sequence is defined as follows: the first and second terms in the
sequence are 0 and 1. Subsequent terms are found by adding the preceding two
terms in the sequence. Write a C program to generate the first n terms of the
sequence.
12. Write a program that shows the binary equivalent of a given positive number
between 0 to 255.
13. Write a C program to generate all the prime numbers between 1 and n, where n
is a value supplied by the user.
14. Write a C program to calculate the following, where x is a fractional value.
1-x/2 +x^2/4-x^3/6
15. Write a C program to read in two numbers, x and n, and then compute the sum
of this geometric progression: 1+x+x^2+x^3+………….+x^n.
For example: if n is 3 and x is 5, then the program computes 1+5+25+125.
16. Write a C program to construct a pyramid of numbers as follows:
1
12
123
17.Write a C program to construct a pyramid of numbers as follows:
*
**
***
18.Write a C program to construct a pyramid of numbers as follows:
1
23
456
19.Write a C program to construct a pyramid of numbers as follows:
1
22
333
4444
20.Write a C program to construct a pyramid of numbers as follows:
*
**
***
**
*
21. Write a C program to find the minimum, maximum and average in an array of
integers.
22. Write a C program to compute mean, variance, Standard Deviation, sorting of n
elements in a single dimension array.
23. Write a program for reading elements using pointer into array and display the
values using array.
24. Write a program for display values reverse order from array using pointer.
25. Write a program through a pointer variable to find sum of n elements from the
array.
26. Write a C program to convert a Roman numeral ranging from I to L to its
decimal equivalent.
27. Write a C program that converts a number ranging from 1 to 50 to Roman
equivalent
28. Write a C program that uses functions to perform the following operations:
i.To insert a sub-string into a given main string from a given position.
ii. To delete n Characters from a given position in a given string.
29. Write a C program to determine if the given string is a palindrome or not
(Spelled same in both directions with or without a meaning like madam, civic,
noon, abcba, etc.)
30. Write a C program that displays the position of a character ch in the string S or
– 1 if S doesn‘t contain ch.
31. Write a C program to count the lines, words and characters in a given text.
32. Write a menu driven C program that allows a user to enter n numbers and then
choose between finding the smallest, largest, sum, or average. The menu and all
the choices are to be functions. Use a switch statement to determine what action to
take. Display an error message if an invalid choice is entered.
33. Write a C program that uses functions to perform the following:
i. Addition of Two Matrices
ii. Multiplication of Two Matrices
iii. Transpose of a matrix with memory dynamically allocated for the new
matrix as row and column counts may not be the same.
34. Write C program that use both recursive and non-recursive functions to find the
factorial of a given integer.
35. Write C program that use both recursive and non-recursive functions to find
the GCD (greatest common divisor) of two given integers.
36. Write C programs that use both recursive and non-recursive functions to find
x^n
37. Write a C program to solve the towers of hanoi problem using a recursion
process.
38. Write a C program to display the contents of a file to a standard output device.
39. Write a C program which copies one file to another, replacing all lowercase
characters with their uppercase equivalents.
40. Write a C program to count the number of times a character occurs in a text
file. The file name and the character are supplied as command line arguments.
41. Write a C program that does the following:
It should first create a binary file and store 10 integers, where the file name and 10
values are given in the command line. (hint: convert the strings using atoi function)
Now the program asks for an index and a value from the user and the value at that
index should be changed to the new value in the file. (hint: use fseek function)
The program should then read all 10 values and print them back.
42. Write a C program to merge two files into a third file (i.e., the contents of the
firs t file followed by those of the second are put in the third file).
43. Write a program to count the number of characters, words and lines of a given
text file.
44.Write a C program to store students' information (id, name, address, marks) into
a file and print the information from the file.
45. Write a C program that uses a non recursive function to search for a Key value
in a given list of integers using linear search method.
46. Write a C program that uses a non recursive function to search for a Key value
in a given sorted list of integers using binary search method.
47. Write a C program that implements the Bubble sort method to sort a given list
of integers in ascending order.
48. Write a C program that sorts the given array of integers using selection sort in
descending order
49. Write a C program that sorts the given array of integers using insertion sort in
ascending order
50. Write a C program that sorts the given array of integers using quick sort in
ascending order
51. Write a C program that sorts the given array of integers using merge sort in
ascending order
52. Write a C program to implement single linked list with the following
operations
a) create b) insert at a position c) delete by value d) delete by position e) reverse
f) sort g) display
53. Write a C program to implement stack using
a) arrays b) linked lists
54. Write a C program to implement queues using
a) arrays b) linked lists
55. Write a C program to perform the following operations using stack
a) conversion of an infix to postfix expression
b) evaluation of postfix expression.
KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY
(Approved by AICTE & Govt of T.S and Affiliated to JNTUH)

3-5-1026, Narayanaguda, Hyderabad-29. Ph: 040-23261407

Department Of Computer Science & Engineering


Vision of the Institution:

To be the fountain head of latest technologies, producing highly skilled, globally competent
engineers.

Mission of the Institution:

● To provide a learning environment that inculcates problem solving skills, professional,


ethical responsibilities, lifelong learning through multi modal platforms and prepare students
to become successful professionals.

● To establish Industry Institute Interaction to make students ready for the industry.

● To provide exposure to students on latest hardware and software tools.

● To promote research based projects/activities in the emerging areas of technology


convergence.

● To encourage and enable students to not merely seek jobs from the industry but also to create
new enterprises

● To induce a spirit of nationalism which will enable the student to develop, understand India’s
challenges and to encourage them to develop effective solutions.

● To support the faculty to accelerate their learning curve to deliver excellent service to
students
KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY
(Approved by AICTE & Govt of T.S and Affiliated to JNTUH)

3-5-1026, Narayanaguda, Hyderabad-29. Ph: 040-23261407

Department Of Computer Science & Engineering

Vision & Mission of Department


Vision of the Department:

To be among the region's premier teaching and research Computer Science and Engineering
departments producing globally competent and socially responsible graduates in the most
conducive academic environment.

Mission of the Department:

● To provide faculty with state of the art facilities for continuous professional development and
research, both in foundational aspects and of relevance to emerging computing trends.
● To impart skills that transform students to develop technical solutions for societal needs and
inculcate entrepreneurial talents.
● To inculcate an ability in students to pursue the advancement of knowledge in various
specializations of Computer Science and Engineering and make them industry-ready.
● To engage in collaborative research with academia and industry and generate adequate
resources for research activities for seamless transfer of knowledge resulting in sponsored
projects and consultancy.
● To cultivate responsibility through sharing of knowledge and innovative computing solutions
that benefits the society-at-large.
● To collaborate with academia, industry and community to set high standards in academic
excellence and in fulfilling societal responsibilities.
KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY
(Approved by AICTE & Govt of T.S and Affiliated to JNTUH)
3-5-1026, Narayanaguda, Hyderabad-29. Ph: 040-23261407

PROGRAM OUTCOMES (POs)

1. Engineering Knowledge: Apply the knowledge of mathematics, science, engineering


fundamentals, and an engineering specialization to the solution of complex engineering
problems.
2. Problem Analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of
mathematics, natural sciences, and engineering sciences.
3. Design/Development of Solutions: Design solutions for complex engineering problems and
design system components or processes that meet the specified needs with appropriate
consideration for the public health and safety, and the cultural, societal, and environmental
considerations.
4. Conduct Investigations of Complex Problems: Use research-based knowledge and research
methods including design of experiments, analysis and interpretation of data, and synthesis of
the information to provide valid conclusions.
5. Modern Tool Usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modelling to complex engineering
activities with an understanding of the limitations.
6. The Engineer and Society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to
the professional engineering practice.
7. Environment and Sustainability: Understand the impact of the professional engineering
solutions in societal and environmental contexts, and demonstrate the knowledge of, and need
for sustainable development.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.
9. Individual and Team Work: Function effectively as an individual, and as a member or
leader in diverse teams, and in multidisciplinary settings.
10. Communication: Communicate effectively on complex engineering activities with the
engineering community and with society at large, such as, being able to comprehend and
write effective reports and design documentation, make effective presentations, and give and
receive clear instructions.
11. Project Management and Finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a member and
leader in a team, to manage projects and in multidisciplinary environments.
12. Life-long Learning: Recognize the need for, and have the preparation and ability to engage
in independent and life-long learning in the broadest context of technological change.
KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY
(Approved by AICTE & Govt of T.S and Affiliated to JNTUH)
3-5-1026, Narayanaguda, Hyderabad-29. Ph: 040-23261407

Department of Computer Science & Engineering

PROGRAM SPECIFIC OUTCOMES (PSOs)


PSO1: An ability to analyze the common business functions to design and develop appropriate
Computer Science solutions for social upliftments.

PSO2: Shall have expertise on the evolving technologies like Python, Machine Learning, Deep
Learning, Internet of Things (IOT), Data Science, Full stack development, Social Networks,
Cyber Security, Big Data, Mobile Apps, CRM, ERP etc.
KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY
(Approved by AICTE & Govt of T.S and Affiliated to JNTUH)
3-5-1026, Narayanaguda, Hyderabad-29. Ph: 040-23261407

Department of Computer Science & Engineering

PROGRAM EDUCATIONAL OBJECTIVES (PEOs)


PEO1: Graduates will have successful careers in computer related engineering fields or will be
able to successfully pursue advanced higher education degrees.

PEO2: Graduates will try and provide solutions to challenging problems in their profession by
applying computer engineering principles.

PEO3: Graduates will engage in life-long learning and professional development by rapidly


adapting changing work environment.

PEO4: Graduates will communicate effectively, work collaboratively and exhibit high levels of
professionalism and ethical responsibility.
KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY
(Approved by AICTE & Govt of T.S and Affiliated to JNTUH)
3-5-1026, Narayanaguda, Hyderabad-29. Ph: 040-23261407

Department of Computer Science & Engineering


Course Objectives: To learn
● Demonstrate an understanding of computer programming language concepts.
● Ability to design and develop Computer programs, analyzes, and interprets the concept of
pointers, declarations, initialization, operations on pointers and their usage.
● To study the representation, implementation and applications of linear and nonlinear data
structures.
● Analyze various searching and sorting techniques and its applications.

Course Outcomes: After learning the contents of this course the student is able to
● Choose the appropriate data structure for modeling a given problem.
● Implement operations like searching, insertion, and deletion, traversing mechanism on various
data structures.
● Students will be able to implement Linear and Non-Linear data structures.
● Implement appropriate sorting/searching technique for given problem.

CO VS PO MAPPING:
CO PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12

CO1 3 3 3 3 2 2 2

PPS lab CO2 3 3 3 3 3 3 2

CO3 3 3 3 3 3 2

CO4 3 3 3 3 3 2
1. Write a simple program that prints the results of all the operators available in C
(including pre/ post increment, bitwise and/or/not, etc.). Read required operand
values from standard input.
#include<stdio.h>

void main( )

int a,b,min,n1,n2,n3,n4;

printf("Enter a and b values:");

scanf("%d %d",&a,&b);

min=a<b?a:b;

printf("Minimum of given values using Ternary Operator is %d\n",min);

printf("Arithmetic operators result:\n");

printf("a+b -> %d a-b -> %d a*b -> %d a/b -> %d a mod b -> %d\n", a+b,a-
b,a*b,a/b,a%b);

printf("Relational operators result:\n");

printf("a>b -> %d a<b -> %d a>=b -> %d a<=b -> %d a==b -> %d a!=b -> %d\
n", a>b,a<b,a>=b,a<=b,a==b,a!=b);

printf("Logical operators result:\n");

printf("a&&b -> %d a||b -> %d !(a==b) -> %d\n", a&&b,a||b,!(a==b));

printf("Bitwise operators result:\n");

printf("a&b -> %d a|b -> %d a^b -> %d a<<2 -> %d b>>3 -> %d\n",a&b,a|
b,a^b,a<<2,b>>3);

printf("Unary operator result:\n");

n1=a++;
n2=++a;

n3=b--;

n4=--b;

printf("a++ -> %d ++a -> %d b-- -> %d --b -> %d\n",n1,n2,n3,n4);

printf("Size of integer variable is %lu", sizeof(a));

Output:

Enter a and b values:25 16

Minimum of given values using Ternary Operator is 16

Arithmetic operators result:

a+b -> 41 a-b -> 9 a*b -> 400 a/b -> 1 a mod b -> 9

Relational operators result:

a>b -> 1 a<b -> 0 a>=b -> 1 a<=b -> 0 a==b -> 0 a!=b -> 1

Logical operators result:

a&&b -> 1 a||b -> 1 !(a==b) -> 1

Bitwise operators result:

a&b -> 16 a|b -> 25 a^b -> 9 a<<2 -> 100 b>>3 -> 2

Unary operator result:

a++ -> 25 ++a -> 27 b-- -> 16 --b -> 14

Size of integer variable is 4


2. Write a simple program that converts one given data type to another using auto
conversion and casting. Take the values from standard input.

#include<stdio.h>

int main()

int sub1, sub2, sub3;

float average;

printf("Enter the marks of 3 subjects: ");

scanf("%d %d %d",&sub1,&sub2,&sub3);

average = ((sub1 + sub2 + sub3) / 3); //implicit typecasting

printf("\nAverage of marks using implicit typecasting = %f",average);

average = (float)(sub1 + sub2 + sub3) / 3; //explicit typecasting

printf("\nAverage of marks using explicit typecasting = %f",average);

return 0;

Output:

Enter the marks of 3 subjects: 20 30 45

Average of marks using implicit typecasting = 31.000000

Average of marks using explicit typecasting = 31.6666


3. Write a program for finding the max and min from the three numbers.
#include<stdio.h>
void main()
{
int a,b,c;
printf("Enter the values of a,b,c: ");
scanf("%d %d %d",&a, &b, &c);
if (a<b && a<c)
printf("\n Minimum is %d ",a);
else if(b<a && b<c)
printf("\n Minimum is %d ",b);
else
printf("\n Minimum is %d ",c);

if (a>b && a>c)


printf("\n Maximum is %d ",a);
else if(b>a && b>c)
printf("\n Maximum is %d ",b);
else
printf("\n Maximum is %d ",c);
}
Output:

Enter the values of a,b,c: 5 2 1

Minimum is 1
Maximum is 5
4. Write the program for the simple, compound interest.
#include<stdio.h>

#include<math.h>

int main()

float p, t, r, si, ci;

printf("Enter principal amount (p): ");

scanf("%f", &p);

printf("Enter time in year (t): ");

scanf("%f", &t);

printf("Enter rate in percent (r): ");

scanf("%f", &r);

/* Calculating simple interest */

si = (p * t * r)/100.0;

/* Calculating compound interest */

ci = p * (pow(1+r/100, t) - 1);

printf("Simple Interest = %0.3f\n", si);

printf("Compound Interest = %0.3f", ci);

return(0);

Output:

Enter principal amount (p): 30000


Enter time in year (t): 5
Enter rate in percent (r): 20
Simple Interest = 30000.000
Compound Interest = 44649.613
5. Write program that declares Class awarded for a given percentage of marks,
where mark <40%= Failed, 40% to <60% = Second class, 60% to <70%=First
class, >= 70% = Distinction. Read percentage from standard input.
#include<stdio.h>

void main()

float percentage;

printf("Enter percentage: ");

scanf("%f", &percentage);

if(percentage >= 70)

printf("Distinction");

else if(percentage<40 )

printf("Failed");

else if(percentage< 60 && percentage>=40)

printf("Second Class");

else if(percentage<70 && percentage>=60)

{
printf("First Class");

Output:

Enter percentage: 78

Distinction
6. Write a C program to find the roots of a Quadratic equation

#include <stdio.h>

#include <math.h>

int main()

double x,a, b, c, discriminant, root1, root2, realPart, imaginaryPart;

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

scanf("%lf %lf %lf",&a, &b, &c);

discriminant = b*b-4*a*c;

// condition for real and different roots

if(a==0&&b==0&&c==0)

printf("Invalid coefficients\nEnter valid inputs\n");

else if(a==0){

x=(float)-c/b;

printf("Linear equation\nRoot = %lf\n",x);

else if (discriminant > 0)

// sqrt() function returns square root

root1 = (-b+sqrt(discriminant))/(2*a);

root2 = (-b-sqrt(discriminant))/(2*a);

printf("The roots are real and distinct\nroot1 = %f and root2 = %f\n",root1 ,


root2);
}

//condition for real and equal roots

else if (discriminant == 0)

root1 = root2 = -b/(2*a);

printf("The roots are real and equal\nroot1 = root2 = %lf\n", root1);

// if roots are not real

else

realPart = -b/(2*a);

imaginaryPart = sqrt(-discriminant)/(2*a);

printf("The roots are real and imaginary\nroot1 = %lf+i%lf\nroot2 = %f-i%f\


n", realPart, imaginaryPart, realPart, imaginaryPart);

return 0;

Output:

Enter coefficients a, b and c : 1 6 9

The roots are real and equal

root1 = root2 = -3.000000


7. Write a C program, which takes two integer operands and one operator from the
user, performs the operation and then prints the result. (Consider the operators
+,-,*, /, % and use Switch Statement)
#include <stdio.h>

void main()

int a, b, c;

char ch;

printf("Enter your operator(+,-,/,*,%%):");

scanf("%c", &ch);

printf("Enter the values of a and b: ");

scanf("%d %d", &a, &b);

switch(ch)

case '+': c = a + b;

printf("Sum is %d", c);

break;

case '-': c = a - b;

printf("Difference is %d", c);

break;

case '*': c = a * b;

printf("Product is %d", c);


break;

case '/': c = a / b;

printf("Quotient is %d", c);

break;

case '%': c = a % b;

printf("Remainder is %d", c);

break;

default: printf("Invalid operator");

break;

Output:

Enter your operator(+,-,/,*,%):/

Enter the values of a and b: 40 4

Quotient is 10
8. Write a program that prints a multiplication table for a given number and the
number of rows in the table. For example, for a number 5 and rows = 3, the output
should be:

5x1=5
5 x 2 = 10
5 x 3 = 15
#include <stdio.h>
int main()
{
int number, r,i=1;
printf("Enter the Number:");
scanf("%d", &number);
printf("Enter the number of rows in the table:");
scanf("%d",&r);
while (i <= r)
{
printf("%d x %d = %d\n", number, i, number * i);
i++;
}
return 0;
}
Output:
Enter the Number:18
Enter the number of rows in the table:3
18 x 1 = 18
18 x 2 = 36
18 x 3 = 54
9. Write a program that finds if a given number is a prime number
#include<stdio.h>

int main() {

int n, i, count = 0;

printf("Enter any integer: ");

scanf("%d", &n);

for (i = 1; i <= n ; ++i) {

if (n % i == 0) {

count++;

if (count ==2) {

printf("\nThe given number %d is a prime number.",n);

else {

printf("\nThe given number %d is not a prime number.", n);

return 0;

Output:

Enter any integer: 41


The given number 41 is a prime number.
10. Write a C program to find the sum of individual digits of a positive integer and
test given number is palindrome.
#include<stdio.h>
int main()
{
int n,r,sum=0,temp,rev=0;
printf(" Enter any positive integer : ");
scanf("%d",&n);
printf("\n The given number is : %d",n);
temp=n;
while(n>0)
{
r=n%10;
sum=r+sum;
rev=(rev*10)+r;
n=n/10;
}
printf("\n The sum of individual digits of a given positive integer is : %d",sum);
if(temp==rev)
printf("\n The given integer %d is a palindrome.",temp);
else
printf("\n The given integer %d is not a palindrome.",temp);
return 0;
}
Output:

Enter any positive integer : 151

The given number is : 151


The sum of individual digits of a given positive integer is : 7

The given integer 151 is a palindrome.


11. A Fibonacci sequence is defined as follows: the first and second terms in the
sequence are 0 and 1. Subsequent terms are found by adding the preceding two
terms in the sequence. Write a C program to generate the first n terms of the
sequence.
#include<stdio.h>
void main()
{
int a = 0, b = 1, lengthOfSeries = 0, counter, sum = 0;
printf("Enter the number of terms : ");
scanf("%d", &lengthOfSeries);
printf("\nThe first %d terms of the Fibonacci sequence is : ",lengthOfSeries);
printf("\n\n%d %d", a, b);
for(counter = 2; counter < lengthOfSeries; counter++)
{
sum = a + b;
printf(" %d",sum);
a = b;
b = sum;
}
}
Output:

Enter the number of terms : 8

The first 8 terms of the Fibonacci sequence is :

0 1 1 2 3 5 8 13
12. Write a program that shows the binary equivalent of a given positive number
between 0 to 255.
#include <stdio.h>

int main()

int num,num2, temp=1,rem;

long bin=0;

printf("Enter any positive integer: ");

scanf("%d", &num);

if(num>=0)

num2=num;

while (num!=0)

rem = num%2;

num = num / 2;

bin = bin + rem*temp;

temp = temp * 10;

printf("\nThe binary equivalent of a given positive number %d is %ld", num2,


bin);

else
{

printf("\nInvalid input! Enter any positive number.");

Output:

Enter any positive integer: 113

The binary equivalent of a given positive number 113 is 1110001


13. Write a C program to generate all the prime numbers between 1 and n, where n
is a value supplied by the user.
#include<stdio.h>
void main()
{
int i,j,n;
printf("Enter the number: ");
scanf("%d",&n);
printf("\nPrime numbers between 1 and %d are:\n",n);
for(i=2;i<=n;i++)
{
int c=0;
for(j=1;j<=i;j++)
{
if(i%j==0)
{
c++;
}
}
if(c==2)
{
printf("%d ",i);
}
}
}
Output:

Enter the number: 17


Prime numbers between 1 and 17 are:

2 3 5 7 11 13
14. Write a C program to calculate the following, where x is a fractional value.
1-x/2 +x^2/4-x^3/6
#include <stdio.h>
#include <math.h>

void main()
{
int counter,i;
float sum=1,x,power,fact;

printf("\n EQUATION SERIES : 1 - x/2 + x^2/4 - x^3/6 ");

printf("\n ENTER VALUE OF x : ");


scanf("%f",&x);

for(counter=1, power=1,i=2; power<=3; counter++,power=power+1,i+=2)


{
//The main equation for sum of series is...
sum=sum+(pow(-1,counter)*(pow(x,power)/i));
}
printf(" Sum of Series is : %f",sum);

}
Output:

EQUATION SERIES : 1 - x/2 + x^2/4 - x^3/6

ENTER VALUE OF x : 15
Sum of Series is : -512.750000
15. Write a C program to read in two numbers, x and n, and then compute the sum
of this geometric progression: 1+x+x^2+x^3+………….+x^n.
example: if n is 3 and x is 5, then the program computes 1+5+25+125.
#include<stdio.h>
#include<math.h>
void main(){
int x,n,sum=1,i;
printf("Enter x and n values : ");
scanf("%d %d",&x,&n);
for(i=1;i<=n;i++)
sum+=pow(x,i);
printf("\nSum of Geometric Progression is: %d",sum);
}
Output:

Enter x and n values : 30 3

Sum of Geometric Progression is: 27931


16. Write a C program to construct a pyramid of numbers as follows:
1
12
123
#include<stdio.h>

int main()

int i,j,n;

printf("Enter no of rows: ");

scanf("%d",&n);

for(i=1;i<=n;i++)

for(j=1;j<=i;j++)

printf("%d ",j);

printf("\n");

return 0;

Output:

Enter no of rows: 4
1
12
123
1234
17. Write a C program to construct a pyramid of numbers as follows:
*
**
***
#include<stdio.h>
int main()
{
int i,j,n;
printf("Enter no of rows: ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=i;j++)
{
printf("* ");
}
printf("\n");
}
return 0;
}
Output:
Enter no of rows: 4
*
**
***
****
18. Write a C program to construct a pyramid of numbers as follows:
1
23
456
#include<stdio.h>
int main()
{
int i,j,n,k=1;
printf("Enter no of rows: ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=i;j++,k++)
{
printf("%d ",k);
}
printf("\n");
}
return 0;
}
Output:
Enter no of rows: 4
1
23
456
7 8 9 10
19. Write a C program to construct a pyramid of numbers as follows:
1
22
333
4444
#include<stdio.h>
int main()
{
int i,j,n;
printf("Enter no of rows: ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=i;j++)
{
printf("%d ",i);
}
printf("\n");
}
return 0;
}
Output:
Enter no of rows: 4

22

333
4444
20.Write a C program to construct a pyramid of numbers as follows:
*
**
***
**
*
#include <stdio.h>
int main()
{
int i, j, rows;
printf("Enter number of rows: ");
scanf("%d",&rows);
for(i=1; i<=rows; ++i)
{
for(j=1; j<=i; ++j)
{
printf("* ");
}
printf("\n");
}
for(i=rows-1; i>=1; --i)
{
for(j=1; j<=i; ++j)
{
printf("* ");
}
printf("\n");
}
return 0;
}

Output:
Enter number of rows: 4

**

***

****

***

**

*
21. Write a C program to find the minimum, maximum and average in an array of
integers.

#include <stdio.h>
int main()
{
int a[50],i,n,sum,min,max;
float avg;

printf("Enter size of the array : ");


scanf("%d",&n);

printf("Enter elements in array : ");


for(i=0; i<n; i++)
{
scanf("%d",&a[i]);
}

sum=min=max=a[0];
for(i=1; i<n; i++)
{
sum+=a[i];
if(min>a[i])
min=a[i];
if(max<a[i])
max=a[i];
}
avg=(float)sum/n;
printf("Minimum in an array of given integers : %d",min);
printf("\nMaximum in an array of given integers : %d",max);
printf("\nAverage in an array of given integers : %.2f",avg);

return 0;
}

Output:
Enter size of the array : 8

Enter elements in array : 4 6 1 8 3 9 3 10

Minimum in an array of given integers : 1

Maximum in an array of given integers : 10

Average in an array of given integers : 5.50


22. Write a C program to compute mean, variance, Standard Deviation, sorting of n
elements in a single dimension array.
#include<stdio.h>
#include<math.h>
int main()
{
int i,n;
float std_dev,sum=0,sumsqr=0,mean,value,variance=0.0,a[100];
printf("Enter value of n : ");
scanf("%d",&n);
printf("Enter array elements : ");
for(i=0;i<n;i++)
{
scanf("%f",&a[i]);
sum=sum+a[i];
}
mean=sum/n;
sumsqr=0;
for(i=0;i<n;i++)
{
value=a[i]-mean;
sumsqr=sumsqr+value*value;
}
variance=sumsqr/n;
std_dev=sqrt(variance);
printf("Mean of %d numbers = %f\n",n,mean);
printf("Variance of %d numbers = %f\n",n,variance);
printf("Standard deviation of %d numbers = %f\n",n,std_dev);
return 0;
}
Output:
Enter value of n : 4
Enter array elements : 5 3 2 4
Mean of 4 numbers = 3.500000
Variance of 4 numbers = 1.250000
Standard deviation of 4 numbers = 1.118034
23. Write a program for reading elements using pointer into array and display the
values using array.
#include<stdio.h>
void main()
{
int a[10],n,i,*p;
p=a;
printf("Enter array size : ");
scanf("%d",&n);
printf("Enter array elements : ");
for(i=0;i<n;i++)
scanf("%d",p+i);

printf("Given array elements are : ");


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

}
Output:
Enter array size : 5
Enter array elements : 4 2 7 1 3
Given array elements are : 4 2 7 1 3
24. Write a program for display values reverse order from array using pointer.

#include<stdio.h>
void main()
{
int a[10],n,i,*p;
printf("Enter array size : ");
scanf("%d",&n);
p=&a[n-1];
printf("Enter array elements : ");
for(i=0;i<n;i++)
scanf("%d",&a[i]);

printf("The reverse order of the given array elements : ");


for(i=0;i<n;i++)
printf("%d ",*p--);

}
Output:
Enter array size : 5
Enter array elements : 5 3 2 8 1
The reverse order of the given array elements : 1 8 2 3 5
25. Write a program through a pointer variable to find sum of n elements from the
array.

#include <stdio.h>
void main()
{
int i,a[20], n, sum = 0;
int *p;
p=a;
printf("Enter the size of array : ");
scanf("%d",&n);

printf("Enter Elements of array : ");


for (i = 0; i < n; i++)
{
scanf("%d",&a[i]);
}

/* Compute the sum of all elements in the given array */

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


{
sum = sum + *(p + i);
/* this *(p+i) is used to access the value stored at the address*/
}

printf("Sum of array elements = %d", sum);


}
Output:
Enter the size of array : 5
Enter Elements of array : 4 3 5 2 1
Sum of array elements = 15
26. Write a C program to convert a Roman numeral ranging from I to L to its
decimal equivalent.
#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <stdlib.h>
void main()
{
char rom[30];
int a[30], l, i, k, dec;
clrscr();
printf("Enter the roman number\n");
scanf("%s", &rom);
l =strlen(rom);
for(i = 0; i < l; i++)
{
switch (rom[i])
{
case 'I': a[i] = 1;
break;
case 'V': a[i] = 5;
break;
case 'X': a[i] = 10;
break;
case 'L': a[i] = 50;
break;
case 'C': a[i] = 100;
break;
case 'D': dec = dec + 500;
break;
case 'M': a[i] = 1000;
break;
default : printf("Invalid choice");
break;
}
}
k = a[l - 1];
for(i = l - 1; i > 0; i--)
{
if(a[i] > a[i - 1])
{
k = k - a[i - 1];
}
if(a[i] <= a[i - 1])
{
k = k + a[i - 1];
}
}
printf("decimal equivalent is %d", k);
getch();
}
27. Write a C program that converts a number ranging from 1 to 50 to Roman
equivalent
#include <stdio.h>
int main(void)
{
int num, rem;
printf("Enter a number less than 50: ");
scanf("%d", &num);
printf("Roman numerals: ");
while(num != 0)
{
if (num >= 40) // 40 - xl
{
printf("xl");
num -= 40;
}
else if (num >= 10) // 10 - x
{
printf("x");
num -= 10;
}
else if (num >= 9) // 9 - ix
{
printf("ix");
num -= 9;
}
else if (num >= 5) // 5 - v
{
printf("v");
num -= 5;
}
else if (num >= 4) // 4 - iv
{
printf("iv");
num -= 4;
}
else if (num >= 1) // 1 - i
{
printf("i");
num -= 1;
}
}
return 0;
}
28. Write a C program to perform the following operations:
i.To insert a sub-string into a given main string from a given position.
ii. To delete n Characters from a given position in a given string.
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char str1[20], str2[20];
int l1, l2, n, i;
clrscr();
puts("Enter the string 1\n");
gets(str1);
l1 = strlen(str1);
puts("Enter the string 2\n");
gets(str2);
l2 = strlen(str2);
printf("Enter the position where the string is to be inserted\n");
scanf("%d", &n);
for(i = n; i < l1; i++)
{
str1[i + l2] = str1[i];
}
for(i = 0; i < l2; i++)
{
str1[n + i] = str2[i];
}
str2[l2 + 1] = '\0';
printf("After inserting the string is %s", str1);
getch();
}
Input & Output:
Enter the string 1
sachin
Enter the string 2
tendulkar
Enter the position where the string is to be inserted
4
After inserting the string is sachtendulkarin

ii) To delete n Characters from a given position in a given string.


#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char str[20];
int i, n, l, pos;
clrscr();
puts("Enter the string\n");
gets(str);
printf("Enter the position where the characters are to be deleted\n");
scanf("%d", &pos);
printf("Enter the number of characters to be deleted\n");
scanf("%d", &n);
l = strlen(str);
for(i = pos + n; i < l; i++)
{
str[i - n] = str[i];
}
str[i - n] = '\0';
printf("The string is %s", str);
getch();
}
Input & Output:
Enter the string
sachin
Enter the position where characters are to be deleted
2
Enter the number of characters to be deleted
2
The string is sai
29. Write a C program to determine if the given string is a palindrome or not
(Spelled same in both directions with or without a meaning like madam, civic,
noon, abcba, etc.)
#include<stdio.h>
#include<string.h>
void main()
{
char s[100];
int i,flag=0,l,j;
printf("Enter a string");
gets(s);
l=strlen(s);
for(i=0,j=l-1;i<=l/2;i++,j--)
{
if(s[i]!=s[j])
{
flag=1;
break;
}
}
if(flag==0)
printf("Palindrome");
else
printf("Not a Palindrome");
}
30. Write a C program that displays the position of a character ch in the string S or
– 1 if S doesn‘t contain ch.
#include<stdio.h>
#include<stdlib.h>
int main()
{
char ss[50],ch;
int cc=0,wc=1,lc=1,i;
printf("\n Enter a string");
scanf("%[^#]s",ss);
printf("Enter the character to search");
scanf(" %c",&ch);
for(i=0;ss[i]!='\0';i++)
{
if(ch==ss[i])
{
printf("Character found at %d\n",(i+1));
getch();
exit(0);
}
}
printf("Character not found -1");
}
31. Write a C program to count the lines, words and characters in a given text.
#include<stdio.h>

int main()

FILE *fp;

char ss[50],ch;

int cc=0,wc=1,lc=1,i;

printf("\n Enter a string");

scanf("%[^#]s",ss);

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

ch=ss[i];

if(ch=='\n'||ch=='\t'||ch==' ')

wc++;

if(ch=='\n')

lc++;

cc++;

printf("\nNumber of characters is %d",cc);

printf("\nNumber of words is %d",wc);

printf("\nNumber of lines is %d",lc);

}
32. Write a C program to find the minimum, maximum and average in an array of
integers.
#include <stdio.h>
int main()
{
int a[50],i,n,sum,min,max;
float avg;

printf("Enter size of the array : ");


scanf("%d",&n);

printf("Enter elements in array : ");


for(i=0; i<n; i++)
{
scanf("%d",&a[i]);
}

sum=min=max=a[0];
for(i=1; i<n; i++)
{
sum+=a[i];
if(min>a[i])
min=a[i];
if(max<a[i])
max=a[i];
}
avg=(float)sum/n;
printf("Minimum in an array of given integers : %d",min);
printf("\nMaximum in an array of given integers : %d",max);
printf("\nAverage in an array of given integers : %.2f",avg);

return 0;
}
Output:
Enter size of the array : 8

Enter elements in array : 4 6 1 8 3 9 3 10

Minimum in an array of given integers : 1

Maximum in an array of given integers : 10

Average in an array of given integers : 5.50


33. Write a C program that uses functions to perform the following:
i. Addition of Two Matrices
ii. Multiplication of Two Matrices
iii. Transpose of a matrix with memory dynamically allocated for the new
matrix as row and column counts may not be the same.
i. #include <stdio.h>
void addition(int [5][5],int [5][5],int,int);
void main()
{
int a[5][5],b[5][5],row,col,i,j;

printf("Enter number of rows :");


scanf("%d",&row);
printf("Enter number of colomns :");
scanf("%d",&col);
printf("Enter the elements of matrix a : ");
for(i = 0; i < row; i++)
{
for(j = 0; j < col; j++)
{
scanf("%d", &a[i][j]);
}
}
printf("Enter the elements of matrix b :");
for(i = 0; i < row; i++)
{
for(j = 0; j < col; j++)
{
scanf("%d", &b[i][j]);
}
}
addition(a,b,row,col);
}
void addition(int a[5][5],int b[5][5],int r,int c)
{
int i,j,res[5][5];
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
res[i][j] = (a[i][j] + b[i][j]);
}
}
printf("Addition of given matrices is : \n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf("%d ",res[i][j]);
}
printf("\n");
}
}
Output:
Enter number of rows :2
Enter number of colomns :2
Enter the elements of matrix a : 2 3 4 5
Enter the elements of matrix b :1 1 1 1
Addition of given matrices is :
34
56
ii.
#include <stdio.h>
void multiplication(int [5][5],int [5][5],int,int,int,int);
void main()
{
int a[5][5],b[5][5],r1,c1,r2,c2,i,j;

printf("Enter number of rows and cols of matrix a: ");


scanf("%d %d",&r1,&c1);
printf("Enter number of rows and cols of matrix b:");
scanf("%d %d",&r2,&c2);
if(c1==r2)
{

printf("Enter the elements of matrix a : ");


for(i = 0; i < r1; i++)
{
for(j = 0; j < c1; j++)
{
scanf("%d", &a[i][j]);
}
}
printf("Enter the elements of matrix b :");
for(i = 0; i <r2; i++)
{
for(j = 0; j < c2; j++)
{
scanf("%d", &b[i][j]);
}
}
multiplication(a,b,r1,c1,r2,c2);
}
else{
printf("Multiplication is not possible.");
}
}
void multiplication(int a[5][5],int b[5][5],int r1,int c1,int r2,int c2)
{
int i,j,k,c[5][5];
for(i = 0; i < r1; i++)
{
for(j = 0; j < c2; j++)
{
c[i][j] = 0;
for(k = 0; k < c1; k++)
{
c[i][j] = c[i][j] + (a[i][k] * b[k][j]);
}
}
}
printf("Multiplication of given matrices is : \n");
for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
{
printf("%d ",c[i][j]);
}
printf("\n");
}
}
Output:

Enter number of rows and cols of matrix a: 3 3


Enter number of rows and cols of matrix b:3 3
Enter the elements of matrix a : 5 6 7 8 9 10 3 1 2
Enter the elements of matrix b :1 2 3 4 5 6 7 8 9
Multiplication of given matrices is :
78 96 114
114 141 168
21 27 33
iii.
#include <stdio.h>
#include<stdlib.h>
void transpose(int [][10],int ,int );
int main()
{
int a[10][10],k,*ptr, 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, j);
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]);
}
printf("\n");
}
transpose(a,r,c);
return 0;
}
void transpose(int a[10][10],int r,int c)
{
int *ptr,i,j,k;
ptr=(int *)calloc(r*c,sizeof(int));
for(i=0,k=0; i<c; ++i)
for(j=0; j<r; ++j)
{
ptr[k++] = a[j][i];
}
printf("\nTranspose of Matrix:\n");
for(i=0; i<r*c; ++i)
{
printf("%d ",ptr[i]);
if((i+1)%r==0)
printf("\n");
}
free(ptr);
}
Output:
Enter rows and columns of matrix: 2 2

Enter elements of matrix:


Enter element a00: 4
Enter element a01: 3
Enter element a10: 2
Enter element a11: 5
Entered Matrix:
43
25

Transpose of Matrix:
42
35
34. Write C program that use both recursive and non-recursive functions to find the
factorial of a given integer.
#include <stdio.h>
int nonrecfactorial(int );
int recfactorial(int );
void main()
{
int n, a, b;
printf("Enter any number: ");
scanf("%d", &n);
printf("The factorial of a given number using recursion is %d \n",
recfactorial(n));
printf("The factorial of a given number using non-recursion is %d ",
nonrecfactorial(n));
}
int recfactorial(int x)
{
int f;
if(x == 0)
{
return(1);
}
else
{
f = x * recfactorial(x - 1);
return(f);
}
}
int nonrecfactorial(int x)
{
int i, f = 1;
for(i = 1;i <= x; i++)
{
f = f * i;
}
return(f);
}
Output:
Enter any number: 5
The factorial of a given number using recursion is 120
The factorial of a given number using non-recursion is 120
35. Write C program that use both recursive and non-recursive functions to find
the GCD (greatest common divisor) of two given integers.
#include <stdio.h>
int recgcd(int , int );
int nonrecgcd(int , int );

void main()
{
int a, b;

printf("Enter two numbers a, b: ");


scanf("%d%d", &a, &b);
printf("The gcd of two numbers using recursion is %d\n", recgcd(a, b));
printf("The gcd of two numbers using nonrecursion is %d", nonrecgcd(a, b));

}
int recgcd(int x, int y)
{
if(y == 0)
{
return(x);
}
else
{
return(recgcd(y, x % y));
}
}
int nonrecgcd(int x, int y)
{
int z;
while(x % y != 0)
{
z = x % y;
x = y;
y = z;
}
return(y);
}
Output:
Enter two numbers a, b: 8 12
The gcd of two numbers using recursion is 4
The gcd of two numbers using nonrecursion is 4
36. Write C programs that use both recursive and non-recursive functions to find
x^n
#include <stdio.h>
int recxpown(int , int );
int nonrecxpown(int , int );
void main()
{
int x, n;

printf("Enter x, n values : ");


scanf("%d %d", &x, &n);
printf("The %d ^ %d using recursion is %d\n", x,n,recxpown(x, n));
printf("The %d ^ %d using non-recursion is %d\n", x,n,nonrecxpown(x, n));
}
int recxpown(int x, int n)
{
if(n == 1)
{
return(x);
}
else
{
return(x*recxpown(x,n-1));
}
}
int nonrecxpown(int x, int n)
{
int i,res=1;
for(i=1;i<=n;i++)
res=res*x;
return(res);
}
Output:
Enter x, n values : 4 3
The 4 ^ 3 using recursion is 64
The 4 ^ 3 using non-recursion is 64
37. Write a C program to solve the towers of hanoi problem using a recursion
process.
#include<stdio.h>
 
void toh(int,char,char,char);
 
void main()
{
int n;
printf("How many plates?");
scanf("%d",&n);
toh(n,'A','B','C');
}
 
void toh(int n,char s,char i,char d)
{
if(n>0)
{
toh(n-1,s,d,i);
printf("\n%c -> %c",s,d);
toh(n-1,i,s,d);
}
}
38. Write a C program to display the contents of a file to a standard output device.
#include<stdio.h>

void main()

FILE *fp;

char ch;

fp=fopen("44.c","r");

if(fp==NULL)

printf("Unable to open the file\n");

exit(0);

while((ch=fgetc(fp))!=EOF)

putchar(ch);

fclose(fp);

}
39. Write a C program which copies one file to another, replacing all lowercase
characters with their uppercase equivalents.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
FILE *file1,*file2;
int i=0;
char c;
char str1[1000];
file1=fopen("file2.c","r");
file2=fopen("ex2.txt","w");
c=fgetc(file1);
while(c!=EOF)
{
str1[i]=toupper(c);
i++;
c=fgetc(file1);
}
fputs(str1,file2);
fclose(file1);
fclose(file2);
return 0;
}
40. Write a C program to count the number of times a character occurs in a text
file.

#include<stdio.h>

#include<stdlib.h>

#include<ctype.h>

#include<string.h>

int main()

FILE *fp;

char fname[50],str[5]=".txt",c,ch;

int count=0;

printf("\nenter a character to match with");

scanf("%c",&ch);

printf("\n Enter a file name");

scanf("%s",fname);

strcat(fname,".txt");

fp=fopen(fname,"r");

while((c=fgetc(fp))!=EOF)

if(c==ch)

count++;

printf("\nthe number of occurances of the character %c is: %d",ch,count);


}
41. Write a C program that does the following:It should first create a binary file
and store 10 integers, where the file name and 10 values are given in the command
line. (hint: convert the strings using atoi function). Now the program asks for an
index and a value from the user and the value at that index should be changed to
the new value in the file. (hint: use fseek function). The program should then read
all 10 values and print them back.
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
FILE *fp;
int a[10],i,ind,val,x;
char fname[50];
printf("\n Enter a file name");
scanf("%s",fname);
strcat(fname,".dat");
fp=fopen(fname,"wb");
printf("\n Enter 10 elements");
for(i=0;i<10;i++)
scanf("%d",&a[i]);
fwrite(a,sizeof(int),10,fp);
printf("\nEnter an index and value ");
scanf("%d%d",&ind,&val);
a[ind]=val;
x=ind+1;
fseek(fp,ind*sizeof(int),SEEK_SET);
fprintf(fp,"%d",a[ind]);
fclose(fp);
fread(a,sizeof(int),10,fp);
printf("\n elements of the array are:");
for(i=0;i<10;i++)
printf("%d\t",a[i]);
}
42. Write a C program to merge two files into a third file (i.e., the contents of the
first file followed by those of the second are put in the third file).
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
int main()
{
FILE *fptr1;
FILE *fptr2;
FILE *fptr3;
char ch;
fptr1=fopen("first.dat","r");
fptr2=fopen("second.dat","r");
fptr3=fopen("merge.dat","w");
while((ch=fgetc(fptr1))!=EOF)
{
fputc(ch,fptr3);
}
fclose(fptr3);
fptr3=fopen("merge.dat","a");
while((ch=fgetc(fptr2))!=EOF)
{
fputc(ch,fptr3);
}
fclose(fptr3);
fptr3=fopen("merge.dat","r");
while((ch=fgetc(fptr3))!=EOF)
{
printf("%c",ch);
}
fclose(fptr1);
fclose(fptr2);
return 0;
}
43. Write a program to count the number of characters, words and lines of a given
text file.
#include<stdio.h>

#include<stdlib.h>

#include<ctype.h>

#include<string.h>

int main()

FILE *fp;

char fname[50],str[5]=".txt",ch;

int cc=0,wc=1,lc=1;

printf("\n Enter a file name");

scanf("%s",fname);

strcat(fname,".txt");

fp=fopen(fname,"r");

while((ch=fgetc(fp))!=EOF)

if(ch=='\n'||ch=='\t'||ch==' ')

wc++;

if(ch=='\n')

lc++;

cc++;

}
printf("\nNumber of characters is %d",cc);

printf("\nNumber of words is %d",wc);

printf("\nNumber of lines is %d",lc);

}
44.Write a C program to store students' information (id, name, address, marks) into
a file and print the information from the file.
#include<stdio.h>
struct student
{
int id;
char name[20];
char address[20];
float marks;
};
void main()
{
FILE *fp;
char ch;
struct student s;
clrscr();
fp=fopen("stud.dat","wb+");
if(fp==NULL)
{
printf("Unable to create the file");
exit(0);
}
do
{
printf("Enter id,name,address,marks\n");
scanf("%d %s %s %f",&s.id,s.name,s.address,&s.marks);
fwrite((struct student*)&s,sizeof(s),1,fp);
printf("Enter y to continue");
scanf(" %c",&ch);
}while(ch!='y');
rewind(fp);
while(fwrite((struct student*)&s,sizeof(s),1,fp))
{
printf("%d %s %s %f\n",s.id,s.name,s.address,s.marks);
}
getch();
}
45. Write a C program that uses a non recursive function to search for a Key value
in a given list of integers using linear search method.
#include<stdio.h>
void linearsearch(int[],int,int);
void main()
{
int i, a[20], n, key;

printf("Enter the size of an array : ");


scanf("%d", &n);
printf("Enter the array elements: ");
for(i = 0; i < n; i++)
{
scanf("%d", &a[i]);
}
printf("Enter the key element: ");
scanf("%d", &key);
linearsearch(a,n,key);
}
void linearsearch(int a[],int n,int key)
{
int i,flag=0;
for(i = 0; i < n; i++)
{
if(a[i] == key)
{
flag = 1;
break;
}
}
if(flag == 1)
printf("The key elements %d is found at location %d.",key, i + 1);
else
printf("The key element %d is not found in the array.",key);

}
Output:
Enter the size of an array : 5
Enter the array elements: 3 4 5 6 8
Enter the key element: 6
The key elements 6 is found at location 4.
46. Write a C program that uses a non recursive function to search for a Key value
in a given sorted list of integers using binary search method.
#include<stdio.h>
void binarysearch(int [],int,int);
void main()
{
int a[20], i, n, key;
printf("Enter no of elements: ");
scanf("%d",&n);
printf("Enter the array elements in ascending order: ");
for(i = 0; i < n; i++)
{
scanf("%d", &a[i]);
}
printf("Enter the key element: ");
scanf("%d", &key);
binarysearch(a,n,key);
}
void binarysearch(int a[],int n,int key)
{
int i,low, high, mid;
low = 0;
high = n - 1;
while(high >= low)
{
mid = (low + high) / 2;
if(key == a[mid])
break;
else if(key > a[mid])
low = mid + 1;
else
high = mid - 1;
}
if(key == a[mid])
printf("The key element %d is found at location %d.", key,mid + 1);
else
printf("The key element %d is not found.",key);
}
Output:
Enter no of elements: 5
Enter the array elements in ascending order: 4 6 8 20 24
Enter the key element: 24
The key element 24 is found at location 5.
47. Write a C program that implements the Bubble sort method to sort a given list
of integers in ascending order.
#include <stdio.h>
int main()
{
int array[100], n, c, d, temp;

printf("Enter number of elements: ");


scanf("%d", &n);

printf("Enter %d integers: ", n);

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


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

for (c = 0 ; c < n - 1; c++)


{
for (d = 0 ; d < n - c - 1; d++)
{
if (array[d] > array[d+1]) /* For decreasing order use '<' instead of '>' */
{
temp = array[d];
array[d] = array[d+1];
array[d+1] = temp;
}
}
}
printf("Sorted list in ascending order using BUBBLE SORT: ");

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


printf("%d ", array[c]);
return 0;
}
Output:
Enter number of elements: 5
Enter 5 integers: 2 4 3 7 6
Sorted list in ascending order using BUBBLE SORT: 2 3 4 6 7
48. Write a C program that sorts the given array of integers using selection sort in
descending order
#include <stdio.h>
int main()
{
int a[100], n, i, j, position, swap;
printf("Enter number of elements: ");
scanf("%d", &n);
printf("Enter the elements: ");
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
for(i = 0; i < n - 1; i++)
{
position=i;
for(j = i + 1; j < n; j++)
{
if(a[position] < a[j])
position=j;
}
if(position != i)
{
swap=a[i];
a[i]=a[position];
a[position]=swap;
}
}
printf("Sorted Array in descending order using Selection sort :");
for(i = 0; i < n; i++)
printf("%d ", a[i]);
return 0;
}
Output:
Enter number of elements: 5
Enter the elements: 6 5 3 7 2
Sorted Array in descending order using Selection sort :7 6 5 3 2
49. Write a C program that sorts the given array of integers using insertion sort in
ascending order
#include <stdio.h>
int main()
{
int n, i, j, key;
int arr[64];

printf("Enter number of elements: ");


scanf("%d", &n);

printf("Enter %d integers :", n);


for (i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
}
for (i = 1 ; i <= n - 1; i++)
{
key=arr[i];
j = i-1;
while (j >= 0 && arr[j] > key)
{
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
printf("Array of integers using insertion sort in Ascending Order: ");
for (i = 0; i <= n - 1; i++)
{
printf("%d ", arr[i]);
}
return 0;
}
Output:
Enter number of elements: 5
Enter 5 integers :7 4 5 8 2
Array of integers using insertion sort in Ascending Order: 2 4 5 7 8
49. Write a C program that sorts the given array of integers using quick sort in
ascending order
#include <stdio.h>
void qsort(int a[],int l,int u)
{
int pivot=a[l],i=l+1,j=u,temp;
if(l<u)
{
while(i<=j)
{
while(a[i]<=pivot)
i++;
while(a[j]>pivot)
j--;
if(i<j)
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
temp=a[j];
a[j]=a[l];
a[l]=temp;
qsort(a,l,j-1);
qsort(a,j+1,u);
}
}
void main()
{
int a[100],i,n;
printf(“Enter the size”);
scanf(“%d”,&n);
printf(“Enter array elements”);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
qsort(a,0,n-1);
for(i=0;i<n;i++)
printf("%d ",a[i]);
}
Write a C program that sorts the given array of integers using merge sort in
ascending order
#include<stdio.h>
void merge(int a[],int l,int m,int u)
{
int i,j=0,temp[20],mid=m-1,lpos=l;
while(lpos<=mid&&m<=u)
{
if(a[lpos]<=a[m])
{
temp[j]=a[lpos];
j++;
lpos++;
}
else
{
temp[j]=a[m];
j++;
m++;
}
}
while(lpos<=mid)
{
temp[j]=a[lpos];
j++;
lpos++;
}
while(m<=u)
{
temp[j]=a[m];
j++;
m++;
}

for(i=l,j=0;i<=u;i++,j++)
{
a[i]=temp[j];
}
}
void mergesort(int a[],int l,int u)
{
int mid;
if(l<u)
{
mid=(l+u)/2;
mergesort(a,l,mid);
mergesort(a,mid+1,u);
merge(a,l,mid+1,u);
}
}

void main()
{
int a[100],i,n;
clrscr();
printf("Enter the size");
scanf("%d",&n);
printf("Enter array elements");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
mergesort(a,0,n-1);
for(i=0;i<n;i++)
printf("%d ",a[i]);
getch();
}
Write a C program to implement single linked list with the following operations
a) create b) insert at a position c) delete by value d) delete by position e) reverse
f) sort g) display
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
}*head=NULL;

void create(int x)
{
struct node *nn,*temp=head;
nn=(struct node*)malloc(sizeof(struct node));
nn->data=x;
nn->next=NULL;
if(head==NULL)
{
head=nn;
return;
}
while(temp->next!=NULL)
temp=temp->next;
temp->next=nn;
}
void addatbeg(int x)
{
struct node *nn;
nn=(struct node*)malloc(sizeof(struct node));
nn->data=x;
nn->next=head;
head=nn;
}

void addatpos(int x,int p)


{
int i;
struct node *nn,*temp=head;
if(p<=1)
{
addatbeg(x);
return;
}
for(i=1;i<p-1;i++)
temp=temp->next;
nn=(struct node*)malloc(sizeof(struct node));
nn->data=x;
nn->next=temp->next;
temp->next=nn;
}

void ldelete(int x)
{
struct node *temp=head,*prev;
while(temp!=NULL)
{
if(temp->data==x)
{
if(temp==head)
{
head=temp->next;
}
else
{
prev->next=temp->next;
}
free(temp);
printf("Node deleted\n");
return;
}
prev=temp;
temp=temp->next;
}
printf("Element not found\n");
}
void display()
{
struct node *temp=head;
if(head==NULL)
{
printf("List is empty\n");
return;
}
while(temp!=NULL)
{
printf("%d ",temp->data);
temp=temp->next;
}
printf("\n");
}
void sort()
{
struct node *t1,*t2;
int x;
for(t1=head;t1->next!=NULL;t1=t1->next)
{
for(t2=t1->next;t2!=NULL;t2=t2->next)
{
if(t1->data>t2->data)
{
x=t1->data;
t1->data=t2->data;
t2->data=x;
}
}
}
}
void main()
{
int x,ch,p;
clrscr();
while(1)
{
printf("\n1.create\n");
printf("2.addatbeg\n");
printf("3.addatpos\n");
printf("4.delete\n");
printf("5.sort\n");
printf("6.display\n");
printf("7.exit\n");
printf("Enter choice\n");
scanf("%d",&ch);
switch(ch)
{
case 1:printf("Enter a value\n");
scanf("%d",&x);
create(x);
break;
case 2:printf("Enter a value\n");
scanf("%d",&x);
addatbeg(x);
break;
case 3:printf("Enter a value and position\n");
scanf("%d %d",&x,&p);
addatpos(x,p);
break;
case 4:printf("Enter a value\n");
scanf("%d",&x);
ldelete(x);
break;
case 5:sort();
break;
case 6:display();
break;
case 7:exit(0);
}
}
}
53. Write a C program to implement stack using
a) arrays b) linked lists
#define size 5
#include<stdio.h>
#include<stdlib.h>
int s[size],top=-1;

void push(int x)
{
if(top==size-1)
{
printf("Stack is full\n");
return;
}
top++;
s[top]=x;
}
int pop()
{
int x;
if(top==-1)
{
printf("Stack is empty\n");
return -1;
}
x=s[top];
top--;
return x;
}
void display()
{
int i;
if(top==-1)
{
printf("Stack is empty\n");
return;
}
for(i=top;i>=0;i--)
{
printf("%d ",s[i]);
}
printf("\n");
}

void main()
{
int ch,x;
while(1)
{
printf("\n1.push\n");
printf("2.pop\n");
printf("3.display\n");
printf("4.exit\n");
printf("Enter choice\n");
scanf("%d",&ch);
switch(ch)
{
case 1:printf("Enter a value other than -1\n");
scanf("%d",&x);
push(x);
break;
case 2:x=pop();
if(x!=-1)
printf("Popped Value is %d\n",x);
break;
case 3:display();
break;
case 4:exit(0);
}
}
}

#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
}*top=NULL;

void push(int x)
{
struct node *nn;
nn=(struct node*)malloc(sizeof(struct node));
if(nn==NULL)
{
printf("Stack is full\n");
return;
}
nn->data=x;
nn->next=top;
top=nn;
}

int pop()
{
int x;
struct node *temp=top;
if(top==NULL)
{
printf("Stack is empty\n");
return -1;
}
x=top->data;
top=temp->next;
free(temp);
return x;
}
void display()
{
struct node *temp=top;
if(top==NULL)
{
printf("Stack is empty\n");
return;
}
while(temp!=NULL)
{
printf("%d ",temp->data);
temp=temp->next;
}
printf("\n");
}

void main()
{
int ch,x;
while(1)
{
printf("\n1.push\n");
printf("2.pop\n");
printf("3.display\n");
printf("4.exit\n");
printf("Enter choice\n");
scanf("%d",&ch);
switch(ch)
{
case 1:printf("Enter a value other than -1\n");
scanf("%d",&x);
push(x);
break;
case 2:x=pop();
if(x!=-1)
printf("Popped Value is %d\n",x);
break;
case 3:display();
break;
case 4:exit(0);
}
}
}
54. Write a C program to implement queues using
a) arrays b) linked lists
#define size 5
#include<stdio.h>
#include<stdlib.h>
int q[size],f=-1,r=-1;

void qinsert(int x)
{
if(r==size-1)
{
printf("Queue is full\n");
return;
}
r++;
q[r]=x;
if(f==-1)
f=0;
}
int qdelete()
{
int x;
if(f==-1)
{
printf("Queue is empty\n");
return -1;
}
x=q[f];
if(f==r)
f=r=-1;
else
f++;
return x;
}
void display()
{
int i;
if(f==-1)
{
printf("Queue is empty\n");
return;
}
for(i=f;i<=r;i++)
{
printf("%d ",q[i]);
}
printf("\n");
}

void main()
{
int ch,x;
while(1)
{
printf("\n1.insert\n");
printf("2.delete\n");
printf("3.display\n");
printf("4.exit\n");
printf("Enter choice\n");
scanf("%d",&ch);
switch(ch)
{
case 1:printf("Enter a value other than -1\n");
scanf("%d",&x);
qinsert(x);
break;
case 2:x=qdelete();
if(x!=-1)
printf("Deleted Value is %d\n",x);
break;
case 3:display();
break;
case 4:exit(0);
}
}
}
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
}*f=NULL,*r=NULL;

void qinsert(int x)
{
struct node *nn;
nn=(struct node*)malloc(sizeof(struct node));
if(nn==NULL)
{
printf("Queue is full\n");
return;
}
nn->data=x;
nn->next=NULL;
if(f==NULL&&r==NULL)
f=r=nn;
else
{
r->next=nn;
r=nn;
}
}

int qdelete()
{
int x;
struct node *temp=f;
if(f==NULL)
{
printf("Queue is empty\n");
return -1;
}
x=f->data;
if(f==r)
f=r=NULL;
else
f=temp->next;
free(temp);
return x;
}

void display()
{
struct node *temp=f;
if(f==NULL)
{
printf("Queue is empty\n");
return;
}
while(temp!=NULL)
{
printf("%d ",temp->data);
temp=temp->next;
}
printf("\n");
}
void main()
{
int ch,x;
while(1)
{
printf("\n1.insert\n");
printf("2.delete\n");
printf("3.display\n");
printf("4.exit\n");
printf("Enter choice\n");
scanf("%d",&ch);
switch(ch)
{
case 1:printf("Enter a value other than -1\n");
scanf("%d",&x);
qinsert(x);
break;
case 2:x=qdelete();
if(x!=-1)
printf("Deleted Value is %d\n",x);
break;
case 3:display();
break;
case 4:exit(0);
}
}
}
55. Write a C program to perform the following operations using stack
a) conversion of an infix to postfix expression
b) evaluation of postfix expression.
#define size 20
#include<stdio.h>
#include<conio.h>
char s[size];
int top=-1;

void push(char ch)


{
s[++top]=ch;
}

char pop()
{
return s[top--];
}

int priority(char ch)


{
switch(ch)
{
case '+':
case '-':return 1;
case '*':
case '/':
case '%':return 2;
case '#':return 0;
default:return 3;
}
}

void convert(char infix[],char postfix[])


{
int i=0,j=0;
while(infix[i]!='#')
{
while(priority(infix[i])<=priority(s[top]))
{
postfix[j]=pop();
j++;
}
push(infix[i]);
i++;
}

while(s[top]!='#')
{
postfix[j]=pop();
j++;
}
postfix[j]='\0';
}
void main()
{
char infix[size],postfix[size];
clrscr();
printf("Enter infix expression");
scanf("%s",infix);
convert(infix,postfix);
printf("Postfix expression is %s",postfix);
getch();
}
#define size 20
#include<stdio.h>
#include<conio.h>
char s[size];
int top=-1;

void push(char ch)


{
s[++top]=ch;
}

char pop()
{
return s[top--];
}

int priority(char ch)


{
switch(ch)
{
case '+':
case '-':return 1;
case '*':
case '/':
case '%':return 2;
case '#':return 0;
default:return 3;
}
}

void convert(char infix[],char postfix[])


{
int i=0,j=0;
while(infix[i]!='#')
{
while(priority(infix[i])<=priority(s[top]))
{
postfix[j]=pop();
j++;
}
push(infix[i]);
i++;
}

while(s[top]!='#')
{
postfix[j]=pop();
j++;
}
postfix[j]='\0';
}

int evaluate(char postfix[])


{
int i,x,y;
for(i=0;postfix[i]!='\0';i++)
{
if(postfix[i]>='0'&&postfix[i]<='9')
{
push(postfix[i]-'0');
}
else
{
x=pop();
y=pop();
switch(postfix[i])
{
case '+':push(y+x);
break;
case '-':push(y-x);
break;
case '*':push(y*x);
break;
case '/':push(y/x);
break;
case '%':push(y%x);
break;
}
}
}
return pop();
}
void main()
{
char infix[size],postfix[size];
clrscr();
printf("Enter infix expression");
scanf("%s",infix);
convert(infix,postfix);
printf("Postfix expression is %s",postfix);
getch();
}

You might also like