You are on page 1of 15

See discussions, stats, and author profiles for this publication at: https://www.researchgate.

net/publication/306482093

Computer programming in c lab manual

Book · February 2016

CITATIONS READS

0 21,992

1 author:

Bhaskar Mondal
National Institute of Technology Patna
55 PUBLICATIONS   569 CITATIONS   

SEE PROFILE

Some of the authors of this publication are also working on these related projects:

Lightweight Encryption Techniques View project

Artificial Intelligence Aided Forecasting of Air Quality Index View project

All content following this page was uploaded by Bhaskar Mondal on 25 August 2016.

The user has requested enhancement of the downloaded file.


Computer Programming with C
Laboratory Manual
Subject Code: CS109
Semester: I
Year: 2015- 16 (Spring Semester)

August 13, 2015

This Laboratory Manual was initiated by me in 2011. In 2014 Mr. Saurabh


Singh Thakur (Currently PhD Research Scholar at IIT Kharagpur) had
modified it, which is included in this 2015 version.
Faculty:
Mr. Bhaskar Mondal

Department of Computer Science and Engineering


National Institute of Technology Jamshedpur
Jamshedpur, Jharkhand, India- 831014
Faculty: Bhaskar Mondal, Email:bm6779@gmail.com Computer Programming with C

Contents

1 Fundamental of Computer 1

2 Write, Compile and Run C Programme on Linux 4

3 Before you start 5

4 Basics of C Programming 6

5 Decision making & Control flow 7

6 Functions and Recursions 9

7 Array and String 11

8 Structure Union and File Handling 12

9 Advanced Assignments 13

10 Books to Follow 13

Instructions
• Maintain your Lab Record regularly.
• Practice all programs by your own. Copying the solution from others will be
penalized.
• Maintain Index/ content properly.
• Brief descriptions including algorithm used and flowchart of the work you did
for each exercise.
• Copies of the C programme you written for the exercises, along with the results.
• You must provide Test Cases/sample Input and Output at the end of exercise.
• Explanations of anything unusual or interesting, or points of confusion that you
were unable to resolve outside lab.
• If you believe I have an error in a lab, please inform me of it. Explain why you
think it is an error and, if you like, suggest a correction.
• Save the C program files in a separate folder on PC (in Lab), also take your
respective C program files with yourself in Pen-Drive.

1 Fundamental of Computer

Version: 1.0 Page 1


Faculty: Bhaskar Mondal, Email:bm6779@gmail.com Computer Programming with C

Figure 1: The computer: top-level structure 1

Figure 2: The CPU. 2

Figure 3: The CPU 3

Version: 1.0 Page 2


Faculty: Bhaskar Mondal, Email:bm6779@gmail.com Computer Programming with C

Version: 1.0 Page 3


Faculty: Bhaskar Mondal, Email:bm6779@gmail.com Computer Programming with C

2 Write, Compile and Run C Programme on Linux


To compile a C or C + + program on any Linux distribution such as Ubuntu, Red Hat,
Fedora, Debian and other Linux distribution you will need:
1. GNU C and C + + compiler collection
2. Development tools
3. Development libraries
4. IDE or text editor to write programs
In most cases these are already installed.

To verify installation run these command from terminal

$ whereis gcc
$ which gcc
$ gcc --version
$

If gcc is not installed, if you are using Debian or Ubuntu Linux, type the following
apt-get command to install GNU c/c++ compiler:

$ sudo apt-get update


$ sudo apt-get install build-essential manpages-dev

Write your programme in any of the editors that are available under Linux such as
gedit, vi or emacs or any other editor. I like to use gedit, to use gedit open terminal and
type

gedit myfirstprog.c

It will create and open a file named myfirstprog.c for you where you can type your c
code. for example:

#include<stdio.h>
/* myfirstprog.c: My first C program on a Linux */
int main(void)
{
printf("Hello World \n");
return 0;
}

Save the file and close the file.

Complie and Run by

$ gcc -o myfirstprog myfirstprog.c


$./myfirstprog

Version: 1.0 Page 4


Faculty: Bhaskar Mondal, Email:bm6779@gmail.com Computer Programming with C

Source Code myprog.c

Preprocessor
Preprossed Code myprog.i

Compiler
Assembly Code myprog.s

Assembler
Object Code myprog.o
Library Files
Linker / Other object �les/
LinkEditor Modules
Executable Code myfprog.exe
Run time Objects,
Loader Module,
Library, etc.

