0% found this document useful (0 votes)
2K views

Programming For Problem Solving Lab Manual: Vaageswari College of Engineering

This document contains the syllabus and lab manual for the Programming for Problem Solving lab course for the first year of the B.Tech program. It outlines the course objectives, outcomes, and lists various programming problems and exercises that students should practice in areas like operators, data types, expressions, arrays, pointers, functions, files, strings, and sorting/searching algorithms. Students will learn to formulate and solve problems by writing correct C programs using concepts like control flow, data manipulation, modularization, and I/O. They will practice debugging and testing programs using appropriate IDE tools.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2K views

Programming For Problem Solving Lab Manual: Vaageswari College of Engineering

This document contains the syllabus and lab manual for the Programming for Problem Solving lab course for the first year of the B.Tech program. It outlines the course objectives, outcomes, and lists various programming problems and exercises that students should practice in areas like operators, data types, expressions, arrays, pointers, functions, files, strings, and sorting/searching algorithms. Students will learn to formulate and solve problems by writing correct C programs using concepts like control flow, data manipulation, modularization, and I/O. They will practice debugging and testing programs using appropriate IDE tools.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 75

I - B.

TECH PPS LAB MANUAL 1

.
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

PROGRAMMING FOR
PROBLEM SOLVING
LAB MANUAL

VAAGESWARI COLLEGE OF ENGINEERING


(affiliated to JNTUH Approved by A.I.C.T.E)
Beside L.M.D Police Station,
Thimmapur, Karimnagar

VAAGESWARI COLLEGE OF ENGINEERING DEPARTMENT OF CSE


I - B.TECH PPS LAB MANUAL 2

B.Tech. I Year Syllabus JNTU HYDERABAD

JAWAHARLAL NEHRU TECHNOLOGICAL UNIVERSITY HYDERABAD


B.Tech. 1st Year Syllabus (w.e.f AY 2018-19)

CS106ES/CS206ES: PROGRAMMING FOR PROBLEM SOLVING LAB


B.Tech. I Year I Sem. L T P C
3 1 0 1.5

[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]

Course Objectives: The students will learn the following:


 To work with an IDE to create, edit, compile, run and debug programs
 To analyze the various steps in program development.
 To develop programs to solve basic problems by understanding basic
concepts in C like operators, control statements etc.
 To develop modular, reusable and readable C Programs using the concepts
like functions, arrays etc.
 To write programs using the Dynamic Memory Allocation concept.
 To create, read from and write to text and binary files

Course Outcomes: The candidate is expected to be able to:


 formulate the algorithms for simple problems
 translate given algorithms to a working and correct program
 correct syntax errors as reported by the compilers
 identify and correct logical errors encountered during execution
 represent and manipulate data with arrays, strings and structures
 use pointers of different types
 create, read and write to and from simple text and binary files
 modularize the code with functions so that they can be reused

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.

VAAGESWARI COLLEGE OF ENGINEERING DEPARTMENT OF CSE


I - B.TECH PPS LAB MANUAL 3

Simple numeric problems:

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.

Arrays, Pointers and Functions:


a. Write a C program to find the minimum, maximum and average in an array of
integers.
b. Write a functions to compute mean, variance, Standard Deviation, sorting of n
elements in single dimension array.
c. Write a C program that uses functions to perform the following:

VAAGESWARI COLLEGE OF ENGINEERING DEPARTMENT OF CSE


I - B.TECH PPS LAB MANUAL 4

i. Addition of Two Matrices


ii. Multiplication of Two Matrices
iii. Transpose of a matrix with memory dynamically allocated for the new
matrix as row and column counts may not be same.
d. Write C programs that use both recursive and non-recursive functions
i. To find the factorial of a given integer.
ii. To find the GCD (greatest common divisor) of two given integers.
iii. To find x^n
e. Write a program for reading elements using pointer into array and display the
values using array.
f. Write a program for display values reverse order from array using pointer.
g. Write a program through pointer variable to sum of n elements from array.

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.

VAAGESWARI COLLEGE OF ENGINEERING DEPARTMENT OF CSE


I - B.TECH PPS LAB MANUAL 5

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

Suggested Reference Books for solving the problems:

i. Byron Gottfried, Schaum‟s Outline of Programming with C, McGraw-Hill


ii. B.A. Forouzan and R.F. Gilberg C Programming and Data Structures, Cengage
Learning, (3rd Edition)
iii. Brian W. Kernighan and Dennis M. Ritchie, The C Programming Language,
Prentice
iv. Hall of India
v. R.G. Dromey, How to solve it by Computer, Pearson (16th Impression)
vi. Programming in C, Stephen G. Kochan, Fourth Edition, Pearson Education.
vii. Herbert Schildt, C: The Complete Reference, Mc Graw Hill, 4th Edition

VAAGESWARI COLLEGE OF ENGINEERING DEPARTMENT OF CSE


I - B.TECH PPS LAB MANUAL 6

INSTRUCTIONS FOR STUDENTS


These are the instructions for the students while attending the lab:
 Before entering the lab the student should carry the following
things(mandatory)
1. Identity card issued by the college
2. Class notes
3. Lab observation book
4. Lab manual
5. Lab Record
 Student must sign in and sign out in the register provided when attending the
lab session without fail
 Come to the lab in time. Students, who are late more than 15 min.,will not be
allowed to attend the lab
 Students need to maintain 100% attendance in lab.
 All students must follow a Dress code while in the lab.
 Foods, drinks are not allowed
 All bags must be left at the indicated place
 Workspace must be kept clean and tidy after experiment is completed
 Read the manual carefully before coming to the lab and be sure about what
you are supposed to do
 Do the experiments as per the instructions given in the manual
 Copy all the programs to observation which are taught in clas before attending
the lab session
 Students are not supposed to use CD,DVD or PENDRIVES without permission
of lab-In charge
 Lab records need to be submitted on or before the date of submission

REQUIREMENTS

Hardware Requirements:
Processor Pentium IV and Above
RAM: 1 GB
Hard Disk 250 GB

