Computer programming in c lab manual

14
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

Transcript of Computer programming in c lab manual

Page 1: Computer programming in c lab manual

Computer Programming with C

Laboratory ManualSubject Code: CS109

Semester: I

Year: 2015- 16 (Spring Semester)

August 13, 2015

This Laboratory Manual was initiated by me in 2011. In 2014 Mr. SaurabhSingh 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 EngineeringNational Institute of Technology Jamshedpur

Jamshedpur, Jharkhand, India- 831014

Page 2: Computer programming in c lab manual

Faculty: Bhaskar Mondal, Email:[email protected] 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

Page 3: Computer programming in c lab manual

Faculty: Bhaskar Mondal, Email:[email protected] 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

Page 4: Computer programming in c lab manual

Faculty: Bhaskar Mondal, Email:[email protected] Computer Programming with C

Version: 1.0 Page 3

Page 5: Computer programming in c lab manual

Faculty: Bhaskar Mondal, Email:[email protected] Computer Programming with C

2 Write, Compile and Run C Programme on LinuxTo 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 collection2. Development tools3. Development libraries4. 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 followingapt-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 asgedit, vi or emacs or any other editor. I like to use gedit, to use gedit open terminal andtype

gedit myfirstprog.c

It will create and open a file named myfirstprog.c for you where you can type your ccode. 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

Page 6: Computer programming in c lab manual

Faculty: Bhaskar Mondal, Email:[email protected] Computer Programming with C

Preprocessor

Compiler

Assembler

Linker / LinkEditor

Loader

Source Code myprog.c

Preprossed Code myprog.i

Assembly Code myprog.s

Object Code myprog.o

Executable Code myfprog.exe

Library Files

Other object �les/

Modules

Execution on target Machine

Run time Objects,

Module,

Library, etc.

Figure 4: Compilation of a C programme

3 Before you start

Version: 1.0 Page 5

Page 7: Computer programming in c lab manual

Faculty: Bhaskar Mondal, Email:[email protected] Computer Programming with C

Problem Solving

1

2

3

4

5

6

7

8

Evaluate the

Problem

Select Best

Solution

Examine

Results

Test and

Review

Gather

Information

Identify

Solutions

Take

Action

Break Problem

into Parts

4 Basics of C Programming

Type Storagesize

Value range Specifier

char 1 byte -128 to 127 or 0 to 255 %cunsigned char 1 byte 0 to 255 %csigned char 1 byte -128 to 127 %cint 2 or 4 bytes -32,768 to 32,767 or -2,147,483,648 to

2,147,483,647%d

unsigned int 2 or 4 bytes 0 to 65,535 or 0 to 4,294,967,295 %ushort 2 bytes -32,768 to 32,767 %iunsigned short 2 bytes 0 to 65,535long 4 bytes -2,147,483,648 to 2,147,483,647 %ldunsigned long 4 bytes 0 to 4,294,967,295 %udfloat 4 byte 1.2E-38 to 3.4E+38 6 decimal places %fdouble 8 byte 2.3E-308 to 1.7E+308 15 decimal places %e,%lflong 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

Page 8: Computer programming in c lab manual

Faculty: Bhaskar Mondal, Email:[email protected] 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, andthe area & circumference of the circle.

11. If a five-digit number is input through the keyboard, write a program to print anew number by adding one to each of its digits. For example, if the number thatis 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 is18. 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 is80,000.

19. Write a program to enter an integer number and display its equivalent values inbinary, octal and hexadecimal.

5 Decision making & Control flow1. 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 itinto upper case.

5. Write a program to enter a character and then determine whether it is a vowel ornot.

6. Write a program to find whether a given year is a leap year or not. Use the logicaloperators && and ||.

7. A company decides to give bonus to all its employees on Diwali. A 5% bonuson salary is given to the male workers and 10% bonus on salary to the femaleworkers. Write a program to enter the salary and sex of the employee. If thesalary 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 anddisplay the salary that the employee will get.

8. Write a program to calculate the roots of a quadratic equation.

Version: 1.0 Page 7

Page 9: Computer programming in c lab manual

Faculty: Bhaskar Mondal, Email:[email protected] Computer Programming with C

9. If the three sides of a triangle are entered through the keyboard, write a programto check whether the triangle is valid or not. The triangle is valid if the sum oftwo 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 tocheck 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 fora worker to complete a particular job. If the time taken by the worker is between2-3 hours, then the worker is said to be highly efficient. If the time required bythe worker is between 3-4 hours, then the worker is ordered to improve speed. Ifthe time taken is between 4-5 hours, the worker is given training to improve hisspeed, and if the time taken by the worker is more than 5 hours, then the workerhas to leave the company. If the time taken by the worker is input through thekeyboard, write a program to find the efficiency of the worker.

12. Any character is entered through the keyboard, write a program to determinewhether the character entered is a capital letter, a small case letter, a digit or aspecial symbol. The following table shows the range of ASCII values for variouscharacters.

Characters ASCII ValuesA-Z 65-90a-z 97-1220-9 48-57Special 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 theday on 1st January of this year.

14. A five digit number is entered through the keyboard. Write a program to obtainthe reversed number and to determine whether the original and reversed numbersare 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, carboncontent and tensile strength of the steel under considerations and output the gradeof the steel.

16. The policy followed by company to process customer orders is given by the fol-lowing rules:

Version: 1.0 Page 8

Page 10: Computer programming in c lab manual

Faculty: Bhaskar Mondal, Email:[email protected] Computer Programming with C

(a) If a customer ordered quantity is less than or equal to that in stock and hiscredit 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 allthe 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 programwhich will determine whether a point lies inside the circle, on the circle or outsidethe circle.

