Programming For Problem Solving Lab Manual: Vaageswari College of Engineering
Programming For Problem Solving Lab Manual: Vaageswari College of Engineering
.
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
PROGRAMMING FOR
PROBLEM SOLVING
LAB MANUAL
[Note:The programs may be executed using any available Open Source/ Freely
available IDE Some 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]
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 form standard input.
a. Write a program for find the max and min from the three numbers.
b. Write the program for the simple, compound interest.
c. 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.
d. 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 ……………..
e. Write a program that shows the binary equivalent of a given positive number
between
0 to 255.
Expression Evaluation:
a. 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)).
b. 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)
c. Write a program that finds if a given number is a prime number
d. Write a C program to find the sum of individual digits of a positive integer and test
given number is palindrome.
e. 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.
f. Write a C program to generate all the prime numbers between 1 and n, where n is
a value supplied by the user.
g. Write a C program to find the roots of a Quadratic equation.
h. Write a C program to calculate the following, where x is a fractional value.
1-x/2 +x^2/4-x^3/6
i. 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.
Files:
a. Write a C program to display the contents of a file to standard output device.
b. Write a C program which copies one file to another, replacing all lowercase
characters with their uppercase equivalents.
c. 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.
d. Write a C program that does the following:
e. 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.
f. 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).
Strings:
a. Write a C program to convert a Roman numeral ranging from I to L to its decimal
equivalent.
b. Write a C program that converts a number ranging from 1 to 50 to Roman
equivalent
c. Write a C program that uses functions to perform the following operations:
d. To insert a sub-string in to a given main string from a given position.
e. ii. To delete n Characters from a given position in a given string.
f. 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.)
g. Write a C program that displays the position of a character ch in the string S or –
1 if S doesn„t contain ch.
h. 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 Key value in a
given List of integers using linear search method.
b. 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.
c. Write a C program that implements the Bubble sort method to sort a given list of
integers in ascending order.
d. Write a C program that sorts the given array of integers using selection sort in
descending order
e. Write a C program that sorts the given array of integers using insertion sort in
ascending order
f. Write a C program that sorts a given array of names
REQUIREMENTS
Hardware Requirements:
Processor Pentium IV and Above
RAM: 1 GB
Hard Disk 250 GB
Software Requirements:
Language: ANSI C Compiler with Supporting Editors
INTRODUCTION ABOUT C
History of C
ABOUT C LANGUAGE:
C is a programming language developed at AT&T‟s BELL Laboratory of USA in
1972. Dennis Ritchie designed it. Because of its reliability.
C is very popular. C stands between high-level languages (HLL) and Low Level
Language (LLL).
C‟s compactness and coherence is mainly due to the fact that it is a one-man
language.
C is highly portable & it is well suited for structured programming.
C program consists of collection of functions.
LINK SECTION
DEFINITION SECTION
}
SUBPROGRAM SECTION
User defined functions
1. Algorithm
Definition:
A method of representing the step – by – step logical procedure for solving a
problem in natural language (like English, etc. ) is called as algorithm.
Algorithm can also be defined as an ordered sequence of well-defined and effective
operations that, when executed, will always produce a result and eventually
terminate in a finite amount of time.
Properties of Algorithm:
Input / Output: Each algorithm can take zero. One or more input data and
must produce one or more output values.
Optimization: Unnecessary steps should be eliminated so as to make the
algorithm to terminate in finite number of steps.
Effectiveness: Each step must be effective in the sense that it should be
primitive (easily convertible into program statement) and can be performed
exactly in a finite amount of time.
Definiteness: Each step of the algorithm should be precisely and
unambiguously stated.
Step5: stop
2. Flowchart
Definition:
It is a diagrammatic representation of an algorithm. It is constructed using different
types Of boxes and symbols.
1. It is possible that the person who formulates the problem is not aware of the
k2details of programming. The programmer is not in a position to formulate the
problem. The flow chart acts as a link between the person who formulates the
problem and the programmer.
2. If the program written by one person is read by another, the job of understanding
the logic is made easier by reference to the flow chart. The flow chart helps the
programmer to modify the existing program.
3. Programming
A computer program is the list of instructions a computer follows in carrying out
its computations.
All the properties of an algorithm hold well, even for effective programming in addition
with the following one:
Repetitiveness: The program should be able to check the results for various
inputs in a single run. This are one of the key properties of good programming.
Example:
Question: Generate and print the first N terms of Fibonacci Series, where N is greater
than or equal to 1.
The Fibonacci series is 0, 1, 1, 2, 3, 5, 8, 13…
1. . Problem understanding:
In Fibonacci series only the first two numbers (0 and 1) are defined.
Each number, after the first, is derived from the sum of its two nearest
predecessors.
Therefore we can say that
New number = sum of last two numbers.
1 = 0+1
2 = 1+1
3 = 1+2
5 = 2+3
8 = 3+5
2. Problem Definition:
Define three variables one for new number and two for the last two numbers, as SUM,
A and B.
3. Algorithm development:
Step 1: Read the total number of required values in the series, N.
Step 2: Initialize the variables A and B to 0 and 1 respectively and SUM to 0.
Step 3: Also initialize a Counter I to 2.
Step 4: Compute the next value by adding A and B and store it in SUM.
Step 5: Display the value of SUM.
Step 6: Transfer the value of B to A and SUM to B.
Step 7: Increment the Counter I by 1.
Step 8: If the value of I is less than or equal to N, then go to step4, else go to
step 9.
Step 9: End of the program
KEYWORDS
C89 has 32 keywords (reserved words with special meaning):
auto, break, case, char, const, continue, default, do, double, else, enum,
extern, float, for, goto, if, int, long, register, return, short, signed, sizeof, static,
struct, switch, typedef, union, unsigned, void, volatile, and while.
Note: C99 adds five more keywords: inline, restrict, _Bool, _Complex, and
_Imaginary.
OPERATORS
C supports a rich set of operators, which are symbols used within an expression to
specify the manipulations to be performed while evaluating that expression.
arithmetic: +, -, *, /, %
assignment: =
augmented assignment: +=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=
bitwise logic: ~, &, |, ^
bitwise shifts: <<, >>
boolean logic: !, &&, ||
conditional evaluation: ? :
equality testing: ==, !=
calling functions: ( )
increment and decrement: ++ and --
Member selection: ., ->
object size: sizeof
order relations: <, <=, >, >=
reference and dereference: &, *, [ ]
sequencing: ,
sub expression grouping: ( )
type conversion: (typename)
#include <stdio.h>
void main()
{
int a,b,c=0,r=5,result=0;
clrscr();
printf("\n Enter a & b values:\n");
scanf("%d%d",&a,&b);
c = a+b;
printf("\n ARITHMETIC OPERATORS a+b = %d \n",c);
c = a-b;
printf("\n ARITHMETIC OPERATORS a-b = %d \n",c);
c = a*b;
printf("\n ARITHMETIC OPERATORS a*b = %d \n",c);
c=a/b;
printf("\n ARITHMETIC OPERATORS a/b = %d \n",c);
c=a%b;
printf("\n ARITHMETIC OPERATORS MODULO DIVISION a%b= %d \n",c);
printf("\n PREINCREMENT OPERATOR ++a = %d \n", ++a);
printf("\n PREDECREMENT OPERATOR--b = %d \n", --a);
printf("\n POST INCREMENT OPERATOR a++ = %d \n", a++);
printf("\n POST DECREMENT OPERATORa-- = %d \n", a--);
b = a;
printf("\n ASSIGNMENT OPERATOR b = %d \n", b);
b += a; // b = b+a
printf("\n ARITHMETIC ASSIGNMENT OPERATOR b = %d \n", b);
b -= a; // b = b-a
printf("\n ARITHMETIC ASSIGNMENT OPERATOR b = %d \n", b);
b *= a; // b = b*a
printf("ARITHMETIC ASSIGNMENT OPERATOR b = %d \n", b);
b /= a; // b = b/a
printf("\n ARITHMETIC ASSIGNMENT OPERATOR b = %d \n", b);
b %= a; // b = b%a
printf("\n ARITHMETIC ASSIGNMENT OPERATOR b = %d \n", b);
printf("\n RELATIONAL OPERATOR %d == %d = %d \n", a, b, a == b);
printf("\n RELATIONAL OPERATOR %d > %d = %d \n", a, b, a > b);
//RETURNS 1 FOR TRUE OR 0 FOR FALSE
printf("\n RELATIONAL OPERATOR %d < %d = %d", a, b, a < b);
printf("\n RELATIONAL OPERATOR %d != %d = %d \n", a, b, a != b);
printf("\n RELATIONAL OPERATOR %d >= %d = %d \n", a, b, a >= b);
printf("\n RELATIONAL OPERATOR %d <= %d = %d \n", a, b, a <= b);
result = (a == b) && (r > b);
OUTPUT:
CONDITIONAL OPERATOR= 0
BITWISE AND Output = 0
BITWISE OR Output = 4
ITWISE XOR Output = 4
SIZE OF OPERATOR int=4 bytes
b. Write a simple program that converts one given data type to another using
auto conversion and casting. Take the values form standard input.
A type cast is basically a conversion from one type to another. There are two types of
type conversion:
1. Implicit Type Conversion Also known as „automatic type conversion‟.
Done by the compiler on its own, without any external trigger from the user.
Generally takes place when in an expression more than one data type is
present. In such condition type conversion (type promotion) takes place to
avoid lose of data.
All the data types of the variables are upgraded to the data type of the variable
with largest data type.
Example:
bool -> char -> short int -> int ->
unsigned int -> long -> unsigned ->
long long -> float -> double -> long double
2. Explicit Type Conversion– This process is also called type casting and it is user
defined. Here the user can type cast the result to make it of a particular data type.
PROGRAM:
#include<stdio.h>
void main()
{
int x = 10,sum=0; // integer x
char y = 'a'; // character c
float z;
double w=1.2;
clrscr();
x = x + y;
getch();
}
OUTPUT:
#include<stdio.h>
void main()
{
int a,b,c;
clrscr();
printf("\n Enter three numbers:\n");
scanf("%d%d%d",&a,&b,&c);
if(a>b && a>c)
printf("\n Maximum number is a = %d",a);
else if(b>a && b>c)
printf("\n Maximum number is b = %d",b);
else
printf("\n Maximum number is c = %d",c);
if(a<b && a<c)
printf("\n Minimum number is a = %d",a);
else if(b<a && b<c)
printf("\n Minimum number is b = %d",b);
else
printf("\n Minimum number is c = %d",c);
getch();
}
OUTPUT:
#include<stdio.h>
#include<math.h>
void main()
{
int n;
float p,q,r,SI=0,CI=0;
clrscr();
printf("\n Enter the value of Principal p = ");
scanf("%f",&p);
printf("\n Enter the value of Rate r = ");
scanf("%f",&r);
printf("\n Enter the value of Period in year n = ");
scanf("%d",&n);
SI = ((p*r*n)/100);
printf("\n Simple Interest SI=%f \n",SI);
q = 1+(r/100);
CI=p*pow(q,n)-p;
printf("\n Compound Interest CI=%f \n",CI);
getch();
}
OUTPUT:
Enter the value of Principal p = 1000
Enter the value of Rate r = 12
Enter the value of Period in year n = 2
Simple Interest SI=240.000000
Compound Interest CI=254.400009
c. 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()
{
int num;
clrscr();
printf("\n Enter your percentage of marks:\n");
scanf("%d",&num);
printf(" \n You entered percentage of marks : %d", num); // printing outputs
if(num >= 70)
printf(" \n You got distinction "); // printing outputs
else if (( num >=60)&&(num<70))
printf(" \n You got First Class");
else if ( num >=40 && num<60)
printf(" \n You got Second Class");
else if ( num < 40)
printf(" \n You Failed in this exam");
getch();
}
OUTPUT:
d. 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>
void main()
{
int n, j,r=0;
clrscr();
printf("\n Enter a number:\n ");
scanf("%d",&n);
printf("\n Enter number of rows:\n ");
scanf("%d",&r);
for(j=1;j<=r;j++)
{
printf("\n %d * %d = %d ", n, j, n*j);
}
getch();
}
Output:
Enter a number:
5
Enter number of rows:
10
Multiplication table for a given=5
The number of rows in the table=10
The Multiplication Table is:
5x1=5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50
#include <stdio.h>
void main()
{
long num, decimal_num, remainder, base = 1, binary = 0;
clrscr();
printf("\n Enter a decimal integer(0-255): \n");
scanf("%ld", &num);
decimal_num = num;
while (num > 0)
{
remainder = num % 2;
binary = binary + remainder * base;
num = num / 2;
base = base * 10;
}
printf("\n Input number is = %d\n", decimal_num);
printf("\n Its binary equivalent is = %ld\n", binary);
getch();
}
Output:
EXPRESSION EVALUATION:
a. 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)).
Description:
The total distance travelled by vehicle in 't' seconds is given by distance = ut+1/2at2
where 'u' and 'a' are the initial velocity (m/sec.) and acceleration (m/sec2)
Algorithm:
Step 1: Start
Step 2: Read interval as integer
Step 3: for counter: 1 to interval increment counter by 1
begin
Read time, velocity, acceleration
Distance += (velocity * time + (accelerations * pow(time, 2)) / 2);
end
Step 4: Print Distance
Step 5: Stop
Program:
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int floor=10,h=3,u=0,s=0;
float a=9.8,t=0,temp,d;
clrscr();
s=floor*h;
d=u*t;
temp=(2*s-d)/a;
t=sqrt(temp);
printf("\n Time taken to reach ground=%fsec",t);
getch();
}
OUTPUT:
Time taken to reach ground= 2.474 sec
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int counter,time,i,t;
float a,distance,u,sum=0;
clrscr();
printf("Enter the total duration time: \n");
scanf("%d",&time);
printf("\n Enter the time internal:");
scanf("%d",&t);
i=time/t;
for(counter=1;counter<=1;counter++)
{
printf("\n Enter velocity:");
scanf("%f",&u);
printf("\n Enter acceleration:");
scanf("%f",&a);
distance=u*t+(a*pow(t,2)/2);
printf("Distance covered in round %d is %f",counter ,distance);
sum=distance;
}
printf("The total distance travelled: %f",sum);
getch();
}
b. 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)
Description:
To take the two integer operands and one operator from user to perform the some
arithmetic operations by using the following operators like: +,-,*, /, %
Ex: 2+3=5
Algorithm:
Step 1:
Start
Step 2:
Read x and y values
Step 3:
Read option + or – or * or / or %
Step 4:
If option is „+‟ res = x + y
Step 5:
If option is „-‟ res = x - y
Step 6:
If option is „*‟ res = x * y
Step 7:
If option is „/‟ res = x / y
Step 8:
If option is „%‟ res = x % y
Step 9:
If option does not match with + or – or * or / or %
Print select option +, -, *, /, /, % only
Step 10: Print x, option, y, res values
Step 11: Stop
Program:
#include <stdio.h>
#include <conio.h>
void main()
{
int a, b, c;
char ch;
clrscr() ;
printf("\n Enter your operator(+, -, /, *, %):\n");
scanf("%c", &ch);
printf("\n Enter the values of a and b:\n");
scanf("%d%d", &a, &b);
switch(ch)
{
case '+': c = a + b;
printf("\n addition of two numbers is: %d", c);
break;
case '-': c = a - b;
printf("\n substraction of two numbers is: %d", c);
break;
case '*': c = a * b;
printf("\n multiplication of two numbers is: %d", c);
break;
case '/': c = a / b;
printf("\n remainder of two numbers is: %d", c);
break;
case '%': c = a % b;
printf("\n quotient of two numbers is: %d", c);
break;
default: printf("\n Invalid operator");
break;
}
getch();
}
Output:
Enter you operator (+, -, /, *, %):
+
Enter the values of a and b:
1
3
addition of two numbers is: 4
#include <stdio.h>
void main()
{
int n, i, c = 0;
clrscr();
printf("\n Enter a positive integer: ");
scanf("%d",&n);
if (c==0)
printf("\n %d is a prime number.",n);
else
printf("\n %d is not a prime number.",n);
getch();
}
Output
Description:
Sum of the individual digits means adding all the digits of a number.
Ex: 123
sum of digits is 1+2+3 = 6
Palindrome number is such number which when reversed is equal to the original
number. For example: 121, 12321, 1001 etc.
#include <stdio.h>
void main()
{
int n, temp, r=0,sum=0, rev = 0;
clrscr();
printf("\n Enter an integer: \n");
scanf("%d", &n);
/* original number is stored at temp */
temp = n;
while (n > 0)
{
r = n % 10;
sum=sum+r; // sum of Individual Numbers
rev = rev * 10 + r;
num = n/10;
}
printf("\n Given number is = %d\n", temp);
printf(“\n Sum of individual digits of a given number is:%d”, sum);
printf("\n Its reverse is = %d\n", rev);
if (temp == rev)
printf("\n %d Number is a palindrome \n", temp);
else
printf("\n %d is Number is not a palindrome \n", temp);
getch();
}
Output
Enter an integer:
1234
Given number is=1234
Sum of individual digits of a given number is: 10
Its reverse is=4321
1234 is Number is not a palindrome
e. 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.
Description:
Algorithm:
Step 1: Start
Step 2: Read a, b, sum,n values as integers
Step 3: Set a as 0 and b as 1
Step 4: for counter: 2 to no increment counter by 1
begin
sum ← a + b;
Print sum
a ← b;
b ← sum;
end
Step 5: Stop
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a = 0, b = 1, n = 0, i, sum = 0;
clrscr();
printf("Enter the length of series: \n ");
scanf("%d", &n);
printf("\n Fibonacci series:\n");
printf("%d\t %d", a, b);
for(i = 2; i < n; i++)
{
sum = a + b;
printf(" \t%d",sum);
a = b;
b = sum;
}
getch();
}
Output:
Enter the length of series:
15
Fibonacci series:
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
f. Write a C program to generate all the prime numbers between 1 and n, where
n is a value supplied by the user.
Description:
Prime number is a number which is exactly divisible by one and itself only
Ex: 2, 3, 5, 7, ……… etc
Step 1: start
Step 2: read n
Step 3: initialize i = 1, c = 0
Step 4:if i <= n goto step 5
If not goto step 10
Step 5: initialize j = 1
Step 6: if j <= 1 do as the follow. If no goto step 7
i)if i%j == 0 increment c
ii) increment j
iii) goto Step 6
Step 7: if c == 2 print i
Step 8: increment i
Step 9: goto step 4
Step 10: stop
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int n, i, j, count;
clrscr();
printf("\n Prime no.series:\n");
printf("\n Enter any number: \n");
scanf("%d", &n);
printf("\n The prime numbers between 1 to %d\n", n);
printf(“\n The Prime Numbers are:\n”);
for(i = 1; i <= n; i++)
{
count = 0;
for(j = 1; j <=i; j++)
if(i % j == 0)
{
count++;
}
if(count == 2)
{
printf("%d\t", i);
}
}
getch();
}
Output:
Nature of roots of quadratic equation can be known from the quadrant = b2-4ac
If b2-4ac >0 then roots are real and unequal
If b2-4ac =0 then roots are real and equal
If b2-4ac <0 then roots are imaginary
Algorithm:
Step 1: Start
Step 2: Read A, B, C as integer
Step 3: Declare disc, deno, x1, x2 as float
Step 4: Assign disc = (B * B) - (4 * A * C)
Step 5: Assign deno = 2 * A;
Step 6: if( disc > 0 )
begin
Print “THE ROOTS ARE REAL ROOTS”
Assign x1 ← (-B / deno) + (sqrt(disc) / deno)
Assign x2 ← (-B / deno) - (sqrt(disc) / deno)
Print x1, x2
end
else if(disc = 0)
begin
Print “ THE ROOTS ARE REPEATED ROOTS"
Assign x1 ← -B / deno
Print x1
end
else Print “THE ROOTS ARE IMAGINARY ROOTS”
Step7: Stop
Program:
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
float a, b, c, d, root1, root2;
clrscr();
Program:
#include <stdio.h>
void main()
{
float x,sum=1,t=1,d;
int i,n;
clrscr();
printf("\n Input the Value of x :\n ");
scanf("%f", &x);
printf("\n Input the number of terms :\n ");
scanf("%d", &n);
for (i=1;i<n;i++)
{
d = (2*i)*(2*i-1);
t = -t*x*x/d;
sum =sum+ t;
}
printf("\nthe sum = %f\nNumber of terms = %d\nvalue of x = %f\n",sum,n,x);
getch();
}
Output:
Input the Value of x : 2
Input the number of terms : 5
i. 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.
Program:
#include <stdio.h>
#include<math.h>
void main()
{
int x,n,sum=1,i;
clrscr();
printf("\n Enter the Value of x :\n ");
scanf("%d", &x);
printf("\n Enter the number of terms :\n ");
scanf("%d", &n);
for (i=1;i<=n;i++)
{
sum =sum+pow(x,i);
}
printf("\n The sum of this geometric progression: 1+x+x^2+x^3+…+x^n.=%d”,sum);
getch();
}
Output:
Enter the Value of x: 2
Enter the number of terms: 5
Program:
#include <stdio.h>
void main()
{
int arr[50];
int i, max, min, size,sum=0;
float avg=0;
clrscr();
printf("\n Enter size of the array:\n ");
scanf("%d", &size);
printf("\n Enter elements in the array:\n ");
for(i=0; i<size; i++)
{
scanf("%d", &arr[i]);
}
avg=sum/size;
printf("\nMaximum element = %d\n", max);
printf("\n Minimum element = %d\n", min);
printf("\n Sum =%d and Average = %f\n", sum, avg);
getch();
}
Description:
Program:
#include <stdio.h>
#include <math.h>
#define Max_Arr 50
void sortarr(float arr[], int n);
float mean_value(float arr[],int n);
float variance_value(float arr[], int n);
float var_stdDev(float var);
void main()
{
int n= 0;
float array[Max_Arr];
int i=0;
float avg=0;
float variance=0;
float stdev=0;
clrscr();
printf("\n How many numbers do you wish to enter (Max of 20):\n");
scanf("%d",&n);
avg=mean_value(array,n);
printf("\n The Meanvalue is:%.2f\n\n",avg);
variance=variance_value(array,n);
printf("\nThe Variance Valueis:%.2f\n\n",variance);
stdev=var_stdDev(variance);
printf("\nThe standard deviation is:%.2f\n\n",stdev);
sortarr(array,n);
getch();
}
float avg;
float sum;
for(i=0;i<n;i++)
{
sum+=arr[i];
}
avg = (sum/n);
return avg;
}
int i;
float var=0,sum1=0,avg=0;
avg=mean_value(arr,n);
float stdDev;
stdDev=sqrt(var); //To calculate Standard Deviation
return stdDev;
}
OUTPUT:
#include<stdio.h>
#include<conio.h>
{
for(j=1;j<=col;j++)
{
m3[i][j] = (m1[i][j] + m2[i][j]);
}
}
}
void main()
{
int m1[10][10],m2[10][10],m3[10][10],row,col;
clrscr();
printf("Enter number of rows :");
scanf("%d",&row);
printf("Enter number of colomns :");
scanf("%d",&col);
read_arr(m1,row,col);
printf("\n THE A MATRIX ELEMENTS:\n");
print_arr(m1,row,col);
read_arr(m2,row,col);
printf("\n THE B MATRIX ELEMENTS:\n");
print_arr(m2,row,col);
add_arr(m1,m2,m3,row,col);
printf("\n MATRIX ADDITION\n");
print_arr(m3,row,col);
mul_arr(m1,m2,m3,row,col);
printf("\n MATRIX MULTIPLICATION:\n");
print_arr(m3,row,col);
printf("\n Transpose of MATRIX\n");
transpose(m3,row,col);
getch();
}
OUTPUT:
Description:
Algorithm:
Step 1: Start
Step 2: Read n value as integer
Step 3: Call function factorial (int n)
Step 4: End
Call function factorial(int n)
begin
if (n = 0)
return 1;
else
return (n * factorial(n - 1));
end
Program:
#include <stdio.h>
#include <conio.h>
long int recfactorial(long int x);
long int nonrecfactorial(long int x);
void main()
{
long int n, a, b;
clrscr();
printf("\n Enter any number:\n");
scanf("%ld", &n);
a = recfactorial(n);
printf("\n The factorial of number using recursion :%ld=%ld \n",n,a);
b = nonrecfactorial(n);
printf("\n The factorial of number using nonrecursion :%ld=%ld ",n,b);
getch();
}
{
f = x * recfactorial(x - 1);
return(f);
}
}
ii. To find the GCD (greatest common divisor) of two given integers.
NOTE: In order to find the Greatest Common Divisor, we have to pass at least one
non-zero value.
Algorithm:
Step 1: Start
Step 2: Read a, b values as integers
Program:
#include <stdio.h>
#include <conio.h>
int recgcd(int x, int y);
int nonrecgcd(int x, int y);
void main()
{
int a, b, c, d;
clrscr();
printf("\n Enter two numbers a, b:\n");
scanf("%d%d", &a, &b);
c = recgcd(a, b);
printf("\n The gcd of two numbers using recursion: %d and %d is
%d\n",a,b,c);
d = nonrecgcd(a, b);
printf("The gcd of two numbers using nonrecursion:%d and %d is %d\n",a,b,d);
getch();
}
#include<stdio.h>
#include<conio.h>
#include<math.h>
/* Power function declaration */
double power(double x, int y);
double powerrec(double num, int power);
void main()
{
int x, n;
double result;
clrscr();
printf("\n Enter any number:\n ");
scanf("%d", &x);
printf("\n Enter power of the number:\n ");
scanf("%d", &n);
result = powerrec(x, n); //Calls power function
printf("\n With recursion %d raised to %d = %.2f\n", x, n, result);
printf("\n Without recursion %d raised to %d = %.2f\n", x, n, power(x,
n));
getch ();
}
double powerrec(double num, int result)
{
if(result == 0)
return 1;
return num * pow(num, result-1);
}
return pow(x,y);
}
OUTPUT
Enter any number:
5
Enter power of the number:
2
With recursion 5 raised to 2 =25.000000
Without recursion 5 raised to 2 = 25.000000;
e. Write a program for reading elements using pointer into array and display
the values using array.
#include<stdio.h>
#include<conio.h>
void main()
{
int a[50],*p,i,n;
clrscr();
p=a;
printf(“\n Enter size of array:\n ”);
scanf(“%d”,&n);
printf(“\n Enter elements of array:\n”);
for(i=0;i<n;++i)
scanf(“%d”,p+i);
printf(“\n The array Elements are:\n”);
for(i=0;i<n;++i)
printf(“\t%d “,*(p+i));
getch();
}
f. Write a program for display values reverse order from array using pointer
#include <stdio.h>
void main()
{
int n, i, arr1[15];
int *pt;
clrscr();
printf("\n\n Pointer : Print the elements of an array in reverse order :\n");
printf("----------------------------------------------------------------\n");
pt = &arr1[n - 1];
Output:
Pointer : Print the elements of an array in reverse order :
----------------------------------------------------------------
Enter the size of an array:
5
Enter 5 integers into array:
Element : 1 is :2
Element : 2 is :3
Element : 3 is :4
Element : 4 is :5
Element : 5 is :6
Element : 2 is :3
Element : 1 is :2
#include<stdio.h>
void main()
{
int array[5];
int i,n, sum=0;
int *ptr;
clrscr();
printf(" \n Enter the size of an array:\n ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
//*ptr refers to the value at address
sum = sum + *ptr;
ptr++;
}
FILES:
Description:
This program takes the number from user and stores in file. After you compile and
run this program, you can see a text file program.txt created in C drive of your
computer. When you open that file, you can see the integer you entered.
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char ch;
clrscr();
fp=fopen(“one.txt”, “w”);
printf(“\n Enter Data press Ctrl+Z:\n”);
while( ( ch=getchar() )!=EOF)
{
putc(ch,fp);
}
fclose(fp);
fp=fopen(“one.txt”, “r”);
printf(“\n The output data is:\n”);
while( ( ch=getc(fp) )! = EOF)
printf(“%c”, ch);
fclose(fp);
getch();
}
OUTPUT:
Enter Data press Ctrl+Z:
This is cp class^z
The output data is:
This is cp class
b. Write a C program which copies one file to another, replacing all lowercase
characters with their uppercase equivalents.
#include<stdio.h>
#include<ctype.h>
#include<process.h>
void main()
{
char ch;
FILE *fp1, *fp2;
clrscr();
fp1=fopen("one.txt", "w");
printf("\n Enter Data press Ctrl+Z:\n");
while((ch=getchar())!=EOF)
putc(ch,fp1);
fclose(fp1);
fp1 = fopen("one.txt","r");
fp2=fopen("two.txt","w");
while ((ch=fgetc(fp1))!= EOF)
{
fputc(ch,fp2);
}
printf("\n File successfully copied..");
fclose(fp2);
fp2=fopen("two.txt","r");
printf("\n The content of TWO File is:\n");
while((ch=getc(fp2))!=EOF)
printf("%c",ch);
fclose(fp1);
fp2=fopen("two.txt","r");
printf("\n The text in UPPER CASE:\n");
while((ch=getc(fp2))!=EOF)
{
ch=toupper(ch);
printf("%c",ch);
}
fcloseall();
getch();
}
OUTPUT:
Enter Data press Ctrl+Z:
This is pps class^z
File successfully copied
The content of TWO File is
This is pps class
The text in UPPER CASE:
THIS IS PPS CLASS
These are the parameters supplied to a program, when the program is invoked.
This parameter may represent a file name that the program should process.
Command line arguments are typed by the user. The first argument is always
the file name.
We know that, every C program should have one main function and it can
take arguments like other functions. If we want to work with command line
arguments, the main function can take 2 arguments called argc and argv and
the information contained in the command line is processed onto the program
through these command line arguments.
The variable argc is an argument counter that counts No of arguments on the
command line. The argument argv is an argument vector that represents an
array of character pointers those points to the command line arguments. The
size of this array is equal to the value of argc.
Syntax:
output:
c:\tc\bin\ copy con f1.txt
hello world program
this is malla reddy institute of engineering and Technology
c:\tc\bin\13a f1.txt p
character p occurred 2 times
c:\tc\bin\13a f1.txt o
#include<stdio.h>
/* Our structure */
struct rec
{
int x,y,z;
};
void main()
{
int counter;
FILE *ptr_myfile;
struct rec my_record;
ptr_myfile=fopen("test.bin","wb");
if (!ptr_myfile)
{
printf("Unable to open file!");
return 1;
}
for ( counter=1; counter <= 10; counter++)
{
my_record.x= counter;
fwrite(&my_record, sizeof(struct rec), 1, ptr_myfile);
}
fclose(ptr_myfile);
getch();
}
e. 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).
Open both source files in r (read) and destination file in w (write) mode.
Copy file contents from both source files one by one to destination file.
Close all files to save and release all resources.
Let the given two files be file1.txt and file2.txt. The following are steps to merge.
To successfully run the below program file1.txt and fil2.txt must exist in same
folder.
#include <stdio.h>
#include <stdlib.h>
void main()
{
// Open two files to be merged
FILE *fp1 = fopen("file1.txt", "r");
FILE *fp2 = fopen("file2.txt", "r");
fp3=fopen(“file3.txt”,”r”);
printf(“\n The third file content is:\n);
while((ch=getc(f3))!=EOF)
printf(“%c”,ch);
fclose(fp1);
fclose(fp2);
fclose(fp3);
getch();
}
Output:
SYMBOL VALUE
I 1
IV 4
V 5
IX 9
X 10
XL 40
L 50
XC 90
C 100
CD 400
D 500
CM 900
M 1000
#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;
Output:
Enter the roman number
XIV
Decimal equivalent is 14
#include <stdio.h>
char romanval[1000];
int i = 0;
int main()
{
int j;
long number;
{
if (number < (10 + 3 * 10))
{
postdigit('X', number / 10);
number = number - (number / 10) * 10;
}
else
{
predigit('X','L');
number = number - (50 - 10);
}
}
else if (number >= 5)
{
if (number < (5 + 4 * 1))
{
postdigit('V', number / 5);
number = number - (number / 5) * 5;
}
else
{
predigit('I', 'X');
number = number - (10 - 1);
}
}
else if (number >= 1)
{
if (number < 4)
{
postdigit('I', number / 1);
number = number - (number / 1) * 1;
}
else
{
predigit('I', 'V');
number = number - (5 - 1);
}
}
}
printf("Roman number is: ");
for(j = 0; j < i; j++)
printf("%c", romanval[j]);
return 0;
}
Output:
Program Explanation
Program:
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char str1[20], str2[20];
int len1, len2, n, i;
clrscr();
puts("Enter the string 1\n");
gets(str1);
len1 = strlen(str1);
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
Program:
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char str[20];
int i, n, len, 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);
len = strlen(str);
for(i = pos + n; i < len; i++)
{
str[i - n] = str[i];
}
str[i - n] = '\0';
printf("The string is %s", str);
getch();
}
OUTPUT
Program:
#include <stdio.h>
#include <string.h>
void main()
{
char a[100], b[100];
strcpy(b,a);
strrev(b);
if (strcmp(a,b) == 0)
printf("\n %c is string is a palindrome.\n",a);
else
printf("\n %c is string isn't a palindrome.\n",a);
getch();
}
Output:
Enter a string to check if it is a palindrome:
madam
Algorithm:
Step 1: Start
Step 2: read the string and then displayed
Step 3: read the string to be searched and then displayed
Step 4: searching the string T in string S and then perform the following steps
i. found = strstr(S, T)
ii. if found print the second string is found in the first string at the position. If
not goto step5
Step 5: print the -1
Step 6: Stop
Program:
#include<stdio.h>
#include<string.h>
#include<conio.h>
void main()
{
char s[30], t[20];
char *found;
clrscr();
puts("Enter the first string: ");
gets(s);
puts("Enter the string to be searched: ");
gets(t);
found = strstr(s, t);
if(found)
{
printf("Second String is found in the First String at %d position.\n", found - s);
}
else
{
printf("-1");
}
getch();
}
Output:
1.Enter the first string:
kali
Enter the string to be searched:
li
second string is found in the first string at 2 position
f. Write a C program to count the lines, words and characters in a given text.
Algorithm:
Step 1: Start
Step 2: Read the text until an empty line
Step 3: Compare each character with newline char „\n‟ to count no of lines
Step 4: Compare each character with tab char „\t\‟ or space char „ „ to count no of
words
Step 5: Compare first character with NULL char „\0‟ to find the end of text
Step 6: No of characters = length of each line of text
Step 7: Print no of lines, no of words, no of chars
Step 8: Stop
Program:
#include <stdio.h>
#include <conio.h>
#include <string.h>
void main()
{
char str[100];
int i = 0, l = 0, f = 1;
clrscr();
puts("Enter any string\n");
gets(str);
for(i = 0; str[i] !='\0'; i++)
{
l = l + 1;
}
printf("The number of characters in the string are %d\n", l);
for(i = 0; i <= l-1; i++)
{
if(str[i] == ' ')
{
f = f + 1;
}
}
printf("The number of words in the string are %d", f);
getch();
}
Output :
Enter any string
abc def ghi jkl mno pqr stu vwx yz
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.
#include<stdio.h>
#include<conio.h>
void smallest(int arr[],int n);
void largest(int arr[],int n);
void sum(int arr[],int n);
void average(int arr[],int n);
void main()
{
int choice, n, i,arr[100];
clrscr();
printf ("\t**************************");
printf("\n\t* MENU ");
printf("\n\t* ***********************");
printf("\n\t* 1. SMALLEST *");
printf("\n\t* 2. LARGEST *");
printf("\n\t* 3. SUM *");
printf("\n\t* 4. AVERAGE *");
printf("\n\t 5. EXIT *");
printf("\n\t *************************");
printf("\n Enter the N Value ( i.e 5 to 10):\n");
scanf("%d",&n);
printf("\n Enter %d Elements:\n",n);
for(i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}
do
{
printf("\nEnter your choice?(1 to 4):\n");
scanf("%d",&choice);
switch(choice)
{
case 1:
smallest(arr,n);
break;
case 2:
largest(arr,n);
break;
case 3:
sum(arr,n);
break;
case 4:
average(arr,n);
break;
case 5:
exit(0);
break;
default:
printf("\n An invalid choice is entered\n");
break;
}
}while(choice<5);
getch();
}
{
int sum=0,i;
for(i=0;i<n;i++)
{
sum=sum+arr[i];
}
printf("\n sum=%d",sum);
}
OUTPUT:
**************************
MENU
* ************************
1. SMALLEST
2. LARGEST
3. SUM
4. AVERAGE
5. EXIT
**************************
#include <stdio.h>
void main()
{
int i, j, rows;
clrscr();
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");
}
getch();
}
OUTPUT:
Enter number of rows: 4
1
12
123
1234
PROGRAM:
#include <stdio.h>
void main()
{
int i, j, rows;
clrscr();
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");
}
getch();
}
OUTPUT:
Enter number of rows: 4
1
22
333
4444
Program:
#include <stdio.h>
void main()
{
int i, j, rows;
clrscr();
printf("Enter number of rows: ");
scanf("%d",&rows);
for(i=1; i<=rows; ++i)
{
for(j=1; j<=i; ++j)
{
printf("* ");
}
printf("\n");
}
getch();
}
OUTPUT:
Enter number of rows: 4
*
**
***
****
PROGRAM:
#include <stdio.h>
void main()
{
int rows, i, j, number= 1;
clrscr();
PROGRAM:
#include <stdio.h>
void main()
{
int i, j, rows;
clrscr();
printf("\n 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
*
* *
* **
* ***
* **
* *
*
The linear search is most simple searching method. It does not expect the list
To be sorted. The key which is to be searched is compared with each element
of the list one by one. If a match exists, the search is terminated. If the end of
list is reached it
If the search has failed and key has no matching in the list.
Algorithm:
1. Start
5. search<--linear(a,n,x)
9. stop
Program:
#include <stdio.h>
void main()
{
long array[100], search, i, n, position;
clrscr();
printf("\n Entered N values:\n");
scanf("%ld", &n);
printf("\n Entered %d numbers:\n", n);
for (i= 0; i < n; i++)
scanf("%ld", &array[i]);
printf("\n Enter number to search: \n");
scanf("%ld", &search);
position = linear_search(array, n, search);
if (position == -1)
printf("%ld isn't present in the array.\n", search);
else
printf("%ld is present at location %ld.\n", search, position+1);
getch();
}
OUTPUT
Enter N value: 5
Entered 5 numbers:
2
5
1
6
4
Enter number to search: 6
6 is present at location 4.
b. 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.
Description:
Binary search is a vast improvement over the sequential search.
For binary search to work, the item in the list must be in assorted order.
The approach employed in the binary search is divide and conquer.
If the list to be sorted for a specific item is not Sorted, binary search fails.
ALGORITHM:
BINARY SEARCH
1. Start
2. Read the value of n
3. for i=1 to n increment in steps of 1
Read the value of ith element into array
4. Read the element(x) to be searched
5. search<--binary(a,n,x)
6. if search equal to 0 goto step 7 otherwise goto step 8
7. print unsuccessful search
8. print successful search
9. stop
1. start
2. initialise low to 1 ,high to n, test to 0
3. if low<= high repeat through steps 4 to 9 otherwise goto step 10
PROGRAM:
#include<stdio.h>
#include<conio.h>
int BinarySearching(int arr[20], int max, int element)
{
int low = 0, high = max - 1, middle;
while(low <= high)
{
middle = (low + high) / 2;
if(element > arr[middle])
low = middle + 1;
else if(element < arr[middle])
high = middle - 1;
else
return middle;
}
return -1;
}
void main()
{
int i,j,element,temp,n, arr[50], position;
clrscr();
printf("\n Enter the N vaule of an array:");
scanf("%d", &n);
printf("\n Enter %d Elements in Array: \n",n);
for(i = 0;i<n;i++)
scanf("%d",&arr[i]);
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(arr[i]>arr[j])
{
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}
printf("\nthe array in sorted order:-\n");
for(i=0;i<n;i++)
printf("%d\n",arr[i]);
printf("\n Enter Element to Search:");
scanf("%d", &element);
position = BinarySearching(arr,n, element);
if(position == -1)
printf("Element %d Not Found\n", element);
else
OUTPUT:
Enter the N vaule of an array: 5
Enter 5 Elements in Array:
6
9
8
7
4
The array in sorted order:
4
6
7
8
9
Enter number to search:6
c. Write a C program that implements the Bubble sort method to sort a given
list of integers in ascending order.
Description:
Algorithm:
Bubble
Sort:
1. start
2. read the value of n
3. for i= 1 to n increment in steps of 1
Read the value of ith element into array
4. call function to sort (bubble_sort(a,n))
5. for i= 1 to n increment in steps of 1
print the value of ith element in the array
6. stop
PROGRAM:
#include <stdio.h>
void main()
{
int data[100],i,n,j,temp;
clrscr();
printf("\n Enter the number of elements to be sorted:\n ");
scanf("%d",&n);
for(i=0;i<n;++i)
{
printf("\n %d. Enter element: ",i+1);
scanf("%d",&data[i]);
}
for(j=0;j<n-1;++j)
for(i=0;i<n-j-1;++i)
{
if(data[i]>data[i+1]) //To sort in descending order, change > to < in
this line. {
temp=data[i];
data[i]=data[i+1];
data[i+1]=temp;
}
}
printf("\n In ascending order:\n");
for(i=0;i<n;++i)
printf("%d\t",data[i]);
getch();
}
OUTPUT:
Enter the number of elements to be sorted: 6
1. Enter element: 12
2. Enter element: 3
3. Enter element: 0
4. Enter element: -3
5. Enter element: 1
6. Enter element: -9
d. Write a C program that sorts the given array of integers using selection sort
in descending order
Description:
Selection sort algorithm starts by comparing first two elements of an array and
swapping if necessary, i.e., if you want to sort the elements of array in
ascending order and if the first element is greater than second then, you need
to swap the elements but, if the first element is smaller than second, leave the
elements as it is. Then, again first element and third element are compared
and swapped if necessary. This process goes on until first and last element of
an array is compared. This completes the first step of selection sort.
If there are n elements to be sorted then, the process mentioned above should
be repeated n-1 times to get required result. But, for better performance, in
second step, comparison starts from second element because after first step,
the required number is automatically placed at the first (i.e, In case of sorting
in ascending order, smallest element will be at first and in case of sorting in
descending order, largest element will be at first.). Similarly, in third step,
comparison starts from third element and so on.
PROGRAM:
#include <stdio.h>
void main()
{
int data[100],i,n,j,temp;
clrscr();
printf("\n Enter the number of elements to be sorted:\n ");
scanf("%d",&n);
for(i=0;i<n;++i)
{
for(j=0;j<n;++j)
for(i=j+1;i<n;++i)
{
if(data[j]<data[i]) //To sort in ascending order, change < to >
{
temp=data[j];
data[j]=data[i];
data[i]=temp;
}
}
printf("\n The Elements in descending order:\n");
for(i=0;i<n;++i)
printf("%d\t",data[i]);
getch();
}
OUTPUT:
Enter the number of elements to be sorted: 5
1. Enter element: 12
2. Enter element: 1
3. Enter element: 23
4. Enter element: 2
5. Enter element: 4
e. Write a C program that sorts the given array of integers using insertion sort
in ascending order
EXPLANATION:
Step 1: The second element of an array is compared with the elements that appear
before it (only first element in this case). If the second element is smaller than
first element, second element is inserted in the position of first element. After
first step, first two elements of an array will be sorted.
Step 2: The third element of an array is compared with the elements that appears
before it (first and second element). If third element is smaller than first
element, it is inserted in the position of first element. If third element is larger
than first element but, smaller than second element, it is inserted in the
position of second element. If third element is larger than both the elements, it
is kept in the position as it is. After second step, first three elements of an
array will be sorted.
Step 3: Similarly, the fourth element of an array is compared with the elements that
appear before it (first, second and third element) and the same procedure is
applied and that element is inserted in the proper position. After third step,
first four elements of an array will be sorted. If there are n elements to be
sorted. Then, this procedure is repeated n-1 times to get sorted list of array.
PROGRAM:
#include<stdio.h>
void main()
{
int data[100],n,temp,i,j;
clrscr();
printf("\n Enter number of terms:\n");
scanf("%d",&n);
printf("\n Enter elements:\n ");
for(i=0;i<n;i++)
scanf("%d",&data[i]);
printf("\n The Entered Elements are:\n");
for(i=0;i<n;i++)
printf("%d\t",data[i]);
for(i=1;i<n;i++)
{
temp = data[i];
j=i-1;
while (temp<data[j] && j>=0) /*To sort elements indescending order,
change*/
{ //temp<data[j] to temp>data[j] in above
line.
data[j+1] = data[j];
--j;
}
data[j+1]=temp;
}
OUTPUT:
PROGRAM:
#include<stdio.h>
#include<string.h>
void main()
{
int i,j,count;
char str[25][25],temp[25];
clrscr();
printf("\n How many strings u are going to enter?: \n ");
scanf("%d",&count);
printf("\n Enter Strings one by one:\n ");
for(i=0;i<=count;i++)
gets(str[i]);
for(i=0;i<=count;i++)
for(j=i+1;j<=count;j++)
{
if(strcmp(str[i],str[j])>0)
{
strcpy(temp,str[i]);
strcpy(str[i],str[j]);
strcpy(str[j],temp);
}
}
printf("\n Order of Sorted Strings:\n ");
for(i=0;i<=count;i++)
puts(str[i]);
getch();
}
OUTPUT:
How many strings u are going to enter?:
5
Enter Strings one by one:
Harshitha
Rithvik
Advith
Arush
Surya
Order of Sorted Strings:
Advith
Arush
Harshitha
Rithvik
Surya