Software Requirements:
Language: ANSI C Compiler with Supporting Editors

VAAGESWARI COLLEGE OF ENGINEERING DEPARTMENT OF CSE


I - B.TECH PPS LAB MANUAL 7

INTRODUCTION ABOUT C

History of C

The milestones in C's development as a language are listed below:

 UNIX developed c. 1969 -- DEC PDP-7 Assembly Language.


 BCPL – (Basic Combined Programming Languaue) Developed by Martin
Richards in 196, Primarily for Writing System Software.
 1970 Ken Thampson developes a new language ``B‟‟.
 Both BCPL and B ware “Typeless” and System Programming langaues.
 Using ALGOL, BCPL and B languages in 1972 Dennis Ritchie developed a
language in AT&T‟s Bell Laboratories Called as „C‟ Language.
 By 1973 UNIX OS almost totally written in ``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.

STRUCTURE OF ‘C’ PROGRAM :


Each instruction in a C program is written as a separate statement. The
program starts with a main function followed by the opening braces which
indicates the start of the function then the variable and constant declarations
followed by the statements, which includes input and output statements.
C program may contain one or more sections as shown below.
 DOCUMENTATION SECTION

 LINK SECTION

 DEFINITION SECTION

 GLOBAL DECLARATION SECTION

main() Function section


{
Declaration part
Executable part

VAAGESWARI COLLEGE OF ENGINEERING DEPARTMENT OF CSE


I - B.TECH PPS LAB MANUAL 8

}
SUBPROGRAM SECTION
User defined functions

PROGRAM DEVELOPMENT STEPS


To develop the program in high level language and translate into machine level
language we are having following steps.
1) Writing and editing the program
2) Compiling the program
3) Linking the program with the required library modules
4) Executing the program

PROGRAM DEVELOPMENT TOOLS

Program Development Tools


There are three stages in the program development-
1. Algorithm development
2. Flowchart representation,
3. Programme.

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.

Note: Algorithm written in English language is called Pseudo code.


On the whole an algorithm is a recipe for finding a right answer to a problem by
breaking it down into simple steps.

Properties of Algorithm:

 Finiteness :- It terminates with finite no of steps


 Definiteness:- each step of algorithm is exactly defined
 Effectiveness:-All the operations used in the algorithm can be performed
exactly in a fixed duration of time
 Input:-An algorithm must have an input before the execution of program
begins
 Output:- An algorithm has one or more outputs after the execution

Properties an Algorithm should possess:


 Generality: The algorithm must be complete in itself so that it can be also used
to solve all problems of a specific type for any input data.

VAAGESWARI COLLEGE OF ENGINEERING DEPARTMENT OF CSE


I - B.TECH PPS LAB MANUAL 9

 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.

Example of algorithm to find sum of two numbers:


Step1: Begin
Step2: read a,b
Step3: add a and b and store in variable c
Step4: display c

Step5: stop

2. Flowchart

Definition:
It is a diagrammatic representation of an algorithm. It is constructed using different
types Of boxes and symbols.

The main advantages of flow charts are:

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.

VAAGESWARI COLLEGE OF ENGINEERING DEPARTMENT OF CSE


I - B.TECH PPS LAB MANUAL10

Standard symbols used in drawing flowcharts:

Oval Terminal Start / stop / begin


/ end

Parallelogram Input / Making data


output available for
Processing (input)
or recording of the
processed
information
(output)
Document Printout Show data output
in the form of
document

Diamond Decision Decision or


switching type of
operations.
Rectangle Process Any processing to
be performed.
A process changes
or moves data. An
assignment
operation.
Circle Connector Used to connect
different parts of
flowchart
Arrow Flow Joins two symbols
and also represents
flow of execution
Bracket with --------- Annotation Descriptive
broken line comments or
explanation
Junction Repetitions Multiple control
flows converge.
More than one
arrow coming into
it.
Double sided Predefined Modules or
rectangle process subroutines
specified elsewhere

VAAGESWARI COLLEGE OF ENGINEERING DEPARTMENT OF CSE


I - B.TECH PPS LAB MANUAL11

3. Programming
A computer program is the list of instructions a computer follows in carrying out
its computations.

The process of writing a program is called programming.

Steps involved in Computer programming:


 Problem Definition
 Problem Understanding
 Program writing
 Error analysis
 Validation & Verification
 Documentation & Maintenance

Properties of Computer Programming:

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.

Note: All the properties of an algorithm holds good for 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.

A – used to store the number previous to the last number,


B – used to store the last number,
SUM – used to store the sum of A and B.

VAAGESWARI COLLEGE OF ENGINEERING DEPARTMENT OF CSE


I - B.TECH PPS LAB MANUAL12

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.

C has operators for:

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

VAAGESWARI COLLEGE OF ENGINEERING DEPARTMENT OF CSE


I - B.TECH PPS LAB MANUAL13

SOLUTIONS FOR PROGRAMS


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.

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

VAAGESWARI COLLEGE OF ENGINEERING DEPARTMENT OF CSE


I - B.TECH PPS LAB MANUAL14

printf("\n LOGICAL OPERATOR AND (a == b) && (r > b) equals to %d \n",


result);
result = (a == b) && (r < b);
printf("\n LOGICAL OPERATOR OR (a == b) || (r < b) equals to %d \n",
result);
result = (a != b) || (r < b);
printf("\n LOGICAL OPERATOR NOT (a != b) || (r < b) equals to %d \n",
result);
result = !(a == b);
printf("!(a == b) equals to %d \n", result);
c = (a == b) ? 1 : 0;
printf("\n CONDITIONAL OPERATOR= %d",c);
printf("\n BITWISE AND Output = %d", a&b);
printf("\n BITWISE OR Output = %d", a|b);
printf("\n BITWISE XOR Output = %d", a^b);
printf("\n SIZE OF OPERATOR int=%lu bytes\n",sizeof(a));
getch();
}

OUTPUT:

Enter a & b values:


4
3

ARITHMETIC OPERATORS a+b = 7