Execution on target Machine

Figure 4: Compilation of a C programme

3 Before you start

Version: 1.0 Page 5


Faculty: Bhaskar Mondal, Email:bm6779@gmail.com Computer Programming with C

Evaluate the
Problem

Test and Gather


Review Information
1

8 2

Examine Problem Break Problem


7 3
Results Solving into Parts

4
6
5
Take Identify
Action Solutions

Select Best
Solution

4 Basics of C Programming

Type Storage Value range Specifier


size
char 1 byte -128 to 127 or 0 to 255 %c
unsigned char 1 byte 0 to 255 %c
signed char 1 byte -128 to 127 %c
int 2 or 4 bytes -32,768 to 32,767 or -2,147,483,648 to %d
2,147,483,647
unsigned int 2 or 4 bytes 0 to 65,535 or 0 to 4,294,967,295 %u
short 2 bytes -32,768 to 32,767 %i
unsigned short 2 bytes 0 to 65,535
long 4 bytes -2,147,483,648 to 2,147,483,647 %ld
unsigned long 4 bytes 0 to 4,294,967,295 %ud
float 4 byte 1.2E-38 to 3.4E+38 6 decimal places %f
double 8 byte 2.3E-308 to 1.7E+308 15 decimal places %e, %lf
long double 10 byte 3.4E-4932 to 1.1E+4932 19 decimal
places

Table 1: Data Types in C

1. Write a program to calculate the area of a circle.


2. Write a program to print the ASCII value of a character.
3. Write a program to read a character in upper case and then print it in lower case.
4. Write a program to swap two numbers using a temporary variable.
5. Write a program to swap two numbers without using a temporary variable.
6. Write a program to calculate the average of two numbers. Also print their devia-

Version: 1.0 Page 6


Faculty: Bhaskar Mondal, Email:bm6779@gmail.com Computer Programming with C

tion.
7. Write a program to convert degrees Fahrenheit into degrees Celsius.
8. Write a program that displays the size of every data type.
9. The distance between two cities(in KM) is input through the keyboard. Write a
program to convert and print this distance in meters, feet, inches and centimeters.
10. The length and breadth of a rectangle and radius of a circle are input through the
keyboard. Write a program to calculate the area & perimeter of the rectangle, and
the area & circumference of the circle.
11. If a five-digit number is input through the keyboard, write a program to print a
new number by adding one to each of its digits. For example, if the number that
is input is 12391, then the output should be displayed as 23502.
12. Write a program to calculate the euclidean distance between two points. [hint:
include math.h, use sqrt() & pow() functions]
13. Write a program to calculate the bill amount for an item given its quantity sold,
value, discount and tax.
14. Write a program to convert a floating point number into corresponding integer.
15. Write a program to convert an integer into the corresponding floating point num-
ber.
16. Write a program to calculate a student’s result based on two examinations, one
sport event, and three activities conducted. The Weightage of activities = 30%,
sports = 20%, and examination = 50%.
17. In a town, the percentage of men is 52. The percentage of total literacy is
18. If total percentage of literate men is 35 of the total population, write a program to
find the total number of illiterate men and women if the population of the town is
80,000.
19. Write a program to enter an integer number and display its equivalent values in
binary, octal and hexadecimal.

5 Decision making & Control flow


1. Write a program to find the larger of two numbers.
2. Write a program to find greater of three numbers.
3. Write a program to find whether the given number is even or odd.
4. Write a program to enter any character. If the entered character is in lower case
then convert it into upper case and if it is a lower case character then convert it
into upper case.
5. Write a program to enter a character and then determine whether it is a vowel or
not.
6. Write a program to find whether a given year is a leap year or not. Use the logical
operators && and ||.
7. A company decides to give bonus to all its employees on Diwali. A 5% bonus
on salary is given to the male workers and 10% bonus on salary to the female
workers. Write a program to enter the salary and sex of the employee. If the
salary of the employee is less than Rs.10,000 then the employee gets an extra 2%
bonus on salary. Calculate the bonus that has to be given to the employee and
display the salary that the employee will get.
8. Write a program to calculate the roots of a quadratic equation.

Version: 1.0 Page 7


Faculty: Bhaskar Mondal, Email:bm6779@gmail.com Computer Programming with C

