Uploaded by r2102862006

PPS-LAB-Manual

advertisement
Department of Computer Science and Engineering
Programming for Problem Solving Laboratory
Lab Manual
Subject Code: KGR23CS108
Regulation: KGR23
Academic Year: 2023-24
I B.Tech I-Semester
COMPUTER SCIENCE AND ENGINEERING
KG REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY
Affiliated To JNTUH, Chilkur, (V), Moinabad(M) R. R Dist, TS- 50150
1
Vision and Mission of the Institution
Vision:
To become an institution which is internationally recognized for its holistic approach
to engineering, innovative teaching and learning culture, research and entrepreneurial
ecosystem, and sustainable social impact in the community.
Mission:

To offer undergraduate and post-graduate programs which are supported through
industry relevant curriculum and innovative teaching and learning processes that
would help students succeed in their professional careers.

To provide faculty and students with an ecosystem that fosters innovation, research,
entrepreneurship, and international exposure through strategic partnerships with
government organizations and collaboration with industries.

To provide holistic learning environment to students which will contribute to their
personal and professional growth and enable them to become leaders in their
respective fields.

To contribute to the development of the region by using our technological expertise to
work with nearby communities and support them in their social and economic
development
2
Department of Computer Science and Engineering
Vision
To be recognized as a department of excellence by stimulating a learning environment
in which students and faculty will thrive and grow to achieve their professional,
institutional and societal goals.
Mission

To provide high quality technical education to students that will enable life-long
learning and build expertise in advanced technologies in Computer Science and
Engineering.

To promote research and development by providing opportunities to solve complex
engineering problems in collaboration with industry and government agencies.