ARITHMETIC OPERATORS a-b = 1
ARITHMETIC OPERATORS a*b = 12
ARITHMETIC OPERATORS a/b = 1
ARITHMETIC OPERATORS MODULO DIVISION a%b= 1
PREINCREMENT OPERATOR ++a = 5
PREDECREMENT OPERATOR--b = 4
POST INCREMENT OPERATOR a++ = 4
POST DECREMENT OPERATORa-- = 5
ASSIGNMENT OPERATOR b = 4
ARITHMETIC ASSIGNMENT OPERATOR b = 8
ARITHMETIC ASSIGNMENT OPERATOR b = 4
ARITHMETIC ASSIGNMENT OPERATOR b = 16
ARITHMETIC ASSIGNMENT OPERATOR b = 4
ARITHMETIC ASSIGNMENT OPERATOR b = 0
RELATIONAL OPERATOR 4 == 0 = 0
RELATIONAL OPERATOR 4 > 0 = 1
RELATIONAL OPERATOR 4 < 0 = 0
RELATIONAL OPERATOR 4 != 0 = 1
RELATIONAL OPERATOR 4 >= 0 = 1
RELATIONAL OPERATOR 4 <= 0 = 0
LOGICAL OPERATOR AND (a == b) && (r > b) equals to 0
LOGICAL OPERATOR OR (a == b) || (r < b) equals to 0
LOGICAL OPERATOR NOT (a != b) || (r < b) equals to 1
!(a == b) equals to 1

VAAGESWARI COLLEGE OF ENGINEERING DEPARTMENT OF CSE


I - B.TECH PPS LAB MANUAL15

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

 It is possible for implicit conversions to lose information, signs can be lost


(when signed is implicitly converted to unsigned), and overflow can occur
(when long long is implicitly converted to float).

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.

The syntax in C: (type) expression


Where: Type indicated the data type to which the final result is converted.

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

// y implicitly converted to int. ASCII


// value of 'a' is 97

VAAGESWARI COLLEGE OF ENGINEERING DEPARTMENT OF CSE


I - B.TECH PPS LAB MANUAL16

x = x + y;

// x is implicitly converted to float


z = x + 1.0;

printf("\n Integer(implicit:char to Int) Value:x = %d",x);


printf("\n Float value(implicit:Int to Float) :z = %f", z);

// Explicit conversion from double to int


sum = (int)w + 1;

printf("\n sum (Exlicit:double to integer)= %d", sum);

getch();
}

OUTPUT:

Integer(implicit:char to Int) Value:x = 107


Float value(implicit:Int to Float) :z = 108.000000
sum (Exlicit:double to integer)= 2

SIMPLE NUMERIC PROBLEMS:


a. Write a program for find the max and min from the three numbers.

#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();
}

VAAGESWARI COLLEGE OF ENGINEERING DEPARTMENT OF CSE


I - B.TECH PPS LAB MANUAL17

OUTPUT:

Enter three numbers:


15
19
14
Maximum number is b =19
Minimum number is c = 14

b. Write the program for the simple, compound interest.

#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

Record at least 3 results Signature of faculty with date

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.

VAAGESWARI COLLEGE OF ENGINEERING DEPARTMENT OF CSE


I - B.TECH PPS LAB MANUAL18

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

Enter your percentage of marks:


65
You entered percentage of marks: 65
You got First Class

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

printf(“\n Multiplication table for a given=%d”, n);


printf(“\n The number of rows in the table=%d”, r);

for(j=1;j<=r;j++)
{
printf("\n %d * %d = %d ", n, j, n*j);
}

getch();
}

VAAGESWARI COLLEGE OF ENGINEERING DEPARTMENT OF CSE


I - B.TECH PPS LAB MANUAL19

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

e. Write a program that shows the binary equivalent of a given positive


number between 0 to 255.

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

Enter a decimal integer (0-255):


134
Input number is = 134
Its binary equivalent is = 10000110

VAAGESWARI COLLEGE OF ENGINEERING DEPARTMENT OF CSE


I - B.TECH PPS LAB MANUAL20

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

Second equation of motion : S=ut+(1/2)at^2


S= Distance, u=initial velocity , a=acceleration , t= time.
Substituing values, S= 10*3= 30 m , u= 0 , a=g=9.8 m/s^2 ,
t to be calculated.
30= 0*t + 1/2(9.8*t^2)
30=4.9t^2
30/4.9=t^2
_/6.12244=t
Taking square root, t=2.474 sec
It will take 2.474 seconds for object to fall from 30 mts.

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

VAAGESWARI COLLEGE OF ENGINEERING DEPARTMENT OF CSE


I - B.TECH PPS LAB MANUAL21

OUTPUT:
Time taken to reach ground= 2.474 sec

//PROGRAME TO FIND DISTANCE BETWEEN TIME INTERVALS(EXRTA PROGRAME)

#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: +,-,*, /, %

VAAGESWARI COLLEGE OF ENGINEERING DEPARTMENT OF CSE


I - B.TECH PPS LAB MANUAL22

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

VAAGESWARI COLLEGE OF ENGINEERING DEPARTMENT OF CSE


I - B.TECH PPS LAB MANUAL23

Output:
Enter you operator (+, -, /, *, %):
+
Enter the values of a and b:
1
3
addition of two numbers is: 4

c. Write a program that finds if a given number is a prime number

A prime number is a positive integer which is divisible only by 1 and itself.


For example: 2, 3, 5, 7, 11, 13

Program to Check Prime Number

#include <stdio.h>
void main()
{
int n, i, c = 0;
clrscr();
printf("\n Enter a positive integer: ");
scanf("%d",&n);

for(i=2; i<=n/2; ++i)


{
// condition for nonprime number
if(n%i==0)
{
c=1;
break;
}
}

if (c==0)
printf("\n %d is a prime number.",n);
else
printf("\n %d is not a prime number.",n);
getch();
}
Output

Enter a positive integer:


29
29 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.

VAAGESWARI COLLEGE OF ENGINEERING DEPARTMENT OF CSE