19. Given a point (x, y), write a program to find out if it lies on the x-axis, y-axis oron the origin, viz (0, 0).

20. Write a program to calculate energy bill. Read the starting and ending meterreadings. The charges are as follows:

No. of units Consumed rates in (Rs.)200 – 500 3.50100 – 200 2.50Less than 100 1.50

6 Functions and Recursions1. Design and develop a c program to add first seven terms of the following series

of equation 1 using a for loop:

1

1+

2

2+

3

3+ · · · (1)

2. Write a program to fill the entire screen with a smiling face. The smiling face hasan ASCII value 1.

3. The natural logarithm can be approximated by the following series in equation 2.

x− 1

x+

1

2

(x− 1

x

)2

+1

2

(x− 1

x

)3

+1

2

(x− 1

x

)4

+ · · · (2)

If x is input through the keyboard, write a program to calculate the sum of firstseven 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 hasfailed 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 inis 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 hefailed in is less than or equal to 2, the grace is of 4 marks per subject.

Version: 1.0 Page 9

Page 11: Computer programming in c lab manual

Faculty: Bhaskar Mondal, Email:[email protected] Computer Programming with C

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

Table 3: pattern

12 3

4 5 67 8 9 10

Table 4: pattern

• If the student gets third class and the number of subjects he failed in isgreater than 1, then he does not get any grace. If the number of subjects hefailed 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 developanother function that will compute the area of the triangle whose vertices areA(x1, y1), B(x2, y2), andC(x3, y3). Use these functions to develop a functionwhich returns a value 1 if the point (x,y) lines inside the triangle ABC, otherwisea 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 = 3631617 / 363 = 4 1617 – 4 * 363 = 165363 / 165 = 2 363 – 2 * 165 = 335 / 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 3ax2 + bx+ c = 0 (3)

using the quadratic formula in 4

x =−b±

√b2 − 4ac

2ac(4)

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

Version: 1.0 Page 10

Page 12: Computer programming in c lab manual

Faculty: Bhaskar Mondal, Email:[email protected] Computer Programming with C

the coefficient a, b and c in the main portion of the program. Then access thefunction written for the preceding problem in order to obtain the desired solution.Finally, display the values of the coefficients, followed by the calculated valuesof 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 thebinary equivalent of this number using recursion.

12. Following is the menu to be displayed to the user. On selecting a choice displayappropriate 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 andAmount. Store these macro definitions in a file called “interest.h”. Include thisfile in your program, and use the macro definitions for calculating simple interestand 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 String1. 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 shouldbe 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 greaterthan zero.) Further Write a complete program to use this method.

8. Write a method that takes as its parameters two arrays of integers and returnsthe dot product of the two (i.e., the sum of the products of the correspondingelements). Assume the two arrays have the same length. Further Write a completeprogram to use this method.

9. Write a method that takes as its parameter an array a of integers and returns anew array of the same length, where each entry is the corresponding value in amultiplied by its index in the array. Further Write a complete program to use thismethod.

10. Write a method that takes as its parameters two arrays of integers and returnsa new array where the value at each index is the sum of the corresponding two

Version: 1.0 Page 11

Page 13: Computer programming in c lab manual

Faculty: Bhaskar Mondal, Email:[email protected] Computer Programming with C

elements of the given arrays at the same index. Assume the arrays are of equallength. Further Write a complete program to use this method.

11. Write a method that takes as its parameters two arrays of integers and returnsa new array where the value at each index is the sum of the corresponding twoelements of the given arrays at the same index. Do not assume the arrays are ofequal length. Pretend that the shorter array is padded with zeros at the end. (Forexample, if the arrays are of length 3 and 5, your result should be as if the shorterarray had zeros in the "missing" slots.) Further Write a complete program to usethis method.

12. Write a method that takes as its parameter an array a of integers and modifies thegiven array so that it contains a running sum of its original values. For example, ifthe array originally had the values [3 2 4 7], after running your method that arraywould 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 consistsof 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 anarray of n arrays of integers, where the array for row 0 has length 0, the arrayfor row 1 has length 1, the array for row 2 has length 2, etc. All values in thearrays can remain uninitialized (0). Further Write a complete program to use thismethod.

15. Write a method that takes an array of String objects and returns a single Stringthat results from concatenating all the strings together, separated by spaces. Donot add a space after the last element, nor before the first one. Further Write acomplete program to use this method.

8 Structure Union and File Handling1. 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 applicationand give me gratuity” such occurrences are ea, ea, ui.

4. Write a menu driven program that depicts the working of a library. The menuoptions 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

Page 14: Computer programming in c lab manual

Faculty: Bhaskar Mondal, Email:[email protected] Computer Programming with C

name, price of the book, and flag indicating whether book is issued or not5. 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 100students in the college.

(a) Write a function to print names of all students who joined in a particularyear.

(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 equalthen display message as “Equal” otherwise “Unequal”.

7. Write a program to read a file and display its contents along with line numbersbefore 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 sortedorder by name.

9 Advanced Assignmentswill added soon.

10 Books to Follow1 Let Us C, Author: Yashavant Kanetkar, Publisher BPB Publications, 2002 ISBN

8176566217, 9788176566216, Online:https://https://books.google.co.in/books/about/LetUsC .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/about/ProgramminginANSIC .html?id =AokcsKn− 1iIC

3 Schaum’s Outline of Programming with C, Byron Gottfried, Edition 2, illustratedPublisher McGraw-Hill Education, 1996, ISBN 0070240353, 9780070240353

Evaluation Scheme

ECNo.

EvaluationComponent

Duration WeightageData &Time

Nature ofComponent

You May Meet Me:Every day 5:00pm.You may mail me at [email protected]; (always mention your Roll Number fol-lowed by Subject at the subject field.)

Version: 1.0 Page 13