Laboratory Manual PPS Cse Updated
Laboratory Manual PPS Cse Updated
of
Prepared By:
Anju Godara
Assistant Professor
(Computer Science & Engg. Deptt.)
1
PROGRAMMING FOR PROBLEM SOLVING LAB
Note:The programs may be executed using any available Open Source/ Freely available IDE.
Software Requirement: Linux Operating System with GCC / TURBO C in WINDOWS OS / TURBO C++
in WINDOWS OS.
2
INSTRUCTIONS TO STUDENTS FOR PREPARING PROGRAMMING IN C LAB REPORT
This lab manual is prepared to help the first year students with their practical understanding and
development of programming skills , and may be used as a base reference during the lab practical
classes.
Students have to submit Lab Exercise report of previous lab into corresponding next lab, and can be
collected back after the instructor/course co-ordinator after it has been checked and signed.At the end
of the semester, students should compile all the lab Excerise reports into single report and submit
during end semester sessional examinations.
3
List of Practical/Programs to be performed in Lab
5
PREFACE
This manual was developed specifically for fresh students taking up their first course in
are arranged based on the order of class discussion. Students will be exposed to several new aspects
of programming. Students will get knowledge about the concepts in C programming which includes
6
Practice sessions:-
1.Module Name:-Familiarization with Programming Environment
Introduction to C Programming:-
Programming is the process that professionals use to write code that instructs how a computer, application
or software program performs. At its most basic, computer programming is set of instructions to Computer
facilitate specific actions. Computer can do amazing things, from basic laptops capable of simple word
processing and spreadsheet functions to incredibly complex supercomputers completing millions of
financial transactions a day and controlling the infrastructure that makes modern life possible but no
computer can do anything until a computer programmer tells it to behave in specific ways. That is what
computer programming is all about .Compiler is used for performing translation.
C is a procedural programming language. It was initially developed by Dennis Ritchie in the year 1972.
It was mainly developed as a system programming language to write an operating system. The main
features of the C language include low-level memory access, a simple set of keywords, and a clean style
these features make C language suitable for system programs like an operating system or compiler
development.
C basic syntax: syntax refers to the rules that specify the correct combined sequence of symbols that can
be used to form a correctly structured program using a given programming language. Programmers
communicate with computers through the correctly structured syntax, semantics and grammar of a
programming language.
This is a preprocessor statement that includes standard input output header file (stdio.h)
#include
from the C library. By including header file, you can use many different functions such
<stdio.h>
as printf()
void main()
The execution of the C program starts with main() function. “void” is the return type of the
7
function. Every C program can have only one main function.
Two curly brackets {} are used to group all code statements. This indicates begins & ends
Braces {}
of the main function.
/* Comments Comments are just used to document or explain the code, to help others understand it.
*/ Everything written inside the command /* */ will be ignored by the compiler.
printf() printf() is a function in C, which prints the text output on the screen.
getch() This is used to read any character input from the keyboard.
1. Start.
2. Initialize int a,b,c,d,e,f;
8
4. Perform addition and store the result in c.
8. Stop.
== Checks if the values of two operands are equal or not. If yes, then the (A == B)
condition becomes true. is not
true.
!= Checks if the values of two operands are equal or not. If the values are not (A != B)
equal, then the condition becomes true. is true.
> Checks if the value of left operand is greater than the value of right operand. (A > B)
If yes, then the condition becomes true. is not
true.
< Checks if the value of left operand is less than the value of right operand. If (A < B)
yes, then the condition becomes true. is true.
>= Checks if the value of left operand is greater than or equal to the value of (A >= B)
right operand. If yes, then the condition becomes true. is not
true.
<= Checks if the value of left operand is less than or equal to the value of right (A <= B)
operand. If yes, then the condition becomes true. is true.
9
Relational Operators:-
Relational operators are used in decision making and loops.
Operator Meaning of Operator Example
== Equal to 5 == 3 is evaluated to 0
Bitwise Operators:-
| Bitwise OR
^ Bitwise XOR
~ Bitwise complement
Logical Opertors:-
Operators Example/Description
(x>=10)||(y>=10)
|| (logical OR) It returns true when at-least one of the condition is true
10
!((x>5)&&(y<5))
It reverses the state of the operand “((x>5) && (y<5))”
! (logical NOT) If “((x>5) && (y<5))” is true, logical NOT operator makes it false
Sample Program
3) 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.
Data Type:-
Each variable in C has an associated data type. Each data type requires different amounts
of memory and has some specific operations which can be performed over it. Let us briefly
describe them one by one:
Following are the examples of some very common data types used in C:
char: The most basic data type in C. It stores a single character and requires a single
byte of memory in almost all compilers.
int: As the name suggests, an int variable is used to store an integer.
float: It is used to store decimal numbers (numbers with floating point value) with
single precision.
double: It is used to store decimal numbers (numbers with floating point value) with
double precision.
Different data types also have different ranges upto which they can store numbers. These
ranges may vary from compiler to compiler.
Memory
Data Type (bytes) Range Format Specifier
-2,147,483,648 to
int 4 2,147,483,647 %d
-2,147,483,648 to
long int 4 2,147,483,647 %ld
11
Memory
Data Type (bytes) Range Format Specifier
0 to
unsigned long long int 8 18,446,744,073,709,551,615 %llu
float 4 %f
--
double 8 %lf
--
long double 16
-- %Lf
Sample Program:-
4) Write a simple program that converts one given data type to
another using auto conversion and casting. Take the values
form standard input.
5) WAP to find area and perimeter of circle.
6) WAP to find area and perimeter of rectangle.
7) Given the values of three variable entered by user, write a
program to compute anddisplay the value of x, where x=a/(b-
c).
8) Write a program for find the max and min from the three
numbers.
If you put some condition for a block of statements, the execution flow may change based on
12
the result evaluated by the condition. This process is called decision making in 'C. ' It is also
called as branching as a program decides which statement to execute based on the result of
the evaluated condition.
If Statement:-
The if statement evaluates the test expression inside the parenthesis () . If the test expression
is evaluated to true, statements inside the body of if are executed. If the test expression is
evaluated to false, statements inside the body of if are not executed.
Syntax:-
If (condition)
{
//Block of C statements here
//These statements will be execute if the condition is true
}
If else Statements:-
The if-else is statement is an extended version of If. The general form of if-else is as follows:
Syntax:-
if (test-expression)
{
True block of statements
}
Else
{
False block of statements
}
Statements;
The general syntax of how else-if ladders are constructed in ‘C’ programming is as follows:
Syntax:-
if (test - expression 1) {
statement1;
} else if (test - expression 2) {
Statement2;
} else if (test - expression 3) {
Statement3;
} else if (test - expression n) {
Statement n;
} else {
13
default;
}
Statement x;
This type of structure is known as the else if ladder.
Switch Statements:-
The switch statement allows us to execute one code block among many alternatives.
You can do the same thing with the if...else..if ladder. However, the syntax of
the switch statement is much easier to read and write.
Syntax:-
Switch (expression )
{
case constant1:
//statements
break;
case constant2:
// statements
break;
.
default:
//default statements
}
Sample Programs:-
1) Program to find whether a given number is positive or not.
2) Program to find greatest of two numbers.
3) Program to find greatest of three numbers using nested if/else if statements only.
4) Program to find greatest of three numbers using & operator.
5) Program to find whether a given is divisible by 5 and 11.
6) Program to find whether a given number is even or odd.
7) Program to check the validity of a triangle when three angles are given.
8) Given the marks of a student studying five different subject. Calculate average
marks ofstudents and assign him/her Grade based on following:Marks is equal or
greater than 90 – Grade AMarks equal or more than 75 and less than 90 –Grade
BMarks equal or more than 60 and less than 75 –Grade CMarks equal or more than
50 and less than 60 –Grade D Marks less than 50 –Grade F
9) Program to print day of a week using switch case statement.
10) Program to design a simple calculate using switch-case statements.
14
4 Module Loops:-
A loop statement allows us to execute a statement or group of statements multiple times.
Given below is the general form of a loop statement in most of the programming languages
−
1 While loop-
Repeats a statement or group of statements while a given condition is true. It tests the condition
before executing the loop body.
Syntax:
While(test condition)
{
Body of the loop
}
2 For loop-
Executes a sequence of statements multiple times and abbreviates the code that manages the
loop variable.
Syntax:-
For(initialization; test condition; increment or decrement)
{
Body of the loop
}
3 do...while loop:-
It is more like a while statement, except that it tests the condition at the end of the loop body.
15
Syntax:-
do
{
body of the loop
}
While (test condition);
Sample Program:-
1) Program to print counting 1 to 10 using all loop
2) Program to print table of any number.
3) Program to print the factorial of given number.
4) Program to print the sum of digits of a given number.
5) Program to print the Fibonacci series up to 10 level.
6) Program to find whether the given number is Armstrong or Not.
7) Program to find whether the given number is Palindrome or Not.
8) Program to find whether the given number is prime or not.
9) Program to reverse the digits of a given number.
5 Module Array:-
The syntax is the same as for a normal variable declaration except the variable name should
be followed by subscripts to specify the size of each dimension of the array. Array is defined
as the collection of similar type of data items stored at contiguous memory locations.
Arrays are the derived data type in C programming language which can store the primitive
type of data such as int, char, double, float, etc. The general form for an array declaration
would be:-
1) 1-D Array
2) 2-D array
1-D Array-
One dimensional array is an array that has only one subscript specification that is needed to
specify a particular element of an array. A one-dimensional array is a structured collection of
components (often called array elements) that can be accessed individually by specifying the
position of a component with a single index value.
Syntax:-data-type arr_name[array_size];
2- DArray-
The two-dimensional array can be defined as an array of arrays. The 2D array is organized as
matrices which can be represented as the collection of rows and columns. However, 2D
arrays are created to implement a relational database lookalike data structure. It provides ease
of holding the bulk of data at once which can be passed to any number of functions wherever
required.
Syntax:-data_type array_name[rows][columns];
16
Sample Program:-
6 Module Functions:-
In c, we can divide a large program into the basic building blocks known as function. The
function contains the set of programming statements enclosed by {}. A function can be called
multiple times to provide reusability and modularity to the C program. In other words, we can
say that the collection of functions creates a program. The function is also known
as procedure or subroutine in other programming languages.
Syntax:-
Syntax:-
return_type function_name(data_type parameter...)
{
//code to be executed
}
Types of Functions:-
1. Library Functions: are the functions which are declared in the C header files such as
scanf(), printf(), gets(), puts(), ceil(), floor() etc.
2. User-defined functions: are the functions which are created by the C programmer, so
that he/she can use it many times. It reduces the complexity of a big program and
optimizes the code.
Sample Program:-
1) Program to create function to add two numbers.
2) Program to create a function to swap two numbers using call by value.
17
3) Program to generate Fibonacci series using recursive function.
4) Program to swap two integers using call by value and call by reference methods
of passing arguments to a function.
7 Module Pointers:-
The pointer in C language is a variable which stores the address of another variable. This
variable can be of type int, char, array, function, or any other pointer. The size of the pointer
depends on the architecture. By the help of * (indirection operator), we can print the value
of pointer variable p.
Syntax:-
data_ type * pointer_ name;
Sample Program:-
1) Program to understand basic use of pointers.
2) Program to implement call by reference for swapping of two numbers.
3) Program to calculate factorial of a number using recursion.
4) Program to Fibonacci series up to 20 using recursive numbers.
8 Module Structure:-
Structure in c is a user-defined data type that enables us to store the collection of different
data types. Each element of a structure is called a member. Structures ca; simulate the use of
classes and templates as it can store various information. The ,struct keyword is used to
define the structure.
Syntax:-
struct tag _name
{
data_type member1;
data_type member2;
------------- ------------
------------- ------------
};
Sample Program:-
1) Program to find user define data type namely student and implement it using array in
structure.
File handling in C enables us to create, update, read, and delete the files stored on the local
file system through our C program. The following operations can be performed on a file.
18
o Writing to the file
o Deleting the file
There are many functions in the C library to open, read, write, search and close the file. A list
of file functions are given below:
Sample Program:-
1) WAP to read a simple file using file handling.
2) WAP to write data in file.
3) WAP to append data in existing file.
Linear Search:-
A linear search, also known as a sequential search, is a method of finding an element
within a list. It checks each element of the list sequentially until a match is found or the
19
whole list has been searched.
Algorithm:-
Linear Search ( Array A, Value x)
Step 1: Set i to 1
Step 2: if i > n then go to step 7
Step 3: if A[i] = x then go to step 6
Step 4: Set i to i + 1
Step 5: Go to Step 2
Step 6: Print Element x Found at index i and go to step 8
Step 7: Print element not found
Step 8: Exit
Binary search:-
Binary search is a fast search algorithm with run-time complexity of Ο(log n). This search
algorithm works on the principle of divide and conquer. For this algorithm to work properly,
the data collection should be in the sorted form.
Binary search looks for a particular item by comparing the middle most item of the
collection. If a match occurs, then the index of item is returned. If the middle item is greater
than the item, then the item is searched in the sub-array to the left of the middle item.
Otherwise, the item is searched for in the sub-array to the right of the middle item. This
process continues on the sub-array as well until the size of the subarray reduces to zero.
Procedure binary_search:-
A ← sorted array
n ← size of array
x ← value to be searched
Set lowerBound = 1
Set upperBound = n
if A[midPoint] < x
set lowerBound = midPoint + 1
if A[midPoint] > x
set upperBound = midPoint - 1
if A[midPoint] = x
EXIT: x found at location midPoint
end while
end procedure
20
Sample Program:-
1) Write a program that uses function to search for a key value in a given list of
integer using linear search method.
2) Write a program that uses function to search for a key value in a given sorted
list of integer using Binary search method.
Sorting:-
Sorting refers to arranging data in a particular format. Sorting algorithm specifies the way to
arrange data in a particular order. Most common orders are in numerical or lexicographical
order.
Bubble Sort:-
Bubble sort is a simple sorting algorithm. This sorting algorithm is comparison-based
algorithm in which each pair of adjacent elements is compared and the elements are
swapped if they are not in order. This algorithm is not suitable for large data sets as its
average and worst case complexity are of Ο(n2) where n is the number of items.
begin BubbleSort(list)
return list
end BubbleSort
Insertion sort:-
This is an in-place comparison-based sorting algorithm. Here, a sub-list is maintained which
is always sorted. For example, the lower part of an array is maintained to be sorted. An
element which is to be 'insert'ed in this sorted sub-list, has to find its appropriate place and
then it has to be inserted there. Hence the name, insertion sort.
The array is searched sequentially and unsorted items are moved and inserted into the sorted
sub-list (in the same array). This algorithm is not suitable for large data sets as its average
and worst case complexity are of Ο(n2), where n is the number of items.
Step 1 − If it is the first element, it is already sorted. return 1;
Step 2 − Pick next element
Step 3 − Compare with all elements in the sorted sub-list
Step 4 − Shift all the elements in the sorted sub-list that is greater than the
value to be sorted
Step 5 − Insert the value
21
Step 6 − Repeat until list is sorted
Selection Sort:-
Selection sort is a simple sorting algorithm. This sorting algorithm is an in-place comparison-
based algorithm in which the list is divided into two parts, the sorted part at the left end and
the unsorted part at the right end. Initially, the sorted part is empty and the unsorted part is the
entire list.
The smallest element is selected from the unsorted array and swapped with the leftmost
element, and that element becomes a part of the sorted array. This process continues moving
unsorted array boundary by one element to the right.
This algorithm is not suitable for large data sets as its average and worst case complexities
are of Ο(n2), where n is the number of items.
Algorithm:-
Step 1 − Set MIN to location 0
Step 2 − Search the minimum element in the list
Step 3 − Swap with value at location MIN
Step 4 − Increment MIN to point to next element
Step 5 − Repeat until list is sorted
Merge Sort:-
Merge sort is a sorting technique based on divide and conquer technique. With worst-case
time complexity being Ο(n log n), it is one of the most respected algorithms.Merge sort first
divides the array into equal halves and then combines them in a sorted manner.
Quick sort:-
Quick sort is a highly efficient sorting algorithm and is based on partitioning of array of data
into smaller arrays. A large array is partitioned into two arrays one of which holds values
smaller than the specified value, say pivot, based on which the partition is made and another
array holds values greater than the pivot value. Quick sort partitions an array and then calls
itself recursively twice to sort the two resulting subarrays. This algorithm is quite efficient
for large-sized data sets as its average and worst-case complexity are O(n2), respectively.
22
Step 8 − if left ≥ right, the point where they met is new pivot
Sample Programs:-
1) Write a C program that implements the Bubble sort method to sort a given list of
integers in ascending/ descending order.
2) Write a C program that sorts the given array of integers using selection
sort in descendingorder
3) Write a C program that sorts the given array of integers using insertion
sort in ascendingorder
4) Write a c program that sorts the given array of integers using quick sort and merge
sort.
23