I - B.TECH PPS LAB MANUAL24

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

VAAGESWARI COLLEGE OF ENGINEERING DEPARTMENT OF CSE


I - B.TECH PPS LAB MANUAL25

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:

A fibonacci series is defined as follows:

The first term in the sequence is 0


The second term in the sequence is 1
The sub sequent terms 1 found by adding the preceding two terms in the sequence
Formula: let t1, t2, ………… tn be terms in fibinacci sequence
t1 = 0, t2 = 1
tn = tn - 2 + tn - 1 …… where n > 2

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

VAAGESWARI COLLEGE OF ENGINEERING DEPARTMENT OF CSE


I - B.TECH PPS LAB MANUAL26

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

VAAGESWARI COLLEGE OF ENGINEERING DEPARTMENT OF CSE


I - B.TECH PPS LAB MANUAL27

Output:

Prime no. series


Enter any number
10
The prime numbers between 1 to 10
2 3 5 7

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


Description:

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

VAAGESWARI COLLEGE OF ENGINEERING DEPARTMENT OF CSE


I - B.TECH PPS LAB MANUAL28

printf("\n Enter the values of a, b, c:\n");


scanf("%f%f%f", &a, &b, &c);
if(a == 0 || b == 0 || c == 0)
{
printf("\n Error: Roots can't be determined");
}
else
{
d = (b * b) - (4.0 * a * c);
if(d > 0.00)
{
printf("\n Roots are real and distinct \n");
root1 = -b + sqrt(d) / (2.0 * a);
root2 = -b - sqrt(d) / (2.0 * a);
printf("\n Root1 = %f \nRoot2 = %f", root1, root2);
}
else if (d < 0.00)
{
printf("\n Roots are imaginary\n");
root1 = -b / (2.0 * a) ;
root2 = sqrt(abs(d)) / (2.0 * a);
printf("\n Root1 = %f +i %f\n", root1, root2);
printf("\n Root2 = %f -i %f\n", root1, root2);
}
else if (d == 0.00)
{
printf("\n Roots are real and equal\n");
root1 = -b / (2.0 * a);
root2 = root1;
printf("\n Root1 = %f\n", root1);
printf("\n Root2 = %f\n", root2);
}
}
getch();
}
Input & Output:
Enter the values of a, b, c
1 2 3
Roots are imaginary
Root1 = -1.000 + i
Root2 = -1.000 - i

h. Write a C program to calculate the following, where x is a fractional value.


1-x/2 +x^2/4-x^3/6