9. If the three sides of a triangle are entered through the keyboard, write a program
to check whether the triangle is valid or not. The triangle is valid if the sum of
two sides is greater than the largest of the three sides.
10. If the three sides of a triangle are entered through the keyboard, write a program to
check whether the triangle isosceles, equilateral, scalene or right angled triangle.
11. In a company, worker efficiency is determined on the basis of the time required for
a worker to complete a particular job. If the time taken by the worker is between
2-3 hours, then the worker is said to be highly efficient. If the time required by
the worker is between 3-4 hours, then the worker is ordered to improve speed. If
the time taken is between 4-5 hours, the worker is given training to improve his
speed, and if the time taken by the worker is more than 5 hours, then the worker
has to leave the company. If the time taken by the worker is input through the
keyboard, write a program to find the efficiency of the worker.
12. Any character is entered through the keyboard, write a program to determine
whether the character entered is a capital letter, a small case letter, a digit or a
special symbol. The following table shows the range of ASCII values for various
characters.

Characters ASCII Values


A-Z 65-90
a-z 97-122
0-9 48-57
Special symbols 0-47, 58-64, 91-96, 123-127

Table 2

13. According to the Gregorian calendar, it was Monday on the date 01 January 2001.
If any year is input through the keyboard write a program to find out what is the
day on 1st January of this year.
14. A five digit number is entered through the keyboard. Write a program to obtain
the reversed number and to determine whether the original and reversed numbers
are equal or not.
15. A certain grade of steel is graded according to the following conditions:
(a) Hardness must be greater than 50
(b) Carbon content must be less than 0.7
(c) Tensile strength must be greater than 5600
The grades are as follows:
(a) Grade is 10 if all the three conditions are met
(b) Grade is 9 if conditions (i) and (ii) are met
(c) Grade is 8 if conditions (ii) and (iii) are met
(d) Grade is 7 if conditions (i) and (iii) are met
(e) Grade is 6 if only one condition is met
(f) Grade is 5 if none of the conditions are met
Write a program, which will require the user to give values of hardness, carbon
content and tensile strength of the steel under considerations and output the grade
of the steel.
16. The policy followed by company to process customer orders is given by the fol-
lowing rules:

Version: 1.0 Page 8


Faculty: Bhaskar Mondal, Email:bm6779@gmail.com Computer Programming with C

(a) If a customer ordered quantity is less than or equal to that in stock and his
credit is OK, supply his requirement.
(b) If his credit is not OK do not supply. Send him intimation.
(c) If his credit is OK but the item in stock is less than his order, supply what is
in stock. Intimate to him the date on which the balance will be shipped.
Write a C program to implement the company policy.
17. Given three points (x1, y1), (x2, y2)and(x3, y3), write a program to check if all
the three points fall on one straight line.
18. Given the coordinates (x,y) of a center of a circle and it’s radius, write a program
which will determine whether a point lies inside the circle, on the circle or outside
the circle.
19. Given a point (x, y), write a program to find out if it lies on the x-axis, y-axis or
on the origin, viz (0, 0).
20. Write a program to calculate energy bill. Read the starting and ending meter
readings. The charges are as follows:

No. of units Consumed rates in (Rs.)


200 – 500 3.50
100 – 200 2.50
Less than 100 1.50

6 Functions and Recursions


1. Design and develop a c program to add first seven terms of the following series
of equation 1 using a for loop:
1 2 3
+ + + ··· (1)
1 2 3
2. Write a program to fill the entire screen with a smiling face. The smiling face has
an ASCII value 1.
3. The natural logarithm can be approximated by the following series in equation 2.
 2  3  4
x−1 1 x−1 1 x−1 1 x−1
+ + + + ··· (2)
x 2 x 2 x 2 x
If x is input through the keyboard, write a program to calculate the sum of first
seven terms of this series.
4. Write a program to produce the following output in pattern 3:
5. Write a program to produce the following output pattern no 4:
6. Write a program to find the grace marks for a student using switch. The user
should enter the class obtained by the student and the number of subjects he has
failed in. Use the following logic:
• If the student gets first class and the number of subject he failed in is greater
than 3, then he does not get any grace. If the number of subjects he failed in
is less than or equal to 3, then the grace is of 5 marks per subject.
• If the student gets second class and the number of subjects he failed in is
greater than 2, then he does not get any grace. If the number of subjects he
failed in is less than or equal to 2, the grace is of 4 marks per subject.