To encourage professional development of students that will inculcate ethical values
and leadership skills through entrepreneurship while working with the community to
address societal issues.
Program Educational Outcomes (PEOs)
PEO 1
Graduates will provide solutions to difficult and challenging issues in their profession
by applying computer science and engineering theory and principles.
PEO 2
Graduates have successful careers in computer science and engineering fields or will be
able to successfully pursue advanced degrees.
PEO 3
Graduates will communicate effectively, work collaboratively and exhibit high levels
of professionalism, moral and ethical responsibility.
Graduates will develop the ability to understand and analyze engineering issues in a broader
PEO 4 perspective with ethical responsibility towards sustainable development.
3
Department of Computer Science and Engineering
Programme Outcomes (POs):
PO 1:
Engineering
knowledge
PO 2:
Problem analysis
PO 3:
Design /
development of
solutions
PO 4:
Conduct
investigations of
complex problems
PO 5:
Modern tool usage
PO 6:
The engineer and
society
PO 7:
Environment and
sustainability
PO 8:
Ethics
PO 9:
Individual and
team work
PO 10:
Communication
PO 11:
Project
management and
finance
PO 12:
Life-long learning
Apply the knowledge of mathematics, science, engineering fundamentals
and an engineering specialization to the solution of complex engineering
problems.
Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first
principles of mathematics, natural sciences, and engineering sciences.
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.
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.
Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modeling to complex
engineering activities with an understanding of the limitations.
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.
Understand the impact of the professional engineering solutions in the
societal and environmental contexts, and demonstrate the knowledge of,
and need for sustainable development.
Apply ethical principles and commit to professional ethics and
responsibilities and norms of the engineering practice.
Function effectively as an individual, and as a member or leader in
diverse teams, and in multidisciplinary settings.
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.
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.
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.
4
Department of Computer Science and Engineering
Programme Specific Outcomes (PSOs)
PSO 1:
The Computer Science and Engineering graduates are able to analyze, design,
develop, test and apply management principles, mathematical foundations in
the development of intelligent systems with computational solutions, make
them to expert in designing the secure application and hardware prototype.
PSO 2:
The graduating student will be analyze the contemporary research issues in
different areas of computer science & engineering and explore research gaps,
analyze and carry out research in the specialized/emerging areas.
PSO 3:
Develop their skills to solve problems in the broad area of programming
concepts and appraise environmental and social issues with ethics and
manage different projects in multi-disciplinary field to conducive in
cultivating skills for successful career, entrepreneurship and higher studies.
5
Programming for Problem Solving Laboratory
Course Code: KGR23CS108
L
T
P
C
0
0
2
1
B.Tech. I Year I Sem.
[Note:The programs may be executed using any available Open Source/Freely available
IDESome of the Tools available are:
CodeLite: https://codelite.org/Code:Blocks:
http://www.codeblocks.org/DevCpp :
http://www.bloodshed.net/devcpp.html Eclipse: http://www.eclipse.org
This list is not exhaustive and is NOT in any order of preference]
Course Objectives: The students will learn the following:
1. To work with an IDE to create, edit, compile, run and debug programs
2. To analyze the various steps in program development.
3. To develop programs to solve basic problems by understanding basic concepts
in C like operators, control statements etc.
4. To develop modular, reusable and readable C Programs using the concepts like
functions, arrays etc.
5. To Write programs using the Dynamic Memory Allocation concept and create,
read from and write to text and binary files.
Course Outcomes: The candidate is expected to be able to:
CO1:
Develop modular and readable C Programs
CO2:
Solve problems using strings, functions
CO3:
Handle data in files
CO4:
Implement stacks, queues using arrays, linked lists.
CO5:
Understand and analyze various searching and sorting algorithms.
Practice sessions:
a. 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.
b. Write a simple program that converts one given data type to another using auto
conversion and casting. Take the values from standard input.
Simple numeric problems:
a. Write a program for finding the max and min from the three numbers.
b. Write the program for the simple, compound interest.
c. Write a 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.
d. Write a program that prints a multiplication table for a given number and the
number of rows inthe table. For example, for a number 5 and rows = 3, the
output should be:
6
5x1=5
5 x 2 = 10
5 x 3 = 15
e. Write a program that shows the binary equivalent of a given positive numberbetween 0 to
255.
Expression Evaluation:
a.
b.
c.
d.
e.
f.
g.
h.
i.
A building has 10 floors with a floor height of 3 meters each. A ball is dropped from
the top of the building. Find the time taken by the ball to reach each floor. (Use the
formula s = ut+(1/2)at^2 where u and a are the initial velocity in m/sec (= 0) and
acceleration in m/sec^2 (= 9.8 m/s^2)).
Write a C program, which takes two integer operands and one operator from the user,
performs the operation and then prints theresult. (Consider the operators +,-,*, /, % and
use Switch Statement)
Write a program that finds if a given number is a prime number
Write a C program to find the sum of individual digits of a positive integer and test
given number is palindrome.
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 programto generate the first n terms of the sequence.
Write a C program to generate all the prime numbers between 1 and n, where n is a
value supplied by the user.
Write a C program to find the roots of a Quadratic equation.
Write a C program to calculate the following, where x is a fractional value. 1-x/2
+x^2/4-x^3/6
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 computes1+5+25+125.
Arrays, Pointers and Functions:
a.
b.
c.
d.
e.
f.
Write a C program to find the minimum, maximum and average in an array of
integers.
Write a function to compute mean, variance, Standard Deviation, sorting of n
elements in a single dimension array.
Write a C program that uses functions to perform the following:
a. Addition of Two Matrices
b. Multiplication of Two Matrices
Transpose of a matrix with memory dynamically allocated for the new matrix as row
and column counts may not be the same.
Write C programs that use both recursive and non-recursive functions
a) To find the factorial of a given integer.
b) To find the GCD (greatest common divisor) of two given integers.
c) To find x^n
Write a program for reading elements using a pointer into an array and display the
values using the array.
7
g.
h.
Write a program for display values reverse order from an array using a pointer.
Write a program through a pointer variable to sum of n elements from anarray.
Files:
a.
b.
c.
d.
e.
Write a C program to display the contents of a file to standard output device.
Write a C program which copies one file to another, replacing all lowercase
characters with their uppercase equivalents.
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.
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.
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 inthe third file).
Strings:
a.
b.
c.
d.
e.
f.
Write a C program to convert a Roman numeral ranging from I to L to its decimal
equivalent.
Write a C program that converts a number ranging from 1 to 50 to Romanequivalent
Write a C program that uses functions to perform the following operations:
a) To insert a sub-string into a given main string from a given position.
b) To delete n Characters from a given position in a given string.
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.)
Write a C program that displays the position of a character ch in the string S or – 1 if S
doesn‘t contain ch.
Write a C program to count the lines, words and characters in a given text.
Miscellaneous:
a.
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.
b.
Write a C program to construct a pyramid of numbers as follows:
1
*
1
1
*
12
**
23
22
**
123
***
456
333
***
4444
**
*
Sorting and Searching:
a.
Write a C program that uses non-recursive function to search for a Keyvalue in
a given list of integers using linear search method.
8
b.
c.
d.
e.
f.
Write a C program that uses non-recursive function to search for a Key value in a
given sorted list of integers using binary search method.
Write a C program that implements the Bubble sort method to sort a given list of
integers in ascending order.
Write a C program that sorts the given array of integers using selection sortin
descending order
Write a C program that sorts the given array of integers using insertionsort in
ascending order
Write a C program that sorts a given array of names
TEXT BOOKS:
1.
2.
Jeri R. Hanly and Elliot B.Koffman, Problem solving and Program Design in C 7th
Edition, Pearson
B.A. Forouzan and R.F. Gilberg C Programming and Data Structures, Cengage
Learning, (3rd Edition)
REFERENCE BOOKS:
1.
2.
3.
4.
5.
6.
7.
Brian W. Kernighan and Dennis M. Ritchie, The C Programming Language, PHI
E. Balagurusamy, Computer fundamentals and C, 2nd Edition, McGraw-Hill
Yashavant Kanetkar, Let Us C, 18th Edition, BPB
R.G. Dromey, How to solve it by Computer, Pearson (16th Impression)
Programming in C, Stephen G. Kochan, Fourth Edition, Pearson Education.
Herbert Schildt, C: The Complete Reference, Mc Graw Hill, 4th Edition
Byron Gottfried, Schaum’s Outline of Programming with C, McGraw-Hill
9
Programming for Problem Solving Laboratory
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. Take the values form standard input.
3. Write a program for find 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 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
8. Write a program that shows the binary equivalent of a given positive number between 0
and 255.
9. Write a C program to construct a pyramid of numbers as follows:
10. A building has 10 floors with a floor height of 3 meters each. A ball is dropped from
the top of the building. Find the time taken by the ball to reach each floor. (Use the
formula s = ut+(1/2) at^2 where u and a are the initial velocity in m/sec (= 0) and
acceleration in m/sec^2 (= 9.8 m/s^2)).
11. 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)
12. Write a program that finds if a given number is a prime number
10
13. Write a C program to find the sum of individual digits of a positive integer and test given
number is palindrome.
14. Write a C program to generate the first n terms of the sequence.
15. Write a C program to generate all the prime numbers between 1 and n, where n is a value
supplied by the user.
16. Write a C program to calculate the following, where x is a fractional value. 1-x/2 +x^2/4x^3/6
17. 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.
18. Write a C program to convert a Roman numeral ranging from I to L to its decimal
equivalent.
19. Write a C program that converts a number ranging from 1 to 50 to Roman equivalent.
20. Write a C program to find the minimum, maximum and average in an array of
integers.
21. 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.)
22. Write a C program that displays the position of a character ch in the string S or – 1 if S
doesn’t contains ch.
23. Write a C program to count the lines, words and characters in a given text.
24. Write a program through pointer variable to sum of n elements from array.
25. Write a program for reading elements using pointer into array and display the values
using array.
26. Write a program for display values reverse order from array using pointer.
27. Write a C program to display the contents of a file to standard output device.
28. Write a C program which copies one file to another, replacing all lowercase characters
with their uppercase equivalents.
29. 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.
30. 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
11
file. (hint: use fseek function) The program should then read all 10 values and print
them back.
31. 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).
32. Write a C program that uses functions to perform addition of two matrices.
33. Write a C program that uses functions to perform multiplication of two matrices.
34. Transpose of a matrix with memory dynamically allocated for the new matrix as row and
column counts may not be same.
35. Write a function to compute mean, variance, Standard Deviation, sorting of n elements in
single dimension array.
36. Write C programs that use both recursive and non-recursive functions to find the factorial
of a given integer.
37. Write C programs that use both recursive and non-recursive functions to find the GCD
(greatest common divisor) of two given integers.
38. Write C programs that use both recursive and non-recursive functions to find x^n
39. Write a C program that uses function to insert a sub-string in to a given main string from a
given position
40. Write a C program that uses function to delete n Characters from a given position in a
given string.
41. 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.
42. Write a C program that uses non recursive function to search for a Key value in agiven list
of integers using linear search method.
43. Write a C program that uses non recursive function to search for a Key value in a given
sorted list of integers using binary search method.
44. Write a C program that implements the Bubble sort method to sort a given list of integers
in ascending order
45. Write a C program that sorts the given array of integers using selection sort in descending
order.
46. Write a C program that sorts the given array of integers using insertion sort in ascending
order.
47. Write a C program that sorts a given array of names
12
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.
Aim: Program that prints the results of all the operators available in C. Program:
Program:
#include<stdio.h>
void main( )
{
int a,b;
printf("Enter the values of a and b");
scanf("%d%d",&a,&b);
printf("The arithmetic operators result is %d %d %d %d\n", a+b,a-b,a*b,a/b);
printf("The relational operators result is %d %d %d %d\n", a>b,a<b,a>=b,a<=b);
printf("The logical operators result is %d %d %d\n", a&&b,a||b,!(a==b));
printf("The increment operator result is %d %d %d %d\n",a++,++a,b++,++b);
printf("The decrement operator result is %d %d %d %d\n",a--,--a,b--,--b);
printf("The bitwise AND operator result is %d\n",a&b);
printf("The bitwise OR operator result is %d\n",a|b);
printf("The bitwise NOT operator result is %d\n",a^b);
}
Output:
Enter the values of a and b 5 2
The arithmetic operators result is 7 3 10 2
The relational operators result is 1 0 1 0
The logical operators result is 1 1 1
The increment operator result is 6 6 3 3
The decrement operator result is 6 6 3 3
The bitwise AND operator result is 0
The bitwise OR operator result is 7
The bitwise NOT operator result is
13
2. Write a simple program that converts one given data type to another using auto
conversion. Take the values form standard input.
Aim: program that converts one given data type to another using auto conversion.
Program:
#include<stdio.h>
void main()
{
float sum, count;
int mean;
printf("Enter the value of sum and count");
scanf("%f%f",&sum, &count);
mean=sum/count;
printf(" The value of mean is : %d\n", mean);
}
Output:
Enter the value of sum and count100 10
The value of mean is: 10
14
3. Write a program for find the max and min from the three numbers.
Aim: program for find the max and min from the three numbers. Program:
Program:
#include<stdio.h>
void main( )
{
int a,b,c;
printf("Enter 3 numbers");
scanf("%d%d%d",&a,&b,&c);
if(a>b && a>c)
printf("Maximum number is a = %d",a);
else if(b>a && b>c)
printf("Maximum number is b = %d",b);
else
printf("Maximum number is c = %d",c);
printf("\n");
if(a<b && a<c)
printf("Minimum number is a = %d",a);
else if(b<a && b<c)
printf("Minimum number is b = %d",b);
else
printf("Minimum number is c = %d",c);
}
Output:
Enter 3 numbers1 2 3
Maximum number is c = 3
Minimum number is a = 1
15
4. Write the program for the simple, compound interest.
Aim: program for the simple, compound interest.
Program:
#include<stdio.h>
#include<math.h>
void main()
{
int p,t;
float r,si, amount, ci;
printf("Enter principle,time and rate of interest");
scanf("%d%d%f",&p,&t,&r);
si=p*t*r/100;
printf("\nSimple interest = %.3f",si);
amount=p*pow((1 +r/100),t);
ci=amount-p;
printf("\nCompound interest = %.3f",ci);
}
Output:
Enter principle, time and rate of interest5000 10 4
Simple interest = 2000.000
Compound interest = 2401.219
16
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.
Aim: program that declares class awarded for a given percentage of marks.Program:
Program:
#include<stdio.h>
void main()
{
float per;
printf("Enter Percentage of Marks: ");
scanf("%f", &per);
printf("Percentage of Marks = %.2f\n", per);
if(per >= 70)
{
printf("Distinction");
}
else if(per>=60 && per<70)
{
printf("First Class");
}
else if(per>=40 && per<60)
{
printf("Second Class");
}
else
{
printf("Failed");
}
}
Output:
Enter Percentage of Marks: 60
Percentage of Marks = 60.00
First Class
17
6. Write a C program to find the roots of a Quadratic equation.
Aim: Program to find the roots of a Quadratic equation. \
Program:
#include<stdio.h>
#include<math.h>
void main()
{
float a,b,c,root1,root2;
printf("Enter values of a,b,c for finding roots of a quadratic eq:");
scanf("%f%f%f",&a,&b,&c);
if(b*b>4*a*c)
{
root1=(-b+sqrt(b*b-4*a*c))/(2*a);
root2=(-b-sqrt(b*b-4*a*c))/(2*a);
printf("\nRoots are real\n");
printf("\n root1=%f\n root2=%f",root1,root2);
}
else if(b*b==4*a*c)
{
printf("The roots are real and equal\n");
printf("\n root1=%f\n root2=%f",root1,root2);
}
else
printf("\n Imaginary Roots.");
}
Output:
Enter values of a, b, c for finding roots of a quadratic eq:2 3 1
Roots are real
root1=-0.500000
root2=-1.000000
18
7. Write a program that prints a multiplication table for a given number and the
numberof 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
Aim: program that prints a multiplication table for a given number and the number of rows
in the table.
Program:
#include <stdio.h>
void main()
{
int n, i, range;
printf("Enter a number for to generate table: ");
scanf("%d",&n);
printf("Enter the no. of rows required in the table: ");
scanf("%d", &range);
printf("The table for given number and no. of rows:\n");
for(i=1; i<=range; i++)
{
printf("%d * %d = %d \n",n,i, n*i);
}
}
Output:
Enter a number for to generate table: 5
Enter the no. of rows required in the table: 10
The table for given number and no. of rows:
5*1=5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
5 * 6 = 30
5 * 7 = 35
5 * 8 = 40
5 * 9 = 45
5 * 10 = 50
19
8. Write a program that shows the binary equivalent of a given positive number
between 0 and 255.
Aim: program that shows the binary equivalent of a given positive number between 0 and
255.
Program:
#include<stdio.h>
#include<math.h>
void main()
{
int num, rem=0, inum, p=0;
long int bin=0;
printf("Enter the number between 0 and 255"); scanf("%d",&num);
inum=num;
while(inum>0)
{
rem=inum%2;
bin+=rem*pow(10,p);
inum/=2;
p++;
}
printf("%d binary equivalent number is %ld",num,bin);
}
Output:
Enter the number between 0 and 25534
34 binary equivalent number is 100010
20
9. Write a C program to construct a pyramid of numbers as follows:
Aim: Program to construct a pyramid of numbers.
1
12
123
Program:
#include <stdio.h>
void 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("%d ",j);
}
printf("\n");
}
}
Output:
Enter number of rows: 3
1
12
123
21
Write a C program to construct a pyramid of numbers as follows:
Aim: Program to construct a pyramid of numbers.
*
**
***
Program:
#include <stdio.h>
void 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");
}
}
Output:
Enter number of rows: 3
*
**
***
22
Write a C program to construct a pyramid of numbers as follows:
Aim: Program to construct a pyramid of numbers.
1
23
456
Program:
#include <stdio.h>
void main()
{
int i, j, rows,num=1;
printf("Enter number of rows: ");
scanf("%d",&rows);
for(i=1; i<=rows; ++i)
{
for(j=1; j<=i; ++j,num++)
{
printf("%d ",num);
}
printf("\n");
}
}
Output:
Enter number of rows: 3
1
23
456
23
Write a C program to construct a pyramid of numbers as follows:
Aim: Program to construct a pyramid of numbers.
1
22
333
4444
Program:
#include <stdio.h>
void 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("%d ",i);
}
printf("\n");
}
}
Output:
Enter number of rows: 4
1
22
333
4444
24
Write a C program to construct a pyramid of numbers as follows:
Aim: Program to construct a pyramid of numbers.
*
**
***
****
***
**
*
Program:
#include <stdio.h>
void 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");
}
}
Output:
Enter number of rows: 4
*
**
***
****
***
**
*
25
10. A building has 10 floors with a floor height of 3 meters each. A ball is dropped
from the top of the building. Find the time taken by the ball to reach each floor.
(Use the formula s = ut+(1/2) at^2 where u and a are the initial velocity in m/sec
(= 0) and acceleration in m/sec^2 (= 9.8 m/s^2)).
Aim: program to print time taken by the ball to reach each floor.
Program:
#include<stdio.h>
#include<math.h>
void main()
{
double a=9.8, t=0.0, tt=0.0;
int i,s=3;
for(i=11;i>1;i--,s+=3)
{
t = sqrt((2*s)/a);
printf("The time taken from %d to %d is %lf\n",i,i-1,t);
}
}
Output:
The time taken from 11 to 10 is 0.782461
The time taken from 10 to 9 is 1.106567
The time taken from 9 to 8 is 1.355262
The time taken from 8 to 7 is 1.564922
The time taken from 7 to 6 is 1.749636
The time taken from 6 to 5 is 1.916630
The time taken from 5 to 4 is 2.070197
The time taken from 4 to 3 is 2.213133
The time taken from 3 to 2 is 2.347382
The time taken from 2 to 1 is 2.474358
26
11. 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)
Aim: program which takes two integer operands and one operator from the user, performs
the operation and then prints the result.
Program:
#include<stdio.h>
void main()
{
int a,b;
char ch;
printf(" + for addition\n");
printf(" - for subtraction\n");
printf(" * for multiplication\n");
printf(" / for division\n");
printf(" '\%' for modulus\n");
printf("Enter your choice");
scanf("%c",&ch);
printf("Enter two integers");
scanf("%d%d",&a,&b);
switch(ch)
{
case '+':
printf("The addition of %d and %d is %d",a,b,a+b);
break;
case '-':
printf("The subtraction of %d and %d is %d",a,b,a-b);
break;
case '*':
printf("The multiplication of %d and %d is %d",a,b,a*b);
break;
case '/':
printf("The division of %d and %d is %d",a,b,a/b);
break;
case '%':
printf("The modulus of %d and %d is %d",a,b,a%b);
27
break;
default:
printf("Entered wrong operator");
}
}
Output:
+ for addition
- for subtraction
* for multiplication
/ for division
'' for modulus
Enter your choice*
Enter two integers12 5
The multiplication of 12 and 5 is 60
28
12. Write a program that finds if a given number is a prime number
Aim: program to find the given number is a prime number or not. Program:
Program:
#include<stdio.h>
void main()
{
int num,i=2,count=0,rem=0;
printf("Enter a number");
scanf("%d",&num);
while(i<=num/2)
{
rem = num%i;
if(rem==0)
count++;
i++;
}
if(count>=1)
printf("The %d is not prime",num);
else
printf("The %d is prime",num);
}
Output:
Enter a number7
The 7 is prime
29
13. Write a C program to find the sum of individual digits of a positive integer and test
given number is palindrome.
Aim: Program to display the sum of individual digits of a positive integer andpalindrome number.
Program:
#include<stdio.h>
#include<math.h>
void main()
{
int num,rem,tnum,pal=0,i=1,sum=0;
printf("enter number");
scanf("%d",&num);
tnum=num;
while(tnum>0)
{
rem = tnum%10;
sum+=rem;
pal+=rem*pow(10,i);
i--;
tnum/=10;
}
printf("The sum of individual digits of %d is %d \n",num,sum);
if(pal == num)
printf("The %d is palindrome number",num);
else
printf("The %d is not a palindrome number",num);
}
Output:
Enter number121
The sum of individual digits of 121 is 4
The 121 is not a palindrome number
30
14. Write a C program to generate the first n terms of the sequence.
Aim: Program to display the first n terms of the Fibonacci sequence.Program:
Program:
#include <stdio.h>
void main()
{
int num1=0, num2=1,n,counter,fib;
printf("Enter Length of Series (n value) : ");
scanf("%d",&n);
printf("\n\t<----Fibonacci Series---->");
printf("\n\t%d %d",num1,num2);
//Loop will run for 2 Time less in series as first 2 digits printed in advance
for(counter = 1; counter <= n-2; counter++)
{
fib=num1 + num2;
printf(" %d",fib);
num1=num2;
num2=fib;
}
}
Output:
Enter Length of Series (n value) : 5
<----Fibonacci Series---->
01123
31
15. Write a C program to generate all the prime numbers between 1 and n, where n is a
value supplied by the user.
Aim: program to generate all the prime numbers between 1and n.
Program:
#include <stdio.h>
void main()
{
int no,counter,counter1,check;
printf("<
PRIME NO. SERIES >");
printf("\n\n\n\t\t\tINPUT THE VALUE OF N: ");
scanf("%d",&no);
printf("\n\nTHE PRIME NO. SERIES B/W 1 TO %d : \n\n",no);
//This loop will check a number to be prime number or not.
for(counter = 2; counter <= no; counter++)
{
check = 0;
for(counter1 = counter-1; counter1 > 1 ; counter1--)
if(counter%counter1 == 0)
{
check++;
// Increment Check, If Number is not a prime.
break;
}
if(check == 0)
printf("%d\t",counter);
}
}
Output:
<
PRIME NO. SERIES
>
INPUT THE VALUE OF N: 15
THE PRIME NO. SERIES B/W 1 TO 15:
2
3
5
7
11
13
32
16. Write a C program to calculate the following, where x is a fractional value. 1-x/2
+x^2/4-x^3/6
Aim: program to calculate the following, where x is a fractional value. 1-x/2 +x^2/4-x^3/6
Program:
#include<stdio.h>
#include<math.h>
void main()
{
float x,sum=1.0; int n;
printf("Enter x value");
scanf("%f",&x);
for(n=1;n<=3;n++)
{
sum+=((pow(-1,n))*((pow(x,n)/(2*n))));
}
printf("The sum of expression is %f",sum);
}
Output:
Enter x value5
The sum of expression is -16.083334
33
17. 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.
Aim: 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.
Program:
#include<stdio.h>
#include<math.h>
void main()
{
int i,x,n,sum=0;
printf("Enter x,n values");
scanf("%d%d",&x,&n);
for(i=0;i<=n;i++)
{
sum+=pow(x,i);
}
printf("The sum of given equation is %d",sum);
}
Output:
Enter x,n values5 3
The sum of given equation is 156
34
18. Write a C program to convert a Roman numeral ranging from I to L to its decimal
equivalent.
Aim: A C program to convert a Roman numeral ranging from I to L to its decimal equivalent.
Program:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void main()
{
int a[10],len,i,j,k;
char rom[10];
printf("Enter the Roman Numeral:");
scanf("%s",&rom);
len=strlen(rom);
for(i=0;i<len;i++)
{
if(rom[i]=='I')
a[i]=1;
else if(rom[i]=='V')
a[i]=5;
else if(rom[i]=='X')
a[i]=10;
else if(rom[i]=='L')
a[i]=50;
else
{
printf("Invalid Value");
exit(0);
}
}
k=a[len-1];
for (i=len-1; i>0; i--)
{
if(a[i]>a[i-1])
k=k-a[i-1];
else if(a[i]==a[i-1] || a[i]<a[i-1])
k=k+a[i-1];
}
printf("Decimal Equivalent of %s is %d",rom,k);
}
Output:
Enter the Roman numeral: IL
Decimal Equivalent of IL is 49
35
19. Write a C program that converts a number ranging from 1 to 50 to Roman
equivalent.
Aim: program that converts a number ranging from 1 to 50 to Roman equivalent Program:
Program:
#include <stdio.h>
void main(void)
{
int num, rem;
printf("Enter a number from 1 to 50: ");
scanf("%d", &num);
printf("Roman numerals: ");
while(num != 0)
{
if (num == 50) /* 50 - l */
{
printf("l");
num -= 50;
}
else 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;
}
}
}
Output:
Enter a number from 1 to 50: 34
Roman numerals: xxxiv
36
20. Write a C program to find the minimum, maximum and average in an
array ofintegers.
Aim: program to find the minimum, maximum and average in an array ofintegers.
Program:
#include<stdio.h>
void main()
{
int i,n,num[20],min=0,max=0;
float sum=0.0,avg=0.0;
printf("Enter how many number of elements you want to store");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter a[%d] value",i); scanf("%d",&num[i]);
}
min = max = num[0];
for(i=0;i<n;i++)
{
sum+=num[i];
if(num[i]<min)
min =num[i];
if(num[i]>max)
max = num[i];
}
avg = sum/i;
printf("The minimum element of an array is %d\n",min);
printf("The Maximum element of an array is %d\n",max);
printf("The average of array elements is %f\n",avg);
}
Output:
Enter how many numbers of elements you want to store5
Enter a[0] value5
Enter a[1] value7
Enter a[2] value8
Enter a[3] value2
Enter a[4] value3
The minimum element of an array is 2
The Maximum element of an array is 8
The average of array elements is 5.000000
37
21. 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.)
Aim: program to determine if the given string is a palindrome or not Program:
Program:
#include<stdio.h>
#include<string.h>
void main()
{
char str[10],strrev[10];
int i,j,len;
printf("Enter a string");
scanf("%s",str);
len=strlen(str);
for(i=len-1,j=0;i>=0;i--,j++)
{
strrev[j]=str[i];
}
strrev[j]='\0';
if(strcmp(str,strrev)==0)
printf("%s is palindrome",str);
else
printf("%s is not palindrome",str);
}
Output:
Enter a stringliril
liril is palindrome
38
22. Write a C program that displays the position of a character ch in the string S or – 1 if S
doesn’t contains ch.
Aim: program that displays the position of a character ch in the string S or – 1 if S doesn’t contains
ch.
Program:
//program that displays the position of a character ch in the string S or – 1 if S doesn’t ‘t contains ch.
#include<stdio.h>
#include<string.h>
#include<conio.h>
void main()
{
char s[30];// t[20];
char *found,t;
clrscr();
/* Entering the main string */
puts("Enter the first string: ");
gets(s);
/* Entering the string whose position or index to be displayed */
puts("Enter the string to be searched: ");
t=getchar();
/*Searching string t in string s */
// found=strstr(s,t);
found =strchr(s,t);
if(found)
printf("Second String is found in the First String at %d position.\n",found-s);
else
printf("-1");
getch();
}
Output:
Enter the first string:
rajaram
Enter the string to be searched:
Second String is found in the First String at 2 position
39
23. Write a C program to count the lines, words and characters in a given text.
Aim: program to count the lines, words and characters in a given text. Program:
Program:
#include <stdio.h>
void main()
{
char line[81], ctr;
int i,c,
end = 0,
characters = 0,
words = 0,
lines = 0;
printf("KEY IN THE TEXT.\n");
printf("GIVE ONE SPACE AFTER EACH WORD.\n");
printf("WHEN COMPLETED, PRESS 'RETURN'.\n\n");
while( end == 0)
{
/* Reading a line of text */ c = 0;
while((ctr=getchar()) != '\n')
line[c++] = ctr;
line[c] = '\0';
/* counting the words in a line */
if(line[0] == '\0')
break ;
else
{
words++;
for(i=0; line[i] != '\0';i++)
if(line[i] == ' ' || line[i] == '\t')
words++;
}
/* counting lines and characters */
lines = lines +1;
characters = characters + strlen(line);
}
printf ("\n");
printf("Number of lines = %d\n", lines);
printf("Number of words = %d\n", words);
printf("Number of characters = %d\n", characters);
}
Output:
KEY IN THE TEXT.
GIVE ONE SPACE AFTER EACH WORD.
WHEN COMPLETED, PRESS 'RETURN'.
this is my first class.
i am learning C programming.
it is a structured programming language.
Number of lines = 3
Number of words = 16
Number of characters = 91
40
24. Write a program through pointer variable to sum of n elements from array.
Aim: program through pointer variable to sum of n elements from array. Program:
Program:
#include<stdio.h>
void main()
{
int num[20],*pn,n,i,sum=0;
printf("Enter how many elements you want to store");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter %d value",i+1);
scanf("%d",&num[i]);
}
pn = &num[0];
printf("Displaying array elements through pointer variable\n");
for(i=0;i<n;i++)
{
sum+=*(pn+i);
printf("%d element is %d\n",i+1,*(pn+i));
}
printf("The sum of array elements through pointer variable is %d",sum);
}
Output:
Enter how many elements you want to store5
Enter 1 value1
Enter 2 value2
Enter 3 value3
Enter 4 value4
Enter 5 value5
Displaying array elements through pointer variable
1 element is 1
2 element is 2
3 element is 3
4 element is 4
5 element is 5
The sum of array elements through pointer variable is 15
41
25. Write a program for reading elements using pointer into array and display the
values using array.
Aim: program for reading elements using pointer into array and display the values using
array.
Program:
#include<stdio.h>
void main()
{
int num[20],*pn,n,i;
printf("Enter how many elements you want to store");
scanf("%d",&n);
pn = num;
for(i=0;i<n;i++)
{
printf("Enter %d value",i+1);
scanf("%d",(pn+i));
}
printf("The array elements are\n");
for(i=0;i<n;i++)
{
printf("%d element is %d\n",i+1,num[i]);
}
}
Output:
Enter how many elements you want to store5
Enter 1 value10
Enter 2 value5
Enter 3 value3
Enter 4 value2
Enter 5 value9
The array elements are
1 element is 10
2 element is 5
3 element is 3
4 element is 2
5 element is 9
42
26. Write a program for display values reverse order from array using pointer.
Aim: Write a program for display values reverse order from array using pointer.
Program:
#include<stdio.h>
void main()
{
int num[20],*pn,n,i;
printf("Enter how many elements you want to store");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter %d value",i+1);
scanf("%d",&num[i]);
}
pn = &num[0];
printf("Displaying array elements in reverse order through pointer variable\n");
for(i=n-1;i>=0;i--)
{
printf("%d element is %d\n",i+1,*(pn+i));
}
}
Output:
Enter how many elements you want to store5
Enter 1 value9
Enter 2 value1
Enter 3 value3
Enter 4 value2
Enter 5 value5
Displaying array elements in reverse order through pointer variable
5 element is 5
4 element is 2
3 element is 3
2 element is 1
1 element is 9
43
27. Write a C program to display the contents of a file to standard output device.
Aim: C program to display the contents of a file to standard output device.
Program:
//C program to display the contents of a file to standard output device.
#include <stdio.h>
#include <conio.h>
#include <process.h>
void main(int argc, char *argv[])
{
FILE *fs;
char ch;
clrscr();
if(argc!=2)
{
puts("Invalid number of arguments.");
exit(0);
}
fs = fopen(argv[1],"r");
if(fs==NULL)
{
puts("Source file cannot be opened.");
exit(0);
}
while(1)
{
ch=fgetc(fs);
if (ch==EOF)
break;
else
putch(ch);
}
fclose(fs);
getch();
}
Output:
C:\turboc3\source>29_file abc
Welcome to C
44
28. Write a C program which copies one file to another, replacing all lowercase characters with
their uppercase equivalents.
Aim: C program copies contents of one file to another by replacing all lowercase characters
with their uppercase equivalents.
Program:
#include<stdio.h>
void main()
{
char ch;
FILE *fp1,*fp2;
clrscr();
fp1 = fopen("cbi","r");
if(fp1 == NULL)
{
printf("File is not opened properly");exit(0);
}
fp2 = fopen("lmn","w");
if(fp2 == NULL)
{
printf("File is not opened properly");exit(0);
}
while((ch=fgetc(fp1))!=EOF)
{
if(ch>=97 && ch<=122)
{
ch=ch-32;
fputc(ch,fp2);
}
else
fputc(ch,fp2);
}
fcloseall();
}
Output:
C:\turboc3\source> type abc
Welcome to C
C:\turboc3\source> type xyz
WELCOME TO C
45
29. Write a C program to count the number of times a character occurs in a text file.
Thefile name and the character are supplied as command line arguments.
Aim: C program to count the number of times a character occurs in a text file.
Program:
#include<stdio.h>
void main(int argc,char* argv[])
{
char ch;
int count=0;
FILE *fp1;
clrscr();
if(argc!=3)
{
printf("Invalid number of arguments");exit(0);
}
fp1 = fopen(argv[1],"r");
if(fp1 == NULL)
{
printf("File is not opened properly");exit(0);
}
while((ch=fgetc(fp1))!=EOF)
{
if(ch==*argv[2])
{
count++;
}
}
printf("The %c is occured %d times in the file %s",*argv[2],count,argv[1]);
fclose(fp1);
}
Output:
C:\turboc3\source>29_ntcof abc m
The m is occurred 2 times in the file abc
46
30. 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.
Aim: C program that create a binary file and store 10 integers, where the file name and 10
values are given in the command line. 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. The program
read all 10 values and prints them back.
Program:
#include<stdio.h>
#include<stdlib.h>
void main(int argc,char* argv[])
{
FILE *fp1,*fp2;
int i,n,j=0,a[100],b[20],index=0,vindex=0;
if(argc!=12)
{
printf("Invalid number of arguments");
exit(0);
}
fp1 = fopen(argv[1],"wb");
if(fp1 == NULL)
{
printf("File is not opened properly");
exit(0);
}
i=2;
printf("Data from user:\n");
while(i<=11)
{
a[j]=atoi(argv[i]);
printf("%d\t",a[j]);
i++;
j++;
}
fwrite(&a,sizeof(int),10,fp1);
printf("Enter the index and value for index");
scanf("%d%d",&index,&vindex);
fseek(fp1,index,0);
fwrite(&vindex,sizeof(int),1,fp1);
47
fclose(fp1);
fp1 = fopen(argv[1],"r+b");
if(fp1 == NULL)
{
printf("File is not opened properly");
exit(0);
}
n = fread(&b,sizeof(int),10,fp1);
i=0;
printf("data from file:\n");
while(i<n)
{
printf("%d\t",b[i]);
i++;
}
fclose(fp1);
}
Output:
C:\turboc3\source>30_binfi dataint 1 2 3 4 5 6 7 8 9 10
Data from user:
1
2
3
4
5
6
7
8
Enter the index and value for index 2 34
Data from file:
1
34
3
4
5
6
7
8
9
9
10
10
48
31. 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).
Aim: C program to merge two files into a third file.
Program:
#include <stdio.h>
#include <conio.h>
void main(int argc, char *argv[])
{
FILE *f1,*f2,*f3;
char ch;
clrscr();
if(argc!=4)
{
puts("Invalid number of arguments.");
exit(0);
}
f1 = fopen(argv[1],"r");
if(f1==NULL)
{
puts("Source file cannot be opened.");
exit(0);
}
f2 = fopen(argv[2],"r");
if (f2==NULL)
{
puts("Source file cannot be opened.");
exit(0);
}
f3 = fopen(argv[3],"w");
if (f3==NULL)
{
puts("Target file cannot be opened.");
exit(0);
}
while((ch=fgetc(f1))!=EOF)
{
fputc(ch,f3);
}
while((ch=fgetc(f2))!=EOF)
{
49
fputc(ch,f3);
}
fclose(f1);
fclose(f2);
fclose(f3);
getch();
}
Output:
C:\turboc3\source>31_file abc pqr lmn
C:\turboc3\source>type abc
Welcome to C
C:\turboc3\source>type pqr
File merge concept
C:\turboc3\source>type lmn
Welcome to C
File merge concept
50
32. Write a C program that uses functions to perform addition of two matrices.
Aim: program that uses functions to perform addition of two matrices.
Program:
#include <stdio.h>
void mat_add(int first[10][10],int second[10][10],int,int);
void main()
{
int m, n, c, d, first[10][10], second[10][10];
printf("Enter the number of rows and columns of matrix\n");
scanf("%d%d", &m, &n);
printf("Enter the elements of first matrix\n");
for (c = 0; c < m; c++)
for (d = 0; d < n; d++)
scanf("%d", &first[c][d]);
printf("Enter the elements of second matrix\n");
for (c = 0; c < m; c++)
for (d = 0 ; d < n; d++)
scanf("%d", &second[c][d]);
mat_add(first,second,m,n);
}
void mat_add(int first[10][10],int second[10][10],int m,int n)
{
printf("addition of two matrices:-\n");
int c,d, sum[10][10];
for (c = 0; c < m; c++)
{
for (d = 0 ; d < n; d++)
{
sum[c][d] = first[c][d] + second[c][d];
printf("%d\t", sum[c][d]);
}
printf("\n");
}
}
Output:
Enter the number of rows and columns of matrix
22
Enter the elements of first matrix
12
34
Enter the elements of second matrix
56
78
Sum of entered matrices:6
8
10
12
51
33. Write a C program that uses functions to perform multiplication of two matrices.
Aim: C program that uses functions to perform multiplication of two matrices.
Program:
/* Multiplication of Two Matrices */
#include<stdio.h>
#include<stdio.h>
void mat_mul(int a[10][10],int b[10][10],int,int,int);
void main()
{
int i,j,m,n,p,q,k,a[10][10],b[10][10],c[10][10];
printf("Input rows and columns of A matrix:");
scanf("%d%d",&m,&n);
printf("Input rows and columns of B matrix:");
scanf("%d%d",&p,&q);
if(n==p)
{
printf("matrices can be multiplised\n");
printf("resultant matrix is %d*%d\n",m,q);
printf("Input A matrix\n");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
{
printf("Enter a[%d][%d] value",i,j);
scanf("%d",&a[i][j]);
}
printf("Input B matrix\n");
for(i=0;i<p;i++)
for(j=0;j<q;j++)
{
printf("Enter b[%d][%d] value",i,j);
scanf("%d",&b[i][j]);
}
mat_mul(a,b,m,n,q);
}
else
{
printf("Matrices cannot be multiplied.");
}
}
52
void mat_mul(int a[10][10],int b[10][10],int m,int n,int q)
{
int i,j,k,c[10][10];
printf("\n =====Matrix Multiplication=====\n");
for(i=0;i<m;++i)
{
for(j=0;j<q;++j)
{
c[i][j]=0;
for(k=0;k<n;++k)
c[i][j]=c[i][j]+a[i][k]*b[k][j];
}
}
printf("Resultant of two matrices:\n");
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
printf("%5d",c[i][j]);
printf("\n");
}
}
Output:
Input rows and columns of A matrix:2 2
Input rows and columns of B matrix:2 2
matrices can be multiplised
resultant matrix is 2*2
Input A matrix
Enter a[0][0] value1
Enter a[0][1] value2
Enter a[1][0] value3
Enter a[1][1] value4
Input B matrix
Enter b[0][0] value5
Enter b[0][1] value6
Enter b[1][0] value7
Enter b[1][1] value8
=====Matrix Multiplication=====
Resultant of two matrices:
19 22
43 50
53
34. Transpose of a matrix with memory dynamically allocated for the new matrix as
rowand column counts may not be same.
Aim: Transpose of a matrix with memory dynamically allocated for the new matrix as row
and column counts may not be same.
Program:
#include<stdio.h>
#include<stdlib.h>
void tra_mat(int a[10][10],int r,int c);
void main()
{
int a[10][10],*b,i,j,r,c,tr,tc;
printf("Enter number of rows and columns you want");
scanf("%d%d",&r,&c);
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf("Enter a[%d][%d] element",i,j);
scanf("%d",&a[i][j]);
}
}
printf("Given Matrix is \n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
printf("%d\t",a[i][j]);
printf("\n");
}
tra_mat(a,r,c);
}
void tra_mat(int a[10][10],int r,int c)
{
int tr,tc,i,j,*b;
tr =c;
tc =r;
b =(int*)malloc(tr*tc*sizeof(int));
for(i=0;i<c;i++)
{
for(j=0;j<r;j++)
{
*(b+i*tc+j)=a[j][i];
}
}
54
printf("Transposed Matrix is\n");
for(i=0;i<tr;i++)
{
for(j=0;j<tc;j++)
printf("%d\t",*(b+i*tc+j));
printf("\n");
}
}
Output:
Enter number of rows and columns you want2 3
Enter a[0][0] element1
Enter a[0][1] element2
Enter a[0][2] element3
Enter a[1][0] element4
Enter a[1][1] element5
Enter a[1][2] element6
Given Matrix is
1
2
3
4
5
6
Transposed Matrix is
1
4
2
5
3
6
55
35. Write a function to compute mean, variance, Standard Deviation, sorting of n
elements in single dimension array.
Aim: a function to compute mean, variance, Standard Deviation, sorting of n elements in
single dimension array.
Program:
#include <stdio.h>
#include <math.h>
#define MAXSIZE 10
void compute_mean_var_sd(int x[MAXSIZE],int n);
void main()
{
int x[MAXSIZE];
int i, n;
printf("Enter the value of N \n");
scanf("%d", &n);
printf("Enter %d integers \n", n);
for (i = 0; i < n; i++)
{
scanf("%d", &x[i]);
}
compute_mean_var_sd(x,n);
}
void compute_mean_var_sd(int x[MAXSIZE],int n)
{
float average, variance, std_deviation, sum = 0, sum1=0;
int i;
/* Compute the sum of all elements */
for (i = 0; i < n; i++)
{
sum = sum + x[i];
}
average = sum / (float)n;
56
for (i = 0; i < n; i++)
{
sum1 = sum1 + pow((x[i] - average), 2);
}
variance = sum1 / (float)n;
std_deviation = sqrt(variance);
printf("Average of all elements = %.2f\n", average);
printf("Variance of all elements = %.2f\n", variance);
printf("Standard deviation = %.2f\n", std_deviation);
}
Output:
Enter the value of N
5
Enter 5 integers
1
2
3
4
5
Average of all elements = 3.00
Variance of all elements = 2.00
Standard deviation = 1.41
57
36. Write C programs that use both recursive and non-recursive functions to find the
factorial of a given integer.
Aim: programs that use both recursive and non-recursive functions to find the factorial of a
given integer.
Program:
#include<stdio.h>
int rec_factorial(int);
int non_rec_factorial(int);
void main()
{
int n,rfact,nrfact;
printf("Enter n value");
scanf("%d",&n);
rfact=rec_factorial(n);
printf("The factorial of %d is %d using recursive\n",n,rfact);
nrfact=non_rec_factorial(n);
printf("The factorial of %d is %d using non-recursive\n",n,nrfact);
}
int rec_factorial(int n)
{
if(n==0)
return 1;
else
return n*rec_factorial(n-1);
}
int non_rec_factorial(int n)
{
int fact=1,i;
for(i=1;i<=n;i++)
fact*=i;
return fact;
}
Output:
Enter n value5
The factorial of 5 is 120 using recursive
The factorial of 5 is 120 using non-recursive
58
37. Write C programs that use both recursive and non-recursive functions to find the
GCD (greatest common divisor) of two given integers.
Aim: programs that use both recursive and non-recursive functions to find the GCD (greatest
common divisor) of two given integers.
Program:
#include<stdio.h>
#include<math.h>
int GcdRecursive(int m, int n);
int GcdNonRecursive(int p,int q);
int main(void)
{
int a,b,iGcd;
printf("Enter the two numbers whose GCD is to be found: ");
scanf("%d%d",&a,&b);
printf("GCD of %d and %d Using Recursive Function is
%d\n",a,b,GcdRecursive(a,b));
printf("GCD of %d and %d Using Non-Recursive Function is
%d\n",a,b,GcdNonRecursive(a,b));
}
/* Recursive Function*/
int GcdRecursive(int m, int n)
{
if(n>m)
return GcdRecursive(n,m);
if(n==0)
return m;
else
return GcdRecursive(n,m%n);
}
/* Non-Recursive Function*/
int GcdNonRecursive(int p, int q)
{
int rem,temp;
if (q>p)
{
temp=p;
p=q;
59
q=temp;
}
rem = p%q;
if(rem==0)
return q;
else
while(rem>0)
{
q=rem;
p=q;
rem = p%q;
}
return q;
}
Output:
Enter the two numbers whose GCD is to be found: 16 4
GCD of 16 and 4 Using Recursive Function is 4
GCD of 16 and 4 Using Non-Recursive Function is 4
60
38. Write C programs that use both recursive and non-recursive functions to find x^n
Aim: C programs that use both recursive and non-recursive functions to find x^n
Program:
#include <stdio.h>
int rec_xpowern(int,int);
int non_rec_xpowern(int,int);
void main()
{
int base, pow, rxpn,nrxpn;
printf("Enter base number: ");
scanf("%d", &base);
printf("Enter power number(positive integer): ");
scanf("%d",&pow);
rxpn = rec_xpowern(base,pow);
printf("\nRecursive %d^%d = %d", base, pow,rxpn);
nrxpn = non_rec_xpowern(base,pow);
printf("\nNon Recursive %d^%d = %d", base, pow,nrxpn);
}
int rec_xpowern(int base, int pow)
{
if (pow != 0)
return (base * rec_xpowern(base, pow - 1));
else
return 1;
}
int non_rec_xpowern(int base, int pow)
{
int i,xpn=1;
if(pow == 0)
return 1;
else
for(i=1;i<=pow;i++)
xpn*=base;
return xpn;
}
Output:
Enter base number: 2
Enter power number (positive integer): 3
Recursive 2^3 = 8
Non Recursive 2^3 = 8
61
39. Write a C program that uses function to insert a sub-string in to a given main string
from a given position
Aim: program that uses function to insert a sub-string in to a given main string from a given
position
Program:
#include<stdio.h>
#include<string.h>
void ins_substr(char a[20],char b[20],int p);
void main()
{
char a[20],b[20];
int p=0;
puts("Enter First String:");
gets(a);
puts("Enter Second String:");
gets(b);
printf("Enter the position where the item has to be inserted: ");
scanf("%d",&p);
ins_substr(a,b,p);
}
void ins_substr(char a[20],char b[20],int p)
{
char c[20];
int r=0,n=0,i=0,t=0,s=0,o=0,x;
r = strlen(a);
n = strlen(b);
i=0;
/* Copying the input string into another array*/
while(i <= r)
{
c[i]=a[i]; i++;
}
s = n+r;
o = p+n;
62
/* Adding the sub-string
*/
for(i=p;i<s;i++)
{
x = c[i];
if(t<n)
{
a[i] = b[t]; t=t+1;
}
a[o]=x; o=o+1;
}
printf("%s", a);
}
Output:
Enter First String:
Rama Reddy
Enter Second String:
Muni
Enter the position where the item has to be inserted: 4
Rama Muni Reddy
63
40. Write a C program that uses function to delete n Characters from a given position
in agiven string.
Aim: program that uses function to delete n Characters from a given position in a given
string.
Program:
#include <stdio.h>
#include <string.h>
void delchar(char *x,int a, int b);
void main()
{
char string[10];
int n,pos,p;
puts("Enter the string");
gets(string);
printf("Enter the position from where to delete");
scanf("%d",&pos);
printf("Enter the number of characters to be deleted");
scanf("%d",&n);
delchar(string, n,pos);
}
/* Function to delete n characters */
void delchar(char *x,int a, int b)
{
if ((a+b-1) <= strlen(x))
{
strcpy(&x[b-1],&x[a+b-1]); puts(x);
}
}
Output:
Enter the string
Ram Reddy
Enter the position from where to delete4
Enter the number of characters to be deleted6
Ram
64
41. 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.
Aim: a menu driven C program that allows a user to enter n numbers and then choose
between finding the smallest, largest, sum, or average.
Program:
#include<stdio.h>
void menu();
int smallest(int a[],int n);
int largest(int a[],int n);
int sum(int a[],int n);
float average(int a[],int n);
void main()
{
int a[10],n,i,ch,small,large,soe;
float avg;
printf("Enter How many numbers you want");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter %d number ",i+1);
scanf("%d",&a[i]);
}
menu();
printf("Enter your choice");
scanf("%d",&ch);
switch(ch)
{
case 1:
small = smallest(a,n);
printf("Smallest number is %d",small);
break;
case 2:
large = largest(a,n);
printf("Largest number is %d",large);
break;
case 3:
soe = sum(a,n);
65
printf("Sum of elements is %d",soe);
break;
case 4:
avg = average(a,n);
printf("Average of elements is %d",avg);
break;
default:
printf("Invalid Choice");
break;
}
}
void menu()
{
printf("1. smalest number\n");
printf("2. largest number\n");
printf("3. sum of all numbers\n");
printf("4. average of all numbers\n");
}
int smallest(int a[],int n)
{
int i,small=a[0];
for(i=1;i<n;i++)
{
if(a[i]<small)
small = a[i];
}
return small;
}
int largest(int a[],int n)
{
int i,large=a[0];
for(i=1;i<n;i++)
{
if(a[i]>large)
large = a[i];
}
return large;
}
int sum(int a[],int n)
{
int i,sum=0;
for(i=0;i<n;i++)
sum+=a[i];
return sum;
}
66
float average(int a[],int n)
{
int i;
float sum=0.0;
for(i=0;i<n;i++)
sum+=a[i];
return (sum/n);
}
Output:
Enter how many numbers you want5
Enter 1 number 4
Enter 2 number 3
Enter 3 number 7
Enter 4 number 8
Enter 5 number 6
1. smalest number
2. largest number
3. sum of all numbers
4. average of all numbers
Enter your choice3
Sum of elements is 28
67
42. Write a C program that uses non-recursive function to search for a Key value in a
given list of integers using linear search method.
Aim: program that uses non- recursive function to search for a Key value in a given list of
integers using linear search method.
Program:
#include <stdio.h>
#define MAX_LEN 10
void l_search_nonrecursive(int l[],int num,int ele);
void main()
{
int l[MAX_LEN], num, ele,i;
printf("Enter the number of elements :");
scanf("%d",&num);
printf("\nEnter the elements:\n");
for(i=0;i<num;i++)
scanf("%d",&l[i]);
printf("\nElements present in the list are:\n\n");
for(i=0;i<num;i++)
printf("%d\t",l[i]);
printf("\n\nElement you want to search:\n\n");
scanf("%d",&ele);
}
l_search_nonrecursive(l,num,ele);
/*end main*/
/* Non-Recursive method*/
void l_search_nonrecursive(int l[],int num,int ele)
{
int i;
for(i=0;i<num;i++)
{
if( l[i] == ele)
{
printf("\nThe element %d is present at index position %d in list\n",ele,i);
exit(0);
}
}
printf("\nThe element %d is not present in the list\n",ele);
}
68
Output:
Enter the number of elements : 6
Enter the elements:
12
5
3
11
6
8
Elements present in the list are:
12
5
3
11
6
8
Element you want to search:
11
The element 11 is present at index position 3 in list
69
43. Write a C program that uses non recursive function to search for a Key value in a
given sorted list of integers using binary search method.
Aim: C program that uses non recursive function to search for a Key value in a given sorted
list of integers using binary search method.
Program:
#include<stdio.h>
#include<stdlib.h>
#define MAX_LEN 10
void b_search_nonrecursive(int l[],int num,int ele);
void main()
{
int l[MAX_LEN], num, ele,i;
printf("\nEnter the number of elements : ");
scanf("%d",&num);
printf("\nEnter the elements in sorted order:\n");
for(i=0;i<num;i++)
scanf("%d",&l[i]);
printf("\nElements present in the list are:\n\n");
for(i=0;i<num;i++)
printf("%d\t",l[i]);
printf("\n\nEnter the element you want to search:\n\n");
scanf("%d",&ele);
b_search_nonrecursive(l,num,ele);
}
/* Non-Recursive function*/
void b_search_nonrecursive(int l[],int num,int ele)
{
int low=0,high=num-1,j;
while(low <= high)
{
j = (low+high)/2;
if( l[j] == ele)
{
printf("\nThe element %d is present at index position %d in list\n",ele,j);
70
exit(0);
}
else if(l[j] < ele)
low = j+1;
else
high = j-1;
}
printf("\nThe element %d is not present in the list\n",ele);
}
Output:
Enter the number of elements : 6
Enter the elements in sorted order:
12
14
15
16
17
18
Elements present in the list are:
12
14
15
16
17
18
Enter the element you want to search:
18
The element 18 is present at index position 5 in list
71
44. Write a C program that implements the Bubble sort method to sort a given list of
integers in ascending order
Aim: program that implements the Bubble sort method to sort a given list of integers in
ascending order
Program:
#include <stdio.h>
#define MAX 10
void swapList(int *m,int *n)
{
int temp; temp = *m;
*m = *n;
*n = temp;
}
/* Function for Bubble Sort */
void bub_sort(int list[], int n)
{
int i,j;
for(i=0;i<(n-1);i++)
for(j=0;j<(n-(i+1));j++)
if(list[j] > list[j+1])
swapList(&list[j],&list[j+1]);
}
void readlist(int list[],int n)
{
int j;
printf("\nEnter the elements: \n");
for(j=0;j<n;j++)
scanf("%d",&list[j]);
}
/* displaying the contents of the list */
void printlist(int list[],int n)
{
int j;
for(j=0;j<n;j++)
printf("%d\t",list[j]);
}
72
void main()
{
int list[MAX],num;
printf("\n\n\n***** Enter the number of elements [Maximum 10] *****\n");
scanf("%d",&num);
readlist(list,num);
printf("\n\nElements in the list before sorting are:\n");
printlist(list,num);
bub_sort(list,num);
printf("\n\nElements in the list after sorting are:\n");
printlist(list,num);
}
Output:
***** Enter the number of elements [Maximum 10] *****
5
Enter the elements:
1
5
2
7
6
Elements in the list before sorting are:
1
5
2
7
6
Elements in the list after sorting are:
1
2
5
6
7
73
45. Write a C program that sorts the given array of integers using selection sort in
descending order.
Aim: program that sorts the given array of integers using selection sort in descendingorder.
Program:
#include<stdlib.h>
#include<stdio.h>
#define MAXSIZE 500
void selection(int elements[], int maxsize);
int elements[MAXSIZE], maxsize;
void main()
{
int i;
printf("\n How many elements you want to sort:");
scanf("%d",&maxsize);
printf("\n Enter the values one by one");
for(i=0;i<maxsize;i++)
{
printf("\nEnter element %i:",i);
scanf("%d",&elements[i]);
}
printf("\n Array before sorting:\n");
for(i=0;i<maxsize;i++)
printf("\t%d",elements[i]);
printf("\n");
selection(elements,maxsize);
printf("\n Array after sorting:\n");
for(i=0;i<maxsize;i++)
printf("\t%d",elements[i]);
}
void selection(int elements[],int maxsize)
{
int i,j,k;
int min,temp;
for(i=0;i<maxsize-1;i++)
{
min=i;
for(j=i+1;j<maxsize;j++)
{
if(elements[j]<elements[min])
min=j;
}
74
temp=elements[i];
elements[i]=elements[min];
elements[min]=temp;
}
}
Output:
How many elements you want to sort:6
Enter the values one by one
Enter element 0:12
Enter element 1:9
Enter element 2:3
Enter element 3:6
Enter element 4:4
Enter element 5:18
Array before sorting:
12 9
3
6
4
18
Array after sorting:
3
4
6
9
12
18
75
46. Write a C program that sorts the given array of integers using insertion sort in
ascending order.
Aim: program that sorts the given array of integers using insertion sort in ascending order.
Program:
#include <stdio.h>
void insertion_sort(int arr[100],int n);
void main()
{
int n, i, j, temp, arr[64];
printf("Enter number of elements\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for (i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
}
insertion_sort(arr,n);
}
void insertion_sort(int arr[100],int n)
{
int i, j, temp;
for (i = 1 ; i <= n - 1; i++)
{
j = i;
while ( j > 0 && arr[j-1] > arr[j])
{
temp = arr[j];
arr[j] = arr[j-1];
arr[j-1] = temp;
j--;
}
}
printf("Sorted list in ascending order:\n");
for (i = 0; i <= n - 1; i++)
{
printf("%d\t", arr[i]);
}
}
76
Output:
Enter number of elements
7
Enter 7 integers
1
4
2
6
3
8
5
Sorted list in ascending order:
1
2
3
4
5
6
8
77
47. Write a C program that sorts a given array of names
Aim: program that sorts a given array of names.
Program:
#include <stdio.h>
#include <string.h>
int main()
{
int i, j, num;
char name[20][10],t_name[15][10],temp[20];
printf("Please enter how many number of names to be sorted in alphabetical order\n");
scanf("%d", &num);
printf("Please enter %d names one by one\n", num);
for(i=0; i< num ; i++)
{
scanf("%s",name[i]);
strcpy (t_name[i], name[i]);
}
for(i=0; i < num-1 ; i++)
{
for(j=i+1; j< num; j++)
{
if(strcmp(name[i],name[j]) > 0)
{
strcpy(temp,name[i]);
strcpy(name[i],name[j]);
strcpy(name[j],temp);
}
}
}
printf("Names before sorting in alphabetical order\n");
for(i=0; i< num ; i++)
{
printf("%s\t",t_name[i]);
}
78
printf("\nNames after sorting in alphabetical order\n");
for(i=0; i< num ; i++)
{
printf("%s\t",name[i]);
}
}
Output:
Please enter how many number of names to be sorted in alphabetical order
5
Please enter 5 names one by one
rajesh
mahesh
manish
anish
suresh
Names before sorting in alphabetical order
rajesh mahesh manish anish suresh
Names after sorting in alphabetical order
anish mahesh manish rajesh suresh
79
Download