Program:
#include <stdio.h>
void main()
{
float x,sum=1,t=1,d;

VAAGESWARI COLLEGE OF ENGINEERING DEPARTMENT OF CSE


I - B.TECH PPS LAB MANUAL29

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

the sum = -0.415873


Number of terms = 5
value of x = 2.000000

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

VAAGESWARI COLLEGE OF ENGINEERING DEPARTMENT OF CSE


I - B.TECH PPS LAB MANUAL30

Output:
Enter the Value of x: 2
Enter the number of terms: 5

The sum of this geometric progression: 1+x+x^2+x^3+…+x^n. = 156.

ARRAYS AND POINTERS AND FUNCTIONS:

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


of integers.

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

/* Assume first element as maximum and minimum */


max = arr[0];
min = arr[0];

//Find maximum and minimum in all array elements.

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


{
if(arr[i] > max)
{
max = arr[i];
}
if(arr[i] < min)
{
min = arr[i];
}
sum=sum+arr[i];S
}

VAAGESWARI COLLEGE OF ENGINEERING DEPARTMENT OF CSE


I - B.TECH PPS LAB MANUAL31

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

Enter size of the array:


5
Enter elements in the array:
15
5
25
20
10
Maximum element = 25
Minimum element = 5
Sum =75 and Average = 15.000000

b. Write a functions to compute mean, variance, Standard Deviation, sorting of


n elements in single dimension array.

Description:

This C Program calculates the mean, variance & standard deviation.


The formula which is used in this program is

 Mean = average of the numbers.


 Variance = (summation( ( Xi – average of numbers) * ( Xi – average of
numbers)) ) / Total no of elements.
where i = 1 to N here N is the total no of elements.
 Standard deviation = Squareroot of the variance.

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;

VAAGESWARI COLLEGE OF ENGINEERING DEPARTMENT OF CSE


I - B.TECH PPS LAB MANUAL32

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

while (n<1 || n>Max_Arr)


{
printf("\n Invalid response. You must enter a value between 1 and 20.\n");
scanf("%d",&n);
}
printf("Enter the %d real numbers:\n",n);
for (i=0;i<n;i++)
{
scanf("%f",&array[i]);
}

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

void sortarr(float arr[], int n)


{
int i,j,k;
for(i=0;i<(n-1);i++)
{
for(j=0;j<n-i-1;j++)
{
if(arr[j]>arr[j+1])
{
k=arr[j];
arr[j]=arr[j+1];
arr[j+1]=k;
}
}
}
printf("\n The Array Elements in Sorted Order:\n");
for(i=0;i<n;i++)
printf("%.2f\t",arr[i]);

float mean_value(float arr[],int n)


{
int i;

VAAGESWARI COLLEGE OF ENGINEERING DEPARTMENT OF CSE


I - B.TECH PPS LAB MANUAL33

float avg;
float sum;
for(i=0;i<n;i++)
{
sum+=arr[i];
}
avg = (sum/n);
return avg;
}

float variance_value(float arr[], int n)


{

int i;
float var=0,sum1=0,avg=0;

avg=mean_value(arr,n);

for (i = 0; i <n; i++) // To calculate Variance


{
sum1 = sum1 + pow((arr[i] - avg), 2);
}
var = sum1 /(float)n;
return var;

float var_stdDev(float var)


{

float stdDev;
stdDev=sqrt(var); //To calculate Standard Deviation
return stdDev;
}

OUTPUT:

VAAGESWARI COLLEGE OF ENGINEERING DEPARTMENT OF CSE


I - B.TECH PPS LAB MANUAL34

c. Write a C program that uses functions to perform the following:


i. Addition of Two Matrices
ii. Multiplication of Two Matrices
iii. Transpose of a matrix with memory dynamically allocated for the new
matrix as row and column counts may not be same.

#include<stdio.h>
#include<conio.h>

void read_arr(int a[10][10],int row,int col)


{
int i,j;
for(i=1;i<=row;i++)
{
for(j=1;j<=col;j++)
{
printf("Enter Element %d %d : ",i,j);
scanf("%d",&a[i][j]);
}
}
}

void add_arr(int m1[10][10],int m2[10][10],int m3[10][10],int row,int col)


{
int i,j;
for(i=1;i<=row;i++)

VAAGESWARI COLLEGE OF ENGINEERING DEPARTMENT OF CSE


I - B.TECH PPS LAB MANUAL35

{
for(j=1;j<=col;j++)
{
m3[i][j] = (m1[i][j] + m2[i][j]);
}
}
}

void mul_arr(int m1[10][10],int m2[10][10],int m3[10][10],int row,int col)


{
int i,j,k;
for(i=1;i<=row;i++)
{
for(j=1;j<=col;j++)
{
m3[i][j]=0;
for (k=1;k<=row;k++)
{
m3[i][j] = m3[i][j] + (m1[i][k] * m2[k][j]);
}
}
}
}

void print_arr(int m[10][10],int row,int col)


{
int i,j;
for(i=1;i<=row;i++)
{
for(j=1;j<=col;j++)
{
printf("%d ",m[i][j]);
}
printf("\n");
}
}

void transpose(int m[10][10],int row,int col)


{
int i,j;
for(i=1;i<=row;i++)
{
for(j=1;j<=col;j++)
{
printf("%d ",m[j][i]);
}
printf("\n");
}
}

void main()
{

VAAGESWARI COLLEGE OF ENGINEERING DEPARTMENT OF CSE


I - B.TECH PPS LAB MANUAL36

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:

d. Write C programs that use both recursive and non-recursive functions


i. To find the factorial of a given integer.
ii. To find the GCD (greatest common divisor) of two given integers.
iii. To find x^n

VAAGESWARI COLLEGE OF ENGINEERING DEPARTMENT OF CSE


I - B.TECH PPS LAB MANUAL37

Description:

Factorial of a number is nothing but the multiplication of numbers from a given


number to
Ex: 5! =5*4*3*2*1= 120
i. To find the factorial of a given integer.

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

long int recfactorial(long int x)


{
long int f;
if(x == 0)
{
return(1);
}
else

VAAGESWARI COLLEGE OF ENGINEERING DEPARTMENT OF CSE


I - B.TECH PPS LAB MANUAL38

{
f = x * recfactorial(x - 1);
return(f);
}
}

Long int nonrecfactorial(long int x)


{
long int i, f = 1;
for(i = 1;i <= x; i++)
{
f = f * i;
}
return(f);
}

Input & Output:


Enter any number
5
The factorial of a given number using recursion: 5 = 120
The factorial of a given number using nonrecursion: 5=120

ii. To find the GCD (greatest common divisor) of two given integers.

According to Mathematics, the Greatest Common Divisor (GCD) of two or more


integers is the largest positive integer that divides the given integer values without
remainder. For example, the GCD value of integer 8 and 12 is 4 because, both 8 and
12 are divisible by 1, 2, and 4 (remainder is 0) and the largest positive integer among
the factors 1, 2, and 4 is 4.
The Greatest Common Divisor (GCD) is also known as the Highest Common
Factor (HCF), or Greatest Common Factor (GCF), or Highest Common Divisor (HCD),
or Greatest Common Measure (GCM). In this article we will show you, How to write a
c program to find GCD of two numbers using For Loop, While Loop, Functions, and
Recursion.

NOTE: In order to find the Greatest Common Divisor, we have to pass at least one
non-zero value.

To compute the GCD of 32 and 24 using Euclid‟s algorithm:

 Divide 32 by 24 to get a quotient of 1 and a remainder of 8.


 Then divide 24 by 8 to get a quotient of 3 and a remainder of 0.
 8 is the gcd of 32 and 24.

Algorithm:
Step 1: Start
Step 2: Read a, b values as integers

VAAGESWARI COLLEGE OF ENGINEERING DEPARTMENT OF CSE


I - B.TECH PPS LAB MANUAL39

Step 3: Call function gcd (a, b) and assign it to res


Step 4: Print res
Step 5: Stop
Called function gcd (a, b)
begin
while(v != 0)
begin
temp ← u MOD v;
u ← v;
v ← temp;
end
return(u);
end

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

int recgcd(int x, int y)


{
if(y == 0)
{
return(x);
}
else
{
return(recgcd(y, x % y));
}
}

VAAGESWARI COLLEGE OF ENGINEERING DEPARTMENT OF CSE


I - B.TECH PPS LAB MANUAL40

int nonrecgcd(int x, int y)


{
int z;
while(x % y != 0)
{
z = x % y;
x = y;
y = z;
}
return(y);
}

Input & Output:


Enter two numbers a, b
3
6
The gcd of two numbers using recursion: 3 and 6 is 3
The gcd of two numbers using nonrecursion: 3 and 6 is 3

iii. To find x^n

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

double power(double x, int y)

VAAGESWARI COLLEGE OF ENGINEERING DEPARTMENT OF CSE


I - B.TECH PPS LAB MANUAL41

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

Enter size of array:


5
Enter elements of array:
10
15
20
25
30
The array Elements are:
10 15 20 25 30

VAAGESWARI COLLEGE OF ENGINEERING DEPARTMENT OF CSE


I - B.TECH PPS LAB MANUAL42

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

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


scanf("%d",&n);
pt = &arr1[0]; // pt stores the address of base array arr1
printf("\n Enter %d integers into array: \n",n);
for(i=0;i<n;i++)
{
printf("\n Element : %d is:",i+1);
scanf("%d",pt);//accept the address of the value
pt++;
}

pt = &arr1[n - 1];

printf("\n The elements of array in reverse order are :");

for (i = n; i > 0; i--)


{
printf("\n Element : %d is:%d", i, *pt);
pt--;
}
printf("\n\n");
getch();
}

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

The elements of array in reverse order are:


Element : 5 is :6
Element : 4 is :5
Element : 3 is :4

VAAGESWARI COLLEGE OF ENGINEERING DEPARTMENT OF CSE


I - B.TECH PPS LAB MANUAL43

Element : 2 is :3
Element : 1 is :2

g. Write a program through pointer variable to sum of n elements from array.

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

printf("\nEnter %d array elements:\n",n);


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

/* array is equal to base address


* array = &array[0] */
ptr = array;

for(i=0;i<n;i++)
{
//*ptr refers to the value at address
sum = sum + *ptr;
ptr++;
}

printf("\nThe sum of array elements using pointers: %d",sum);


getch();
}
Output:

Enter the size of an array:


5
Enter 5 array elements :
1
2
3
4
5
The sum of array elements using pointers:15

VAAGESWARI COLLEGE OF ENGINEERING DEPARTMENT OF CSE


I - B.TECH PPS LAB MANUAL44

FILES:

a. Write a C program to display the contents of a file to standard output device.

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.

 Declare a file pointer fp in read mode


 Read the characters of file
 Write to characters to stdout.

#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

VAAGESWARI COLLEGE OF ENGINEERING DEPARTMENT OF CSE


I - B.TECH PPS LAB MANUAL45

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

VAAGESWARI COLLEGE OF ENGINEERING DEPARTMENT OF CSE


I - B.TECH PPS LAB MANUAL46

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.

Command line arguments:

 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:

int main(int argc, char *argv[])


#include<stdio.h>
void main(int argc,char *argv[])
{
FILE *f1;
char ch;
int count=0;
if(argc!=3)
{
printf("\n error occured");
exit();
}
f1=fopen(argv[1],"r");
while((ch=getc(f1))!=EOF)
{
if(ch==*argv[2])
count++;
}
fclose(f1);
printf("character %c occured %d times",ch,count);
getch();
}

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

VAAGESWARI COLLEGE OF ENGINEERING DEPARTMENT OF CSE


I - B.TECH PPS LAB MANUAL47

character p occurred 6 times

d. Write a C program that does the following:


It should first create a binary file and store 10 integers, where the file name and
10 values are given in the command line. (hint: convert the strings using atoi
function) Now the program asks for an index and a value from the user and the
value at that index should be changed to the new value in the file. (hint: use
fseek function) The program should then read all 10 values and print them back.

#include<stdio.h>

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

Step by step descriptive logic to merge two files to 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.

VAAGESWARI COLLEGE OF ENGINEERING DEPARTMENT OF CSE


I - B.TECH PPS LAB MANUAL48

1) Open file1.txt and file2.txt in read mode.


2) Open file3.txt in write mode.
3) Run a loop to one by one copy characters of file1.txt to file3.txt.
4) Run a loop to one by one copy characters of file2.txt to file3.txt.
5) Close all files.

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