Version: 1.0 Page 9


Faculty: Bhaskar Mondal, Email:bm6779@gmail.com Computer Programming with C

A B C D E F G F E D C B A
A B C D E F F E D C B A
A B C D E E D C B A
A B C D D C B A
A B C C B A
A B B A
A A

Table 3: pattern

1
2 3
4 5 6
7 8 9 10

Table 4: pattern

• If the student gets third class and the number of subjects he failed in is
greater than 1, then he does not get any grace. If the number of subjects he
failed in is equal to 1, then the grace is of 5 marks per subject.
7. Write a recursive function to obtain the first 25 numbers of a Fibonacci sequence.
In a Fibonacci sequence the sum of two successive terms gives the third term. Fol-
lowing are the first few terms of the Fibonacci sequence: 1, 1, 2, 3, 5, 8, 13, 21, 34 . . .
8. Write a function to compute the distance between two points and use it to develop
another function that will compute the area of the triangle whose vertices are
A(x1 , y1 ), B(x2 , y2 ), andC(x3 , y3 ). Use these functions to develop a function
which returns a value 1 if the point (x,y) lines inside the triangle ABC, otherwise
a value 0.
9. Write a function to compute the greatest common divisor given by Euclid’s algo-
rithm, exemplified for J = 1980, K = 1617 as follows:
1980 / 1617 = 1 1980 – 1 * 1617 = 363
1617 / 363 = 4 1617 – 4 * 363 = 165
363 / 165 = 2 363 – 2 * 165 = 33
5 / 33 = 5 165 – 5 * 33 = 0
Thus, the greatest common divisor is 33.
10. Write a function that will calculate and display the real roots of the quadratic
equation 3
ax2 + bx + c = 0 (3)
using the quadratic formula in 4

−b ± b2 − 4ac
x= (4)
2ac
Assume that a, b and c are floating-point arguments whose values are given, and
that x1 and x2 are floating-point variables. Also, assumes that b2 > 4 × a × c, so
that the calculated roots will always be real.
Now write a complete C program that will calculate the real roots of the quadratic
equation ax2 + bx + c = 0 using the quadratic formula, as described above. Read

Version: 1.0 Page 10


Faculty: Bhaskar Mondal, Email:bm6779@gmail.com Computer Programming with C

the coefficient a, b and c in the main portion of the program. Then access the
function written for the preceding problem in order to obtain the desired solution.
Finally, display the values of the coefficients, followed by the calculated values
of x1 and x2 . Be sure that all of the output is clearly labeled.
11. A positive integer is entered through the keyboard, write a function to find the
binary equivalent of this number using recursion.
12. Following is the menu to be displayed to the user. On selecting a choice display
appropriate result. Number should be accepted from the user.
• Prime Factors
• Leap Year
• Sum of all digits
• Number in reverse order
13. Write macro definitions with arguments for calculation of Simple Interest and
Amount. Store these macro definitions in a file called “interest.h”. Include this
file in your program, and use the macro definitions for calculating simple interest
and amount.
14. Write down macro definitions for the following:
• To find arithmetic mean of two numbers.
• To find absoloute value of a number.
• To convert a uppercase alphabet to lowercase.
• To obtain the bigger of two numbers.

7 Array and String


1. Write a program to insert an element at any position (determined by user) into an
existing array filled up with some elements. [Note: No existing element should
be deleted from array]
2. Write a program to delete an element from an array.
3. Write a program to find smallest and largest number present in an array.
4. Write a program to find the 2nd smallest element present in an array. [Note: Do
not change the arrangements of elements in array]
5. Write a program to sort the elements of an array in increasing order.
6. Write a method that takes as its parameter an array of integers and returns the sum
of the values in the array. Further Write a complete program to use this method.
7. Write a method that takes as its parameter an array of integers and returns the
minimum of the values in the array. (Assume the length of the array is greater
than zero.) Further Write a complete program to use this method.
8. Write a method that takes as its parameters two arrays of integers and returns
the dot product of the two (i.e., the sum of the products of the corresponding
elements). Assume the two arrays have the same length. Further Write a complete
program to use this method.
9. Write a method that takes as its parameter an array a of integers and returns a
new array of the same length, where each entry is the corresponding value in a
multiplied by its index in the array. Further Write a complete program to use this
method.
10. Write a method that takes as its parameters two arrays of integers and returns
a new array where the value at each index is the sum of the corresponding two