// Open file to store the result


FILE *fp3 = fopen("file3.txt", "w");
char c;
clrscr();

if (fp1 == NULL || fp2 == NULL || fp3 == NULL)


{
puts("Could not open files");
exit(0);
}

// Copy contents of first file to file3.txt


while ((c = fgetc(fp1)) != EOF)
fputc(c, fp3);

// Copy contents of second file to file3.txt


while ((c = fgetc(fp2)) != EOF)
fputc(c, fp3);

printf("Merged file1.txt and file2.txt into file3.txt");


fclose(fp3);

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

VAAGESWARI COLLEGE OF ENGINEERING DEPARTMENT OF CSE


I - B.TECH PPS LAB MANUAL49

Output:

Merged file1.txt and file2.txt into file3.txt


The third file content is:
Hello friends How are you
STRINGS:
a. Write a C program to convert a Roman numeral ranging from I to L to its
decimal equivalent.

C program to convert Roman Number to Decimal Number : This C Program Converts


the given Roman Number to Decimal Number. Roman Number System of representing
numbers devised by ancient Romans. Roman numbers are formed by combinations
of symbols I, V, X, L, C, D, and M, standing, respectively, for 1, 5, 10, 50, 100, 500, n
1,000 in Hindu-Arabic Decimal numeral system. Decimal is a term that describes
base-10 number system commonly used by lay people in developed world

Roman numerals are based on below symbols.

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;

VAAGESWARI COLLEGE OF ENGINEERING DEPARTMENT OF CSE


I - B.TECH PPS LAB MANUAL50

case 'V': a[i] = 5;


break;
case 'X': a[i] = 10;
break;
case 'L': a[i] = 50;
break;
case 'C': a[i] = 100;
break;
case 'D': dec = dec + 500;
break;
case 'M': a[i] = 1000;
break;
default : printf("Invalid choice");
break;
}
}
k = a[l - 1];
for(i = l - 1; i > 0; i--)
{
if(a[i] > a[i - 1])
{
k = k - a[i - 1];
}
if(a[i] <= a[i - 1])
{
k = k + a[i - 1];
}
}
printf("decimal equivalent is %d", k);
getch();
}

Output:
Enter the roman number
XIV
Decimal equivalent is 14

b. Write a C program that converts a number ranging from 1 to 50 to Roman


equivalent

#include <stdio.h>

void predigit(char num1, char num2);


void postdigit(char c, int n);

char romanval[1000];
int i = 0;
int main()
{
int j;
long number;

VAAGESWARI COLLEGE OF ENGINEERING DEPARTMENT OF CSE


I - B.TECH PPS LAB MANUAL51

printf("Enter the number: ");


scanf("%d", &number);
if (number <= 0)
{
printf("Invalid number");
return 0;
}
while (number != 0)
{
if (number >= 1000)
{
postdigit('M', number / 1000);
number = number - (number / 1000) * 1000;
}
else if (number >= 500)
{
if (number < (500 + 4 * 100))
{
postdigit('D', number / 500);
number = number - (number / 500) * 500;
}
else
{
predigit('C','M');
number = number - (1000-100);
}
}
else if (number >= 100)
{
if (number < (100 + 3 * 100))
{
postdigit('C', number / 100);
number = number - (number / 100) * 100;
}
else
{
predigit('L', 'D');
number = number - (500 - 100);
}
}
else if (number >= 50 )
{
if (number < (50 + 4 * 10))
{
postdigit('L', number / 50);
number = number - (number / 50) * 50;
}
else
{
predigit('X','C');
number = number - (100-10);
}
}
else if (number >= 10)

VAAGESWARI COLLEGE OF ENGINEERING DEPARTMENT OF CSE


I - B.TECH PPS LAB MANUAL52

{
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;
}

void predigit(char num1, char num2)


{
romanval[i++] = num1;
romanval[i++] = num2;
}

void postdigit(char c, int n)


{
int j;

VAAGESWARI COLLEGE OF ENGINEERING DEPARTMENT OF CSE


I - B.TECH PPS LAB MANUAL53

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


romanval[i++] = c;
}

Output:

Enter the number: 500


Roman number is be: D

Program Explanation

1. Take a decimal number as input and store it in the variable number.


2. Check if the number is lesser than 0. If it is, then print the output as “Invalid
number”.
3. Check if the number is greater than 1000 or 500 or 100 or 50 or 10 or 5.
4. If it is, then also check if the number is greater than 900 or 400 or 90 or 40 or 9
or4. If it is, then call the function predigit() and subtract the variable number by its
equivalent number and override the variable number with this value.
5. Otherwise call the function postdigit() and divide the variable number by its
equivalent number and get the quotient. Multiply the quotient with its equivalent
number and decrement the variable number with this value.
6. In the function postdigit(), assign the equivalent roman number to the array
romanval[].
7. In the function predigit(), assign the array romanval[] with the parameters of
function.
8. Repeat the steps 3-5 until the variable number becomes zero.
9. Print the array romanval[] as output.

c. Write a C program that uses functions to perform the following operations:


i. To insert a sub-string in to a given main string from a given position.
ii. To delete n Characters from a given position in a given string.

i. To insert a sub-string in to a given main string from a given position.

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

VAAGESWARI COLLEGE OF ENGINEERING DEPARTMENT OF CSE


I - B.TECH PPS LAB MANUAL54

puts("Enter the string 2\n");


gets(str2);
len2 = strlen(str2);
printf("Enter the position where the string is to be inserted\n");
scanf("%d", &n);
for(i = n; i < len1; i++)
{
str1[i + len2] = str1[i];
}
for(i = 0; i < len2; i++)
{
str1[n + i] = str2[i];
}
str2[len2 + 1] = '\0';
printf("After inserting the string is %s", str1);
getch();
}

output
Enter the string 1
sachin
Enter the string 2
tendulkar
Enter the position where the string is to be inserted
4
After inserting the string is sachtendulkarin

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

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++)
{

VAAGESWARI COLLEGE OF ENGINEERING DEPARTMENT OF CSE


I - B.TECH PPS LAB MANUAL55

str[i - n] = str[i];
}
str[i - n] = '\0';
printf("The string is %s", str);
getch();
}

OUTPUT

Enter the string


sachin
Enter the position where characters are to be deleted
2
Enter the number of characters to be deleted
2
The string is sain

d. 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.)

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

void main()
{
char a[100], b[100];

printf("\n Enter a string to check if it is a palindrome:\n");


gets(a);

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

madam is string is a palindrome

VAAGESWARI COLLEGE OF ENGINEERING DEPARTMENT OF CSE


I - B.TECH PPS LAB MANUAL56

e. Write a C program that displays the position of a character ch in the string S


or – 1 if S doesn‘t contain ch.

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

2.Enter the first string:


nagaraju
Enter the string to be searched:
raju

VAAGESWARI COLLEGE OF ENGINEERING DEPARTMENT OF CSE


I - B.TECH PPS LAB MANUAL57

second string is found in the first string at 4 position

3.Enter the first string:


nagarjuna
Enter the string to be searched:
ma
-1

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

VAAGESWARI COLLEGE OF ENGINEERING DEPARTMENT OF CSE


I - B.TECH PPS LAB MANUAL58

The number of characters in the string are 34


The number of words in the string are 9

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;

VAAGESWARI COLLEGE OF ENGINEERING DEPARTMENT OF CSE


I - B.TECH PPS LAB MANUAL59

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

void smallest(int arr[],int n)


{
int min,i,j;
min=arr[0];
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(min > arr[j])
{
min = arr[j];
}
}
}
printf("\n Smallest Number =%d " ,min);
}

void largest(int arr[],int n)


{
int max,i,j;
max=arr[0];
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(max < arr[j])
{
max = arr[j];
}
}
}
printf("\n Largest Number=%d " ,max);
}
void sum(int arr[],int n)

VAAGESWARI COLLEGE OF ENGINEERING DEPARTMENT OF CSE


I - B.TECH PPS LAB MANUAL60

{
int sum=0,i;
for(i=0;i<n;i++)
{
sum=sum+arr[i];
}
printf("\n sum=%d",sum);
}

void average(int arr[],int n)


{
int sum=0,i;
float avg=0;
for(i=0;i<n;i++)
{
sum=sum+arr[i];
}
avg=sum/n;
printf("\nAverage of n numbers %f",avg);
}

OUTPUT:

**************************
MENU
* ************************
1. SMALLEST
2. LARGEST
3. SUM
4. AVERAGE
5. EXIT
**************************

Enter the N value (i.e 5 to 10):


5
Enter the 5 Elements:
5
2
3
1
4

Enter your choice? (1 to 4):


2
Largest Number=5
Enter your choice? (1 to 4):
1
Smallest Number=1
Enter your choice? (1 to 4):
5

VAAGESWARI COLLEGE OF ENGINEERING DEPARTMENT OF CSE