Version: 1.0 Page 11


Faculty: Bhaskar Mondal, Email:bm6779@gmail.com Computer Programming with C

elements of the given arrays at the same index. Assume the arrays are of equal
length. Further Write a complete program to use this method.
11. Write a method that takes as its parameters two arrays of integers and returns
a new array where the value at each index is the sum of the corresponding two
elements of the given arrays at the same index. Do not assume the arrays are of
equal length. Pretend that the shorter array is padded with zeros at the end. (For
example, if the arrays are of length 3 and 5, your result should be as if the shorter
array had zeros in the "missing" slots.) Further Write a complete program to use
this method.
12. Write a method that takes as its parameter an array a of integers and modifies the
given array so that it contains a running sum of its original values. For example, if
the array originally had the values [3 2 4 7], after running your method that array
would instead contain [3 5 9 16], and if you ran it another time on the same array,
you’d have [3 8 17 33]. Further Write a complete program to use this method.
13. Write a method that takes as its parameter an "two dimensional?" array a of in-
tegers and fills the main diagonal with the value 1. (The main diagonal consists
of those entries whose row and column index are equal.) Assume the two dimen-
tional array is square. Further Write a complete program to use this method.
14. Write a method that takes an integer parameter n. It should create and return an
array of n arrays of integers, where the array for row 0 has length 0, the array
for row 1 has length 1, the array for row 2 has length 2, etc. All values in the
arrays can remain uninitialized (0). Further Write a complete program to use this
method.
15. Write a method that takes an array of String objects and returns a single String
that results from concatenating all the strings together, separated by spaces. Do
not add a space after the last element, nor before the first one. Further Write a
complete program to use this method.

8 Structure Union and File Handling


1. Write a program to delete all vowels from a sentence. Assume that the sentence
is not more than 80 characters long.
2. Write a program that will read line and delete from it all occurrences of the word
‘the’.
3. Write a program to count the number of occurrences of any two vowels in succes-
sion in a line of text. For, example, in the sentence “Please read this application
and give me gratuity” such occurrences are ea, ea, ui.
4. Write a menu driven program that depicts the working of a library. The menu
options should be:
(a) Add book Information
(b) Display book information
(c) List all books of given author
(d) List the title of specified book
(e) List the count of books in the library
(f) List the books in the order of accession number
(g) Exit
Create a structure called library to hold accession number, title of the book, author

Version: 1.0 Page 12


Faculty: Bhaskar Mondal, Email:bm6779@gmail.com Computer Programming with C

name, price of the book, and flag indicating whether book is issued or not
5. Create a structure to specify data on students given below: Roll number, Name,
Department, Course, Year of joining. Assuming that there are not more than 100
students in the college.
(a) Write a function to print names of all students who joined in a particular
year.
(b) Write a function to print the data of a student whose roll number is given.
6. Write a program that compares two given dates. To store a date use a structure
that contains three members namely date, month and year. If the dates are equal
then display message as “Equal” otherwise “Unequal”.
7. Write a program to read a file and display its contents along with line numbers
before each line.
8. Rewrite Program no. 5 (above) using suitable File operations.
9. Suppose a file contains student’s record with each record containing name and age
of a student. Write a program to read these records and display them in sorted
order by name.

9 Advanced Assignments
will added soon.

10 Books to Follow
1 Let Us C, Author: Yashavant Kanetkar, Publisher BPB Publications, 2002 ISBN
8176566217, 9788176566216, Online:
https://https://books.google.co.in/books/about/LetU sC .html?id = 6XrjAAAACAAJ
2 Title Programming in ANSI C, Balagurusamy, Publisher: Tata McGraw-Hill Educa-
tion, 2008, ISBN 0070648220, 9780070648227, Online:https://https://books.google.co.in/books/
AokcsKn − 1iIC
3 Schaum’s Outline of Programming with C, Byron Gottfried, Edition 2, illustrated
Publisher McGraw-Hill Education, 1996, ISBN 0070240353, 9780070240353

Evaluation Scheme
EC Evaluation Data & Nature of
Duration Weightage
No. Component Time Component

You May Meet Me:Every day 5:00pm.


You may mail me at bm.6779@gmail.com; (always mention your Roll Number fol-
lowed by Subject at the subject field.)

Version: 1.0 Page 13

View publication stats

You might also like