I - B.TECH PPS LAB MANUAL61

b. Write a C program to construct a pyramid of numbers as follows:


1 * 1 1 *
12 ** 23 22 **
123 *** 456 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("%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)
{

VAAGESWARI COLLEGE OF ENGINEERING DEPARTMENT OF CSE


I - B.TECH PPS LAB MANUAL62

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

VAAGESWARI COLLEGE OF ENGINEERING DEPARTMENT OF CSE


I - B.TECH PPS LAB MANUAL63

printf("\n Enter number of rows: ");


scanf("%d",&rows);
for(i=1; i <= rows; i++)
{
for(j=1; j <= i; ++j)
{
printf("%d ", number);
++number;
}
printf("\n");
}
getch();
}
OUTPUT:
Enter number of rows: 4
1
23
456
7 8 9 10

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

VAAGESWARI COLLEGE OF ENGINEERING DEPARTMENT OF CSE


I - B.TECH PPS LAB MANUAL64

*
* *
* **
* ***
* **
* *
*

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.
Description:

 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

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<--linear(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

VAAGESWARI COLLEGE OF ENGINEERING DEPARTMENT OF CSE


I - B.TECH PPS LAB MANUAL65

Program:
#include <stdio.h>

long linear_search(long a[100], long, long);

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

long linear_search(long a[100], long n, long find)


{
long i;

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


{
if (a[i] == find)
return i;
}
return -1;
}

OUTPUT
Enter N value: 5
Entered 5 numbers:
2
5
1
6
4
Enter number to search: 6
6 is present at location 4.

VAAGESWARI COLLEGE OF ENGINEERING DEPARTMENT OF CSE


I - B.TECH PPS LAB MANUAL66

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

BINARY SEARCH FUNCTION

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

4. assign (low+high)/2 to mid


5. if m<k[mid] goto step 6 otherwise goto step 7
6. assign mid-1 to high goto step 3
7. if m>k[mid] goto step 8 otherwise goto step 9
8. assign mid+1 to low
9. return mid
10. return 0
11. Stop

VAAGESWARI COLLEGE OF ENGINEERING DEPARTMENT OF CSE


I - B.TECH PPS LAB MANUAL67

PROGRAM:

/*write a c program for implementing binary search method using function */

#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

VAAGESWARI COLLEGE OF ENGINEERING DEPARTMENT OF CSE


I - B.TECH PPS LAB MANUAL68

printf("\n Element %d Found at Position %d\n",element,position + 1);


getch();
}

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

Element 6 Found at Position 2

c. Write a C program that implements the Bubble sort method to sort a given
list of integers in ascending order.

Description:

 Bubble sort is the simplest and oldest sorting technique.


 This method takes two elements at a time. It compares these two elements. If
first elements are less than second one, they are left un-disturbed. If the first
element is greater than second one then they are swapped.
 The procedure continues with the next two elements goes and ends when all
the elements are sorted.
 But bubble sort is an inefficient algorithm.
 The order of bubble sort algorithm is O(n2).

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

VAAGESWARI COLLEGE OF ENGINEERING DEPARTMENT OF CSE


I - B.TECH PPS LAB MANUAL69

BUBBLE SORT FUNCTION


1. start
2. initialise last to n
3. for i= 1 to n increment in steps
of 1 begin
4. initialise ex to 0
5. for i= 1 to last-1 increment in steps
of 1 begin
6. if k[i]>k[i+1] goto step 7 otherwise goto step
5 begin
7. assign k[i] to temp assign k[i+1] to k[i]
assign temp to k[i+1] increment ex by 1
end-if
8. end inner for loop
9. if ex!=0
assign last-1 to last

end for loop


10. Stop.

This figure for better understanding of bubble sort:

/*C Program To Sort data in ascending order using bubble sort.*/

PROGRAM:

#include <stdio.h>
void main()
{
int data[100],i,n,j,temp;

VAAGESWARI COLLEGE OF ENGINEERING DEPARTMENT OF CSE


I - B.TECH PPS LAB MANUAL70

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

printf("\n The Entered Elements are:\n");


for(i=0;i<n;i++)
printf("%d\t",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

The Entered Elements are:


12 3 0 -3 1 -9

Elements in descending order:


-3 -9 0 1 3 12

d. Write a C program that sorts the given array of integers using selection sort
in descending order

VAAGESWARI COLLEGE OF ENGINEERING DEPARTMENT OF CSE


I - B.TECH PPS LAB MANUAL71

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.

This figure for better understanding of selection sort:

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

VAAGESWARI COLLEGE OF ENGINEERING DEPARTMENT OF CSE


I - B.TECH PPS LAB MANUAL72

printf("\n %d. Enter element: ",i+1);


scanf("%d",&data[i]);
}

printf("\n The Entered Elements are:\n");


for(i=0;i<n;i++)
printf("%d\t",data[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

The Entered Elements are:


12 1 23 2 4

Elements in descending order:


23 12 4 2 1

e. Write a C program that sorts the given array of integers using insertion sort
in ascending order

VAAGESWARI COLLEGE OF ENGINEERING DEPARTMENT OF CSE


I - B.TECH PPS LAB MANUAL73

EXPLANATION:

Suppose, you want to sort elements in ascending as in above figure. Then,

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:

/*Sorting Elements of an array in ascending order using insertion sort


algorithm*/

#include<stdio.h>

VAAGESWARI COLLEGE OF ENGINEERING DEPARTMENT OF CSE


I - B.TECH PPS LAB MANUAL74

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

printf("\n The Elements in ascending order:\n ");


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

OUTPUT:

Enter number of terms: 5


Enter elements: 12
1
2
5
3
The Entered Elements are:
12 1 2 5 3
The Elements in ascending order: 1 2 3 5 12

VAAGESWARI COLLEGE OF ENGINEERING DEPARTMENT OF CSE


I - B.TECH PPS LAB MANUAL75

f. Write a C program that sorts a given array of names

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

VAAGESWARI COLLEGE OF ENGINEERING DEPARTMENT OF CSE

You might also like