0% found this document useful (0 votes)
33 views

FYBScCS - Sem I - LabBook C Programming CS 102 P

Lab book of c programming

Uploaded by

Sakshi Sonawane
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views

FYBScCS - Sem I - LabBook C Programming CS 102 P

Lab book of c programming

Uploaded by

Sakshi Sonawane
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

Savitribai Phule Pune University,Pune

F. Y. B. Sc. (Computer Science)

CS-102-P: Practical course on Problem Solving using ‘C’


Programming Lab Course based on CS-101-T

WorkBook

(From Academic year 2024)

Name :
College Name :
Roll No. : Division :
Academic Year :

K.T.H.M.COLLEGE, NASHIK 1
Preface to the Second Edition
The new syllabus for F.Y.B.Sc. Computer Science is implemented from the academic year 2024. For
the subject CS-102-P: Lab Course based on CS-101-T

It is absolutely necessary and essential that all the Computer Science practicals be conducted on Open
Source Operating System like Linux. All the practicals related to C needs to be conducted using GCC
compiler.

The practical examination will be conducted by the respective colleges at the end of the academic
year, 35 marks will be assigned to performance in practical examination and 15 marks for journals
through continuous assessment.

It is mandatory to carry the completed and duly signed lab book for the practical examination.

Editors:

Prof. Ms. Poonam Ponde Nowrosjee Wadia College


Prof. Ms. Ashwini Kamble Nowrosjee Wadia College

Prof. Ms. Vandana Babrekar Nowrosjee Wadia College


Prof. Ms. Rashmi Baghel Nowrosjee Wadia College

Updated By

Ms.Sunita N.Deore K.T.H.M.College, Nashik


Ms.Ratna S.Chaudhari K.T.H.M.College, Nashik
Ms.Asmita L.Taskar K.T.H.M.College, Nashik
Ms.Archana R.Mogal K.T.H.M.College, Nashik

K.T.H.M. COLLEGE, NASHIK 2


Introduction
1. About the work book

This workbook is intended to be used by F.Y.B.Sc. (Computer Science) students for the Computer
Science laboratory courses in their curriculum. In Computer Science, hands-on laboratory experience
is critical to the understanding of theoretical concepts studied in the theory courses. This workbook
provides the requisite background material as well as numerous computing problems covering all
difficulty levels.

The objectives of this book are


1) Defining clearly the scope of the course

2) Bringing uniformity in the way the course is conducted across different colleges

3) Continuous assessment of the course

4) Bring in variation and variety in the experiments carried out by different students in a batch

5) Providing ready reference for students while working in the lab

6) Catering to the need of slow paced as well as fast paced learners

2. How to use this workbook


This workbook is mandatory for the completion of the laboratory course. It is a measure of the
performance of the student in the laboratory for the entire duration of the course.

2.1 Instructions to the students


Please read the following instructions carefully and follow them

1) Carry this book every time you come to the lab for computer science practicals
2) A notebook should be maintained separately by each student which should contain the
algorithms, flowcharts, written answers, source code as well as the program output.
3) You should prepare yourself beforehand for the Exercise by reading the material mentioned under.
4) If the self-activity exercise or assessment work contains any blanks such as , get them filled
by your instructor.
5) Instructor will specify which problems you are to solve by ticking box
6) You will be assessed for each exercise on a scale of 5
i) Not done 0 ii) Incomplete 1
iii) Late Complete 2 iv) Needs improvement 3
v) Complete 4 vi) Well Done 5

K.T.H.M.COLLEGE, NASHIK 3
Instruction to the Instructors

1) Explain the assignment and related concepts in around ten minutes using white board if required or by

demonstrating the software


2) Fill in the blanks with different values for each student

3) Choose appropriate problems to be solved by student by ticking box

4) Make sure that students follow the instruction as given above

5) After a student completes a specific set, the instructor has to verify the outputs and sign in the provided

space after the activity.


6) You should evaluate each assignment carried out by a student on a scale of 5 as specified above by
ticking appropriate box.
7) The value should also be entered on assignment completion page of the respective Lab course

Instructions to the Lab administrator

You have to ensure appropriate hardware and software is made available to each student.
The operating system and software requirements on server side and also client side are as given below
1) Server Side (Operating System)
a. * Fedora Core Linux *

b. Servers Side (software’s to be installed)

In Linux – C, C++, awk, shell, perl, postgresql/Mysql


2) Client Side ( Operating System )
* Red Hat Linux and Fedora Core *
Client Side ( software’s to be installed )
In Linux – C, C++, awk, shell, perl, postgresql/mysql
Information about installation and configuring of the server and client are provided in appendix A
First Edition Editors:

Dr. Mrs. S. C. Shirwaikar


Prof. Poonam Ponde
Prof. Reena Bharathi
Prof. Manisha Suryavanshi
Prof. Jeevan Limaye
Prof. Kalyani Ghanwat
Prof. Anagha Joshi
Prof. Vandana Babrekar
Prof. Manasi Keskar
Prof. Seema Purandare Prof.
Padmavathy M.
Prof. Anjali Sardesai
Prof. Parag Tamhankar
Prof. Rasika Rahalkar
K.T.H.M. COLLEGE, NASHIK 4
Assignment Completion Sheet

A) Problem Solving and C programming


Sr.No Assignment Name Marks
1 Problem Solving using Pseudo code and Flowchart, Simple programs, Understanding errors
and error handling.
2 Decision Making Control Structures.
3 Loop Control Structures
4 Functions (User Defined functions, Library functions and Recursion).
5 Arrays (1-D and 2-D)

CERTIFICATE

This is to certify that, Mr./Miss. Roll No. of

F.Y.B.Sc. (Computer Science) has successfully completed out of practicals satisfactorily

during the academic year 20 - 20 .

Practical In-charge Head,


Dept. of Computer Science

Internal Examiner External Examiner

K.T.H.M.COLLEGE, NASHIK 5
Savitribai Phule Pune University,Pune

CS-102-P: Practical course on Problem Solving using ‘C’


Programming Lab Course based on CS-101-T

Section A

Problem Solving using ‘C’


Programming

K.T.H.M. COLLEGE, NASHIK 6


You should read following topics before starting this exercise
1. UNIX and LINUX operating system
About UNIX and LINUX
The success story of UNIX starts with the failure of the MULTICS project. The project failed and the
powerful GE-645 machine was withdrawn by GE. Two scientists at Bell Labs, Ken Thompson and
Dennis Ritchie, who were part of the MULTICS team, continued to work and succeeded and named
their Operating system UNIX, a pun on MULTICS.
The machine available at Bell Labs was a DEC PDP-7 with only 64 k memory while the Operating
system they were developing was meant for a larger machine. The problematic situation was handled
with an innovative solution. They developed most part of the software in a higher-level language, C,
which helped them in porting their Operating system from one hardware to another.
With the growing popularity of UNIX, it was available on a variety of machines, from personal computers
to mainframes. The most popular amongst them was UNIX System V from AT&T.
Each big player in the market came up with their own versions of UNIX. IBM had its own version of
UNIX called AIX, which was used on high-end servers. Sun’s version of UNIX called Solaris was
used on Sun workstations. Novell marketed UnixWare along with Netware, its Network operating
system. LINUX is a version of UNIX, which though it resembles UNIX in looks and feels but differs
from other versions in the way it was developed and distributed. In contrast to large proprietary UNIX
versions, Linux was developed by Linus Torvalds, a Finnish student. He made the source code
available and invited partners via the internet in his development effort. He got professional help from
all quarters and Linux evolved rapidly. It was made freely available for everyone to use. Linux that
was initially meant for Personal computers is now available for a variety of hardware platforms, from
mainframes to handheld computers
Linux supports multiple users. Every user needs to have an account in order to use the system. One of
the users called system administrator (root) is given the charge of creating user accounts and managing
the system normally works on the “#” prompt.
You will be given a username and password, using which you can login into Linux operating system.
For computer users, the operating system provides a user-command interface that is easy to use, usually
called the Shell. The user can type commands at the shell prompt and get the services of the operating
system. Linux operating system shell has the “$” prompt.
You can open a system terminal that gives you a $ prompt where you can type in various shell commands.

LINUX system will usually offer a variety of shell types:


• sh or Bourne Shell: the original shell still used on UNIX systems and in UNIX-related environments.
It is available on every Linux system for compatibility with UNIX programs.
• bash or Bourne Again shell: the standard GNU shell, is the standard shell for common users on Linux
and is a superset of the Bourne shell.
• csh or C shell: the syntax of this shell resembles that of the C programming language.
• tcsh or Turbo C shell: a superset of the common C shell, enhancing user-friendliness and speed.
• ksh or the Korn shell: A superset of the Bourne shell

K.T.H.M.COLLEGE, NASHIK 7
Assignment 1 Date:
Problem Solving using Pseudo code and Flowchart, Simple programs, understanding errors and error
handling.
Objective-To demonstrate the use of data types, simple operators and expressions

Reading-
You should read following topics before starting this exercise
1. Problem solving steps- writing algorithms and flowcharts

2. Different basic data types in C and rules of declaring variables in C

3. Different operators and operator symbols in C

4. How to construct expressions in C, operator precedence

Program solving using Computers

The steps in solving a problem using computers are shown below

Pseudo Language conventions


1. Appropriate names should be given to variables – the algorithm itself is given a name

Algorithm FindingMaximum
2. Organized sequence of data values is given a name and each data value is indicated by
giving the index in brackets

Values[position]
3. Expressions containing Arithmetic operators +, -, * , / relational operators <, ≤ , >, ≥,
≠, = and logical and, or , not can be used

Example: length * breadth, previous < next


4. Assignment statement variable = expression is used to assign data values to variables

5. Conditional constructs for making decisions

if condition then statements


Statements are to be carried out only if condition is true
if condition then statements1 else statements2
Statements1 are to be carried out only if condition is true and statements2 are to be
carried out if condition is false
K.T.H.M. COLLEGE, NASHIK 8
6. Loops

i. while condition do statements

Statements are to be repeated while condition is true

ii. for variable = value1 to value2 do statements

Statements are to be repeated moving from value1 to value2, with


an increment one step.

iii. for variable = value1 downto value2 do { statements }


Statements are to be repeated moving from value1 down to value2,
with a decrement one step.

iv. repeat { statements } until condition


Statements are to be repeated until condition is true

7. Input /output statements

i. read value For taking value as input for the algorithm

ii. write value For printing value as output of the algorithm

8. Algorithm name( value1 , valu2) – taking input for the algorithm

9. return value1 , value2 – for giving output of the algorithm

Examples:

Problem Statement: Accept radius and calculate area and circumference of a circle
Algorithm AreaCircumference
Begin
Input radius pi=3.142
area = piXradiusXradius
circum= 2XpiXradius Output
area
Output circum
End

Problem Statement: Check if a number is even


Algorithm Even
Begin Input m if m mod 2 = 0 then
output “m is even”
End

K.T.H.M.COLLEGE, NASHIK 9
Problem Statement: Find maximum of two numbers
Algorithm Maximum
Begin
Input m Input n if
m > n then output
m
else output n
End

Problem Statement: Give a discount of 15 % when purchase amount exceeds 5000, otherwise give
a discount of 10%

Algorithm Discount Input


amount
if amount exceeds 5000 then compute discount as 25 times
amount divided by 100
else compute discount as 15 times amount divided by 100
Subtract discount from amount
Output amount
End

Problem Statement: Given a set of 100 values representing marks of students, count the total
students that have passed. (A score of 40 is required for passing.)

Algorithm PassCount1
Begin
count = 0
n=1
While n <= 100 do
Input marks
If marks >= 40 then
increment count by 1
n = n+1
Output count
End

The same can be done using another loop construct as shown below:
Algorithm PassCount1
Begin
count = 0
for n = 1 to 100 do
Input marks
If marks >= 40 then increment
count by 1 Output count
End

K.T.H.M. COLLEGE, NASHIK 10


Problem Statement: Accept characters till a * is entered from the keyboard and count the number
of characters entered.

Algorithm CharacterCount
Begin
count = 0
Input char
while char ≠ * do
count = count + 1
Input char
Output count
End

Problem Statement: Accept a number and calculate the sum of its digits.

Algorithm SumDigits
Begin
Input num
sum=0
repeat
digit = num mod 10
sum=sum+digit
num = num/10
until num>0 Output
sum
End

FLOWCHART SYMBOLS

Start Statement
start

Input Statement

Statement or
procedure

Decision, choice or

Selection

Connectors

Control flow

K.T.H.M.COLLEGE, NASHIK 11
Basic control structures in an algorithm: Sequence, Selection and Iteration are shown below

false true

.Sequence Selection

true true

false false

Top tested Iteration Bottom tested Iteration

1. Data type Table


Data Data C Data C Variable Input Statement Output statement
FormatType declaration
quantity Numeric int int quantity; scanf(“%d”,&quantity); printf(“The quantity is %d”, quantity);
month Short short scanf(“%d”,&month); printf(“Credit card number is %ld, ccno);
creditcard int month; scanf(“%ld”, &ccno);
number long long ccno;
int
price π real float float price; scanf(“%f”,&price); printf(“The price is %5.2f”, price);
double const double
pi=3.141593
;
grade character char grade; scanf(“%c”,&grade) printf(“The grade is %c”,grade);

2. Expression Examples
Expression C expression
Increment by a 3 a=a+3
Decrement b by 1 b = b-1 or b--
2 a2 + 5 b/2 2*a*a + 5*b/2
7/13(x-5) (float)7/13*(x-5)
5% of 56 (float)5/100*56
n is between 12 to 70 n>=12 && n<=70
πr2h Pi*r*r*h
n is not divisible by 7 n % 7 != 0
n is even n%2== 0
ch is an alphabet ch>=’A’ && ch<=’Z’ || ch>=’a’ && ch<=’z’

K.T.H.M. COLLEGE, NASHIK 12


Step 1: Writing the Step 2: Draw the
flowchart Step 3: Write the Program
Pseudocode

Algorithm SimpleInterest start #include <stdio.h>


void main( )
Begin {
Input amount, rate, years /* variable declarations */
Read ,principal float amount, rateOfInterest, simpleInterest;
si =amountXyearsXrate / 100
sum, rate and int noOfYears;
Output si no of years /* prompting and accepting input */
End printf(“Give the Principal Sum”);
scanf(“%f”,&amount);
Compute printf(“Give the Rate of Interest”);
Simple interest scanf(“%f”,&rateOfInterest);
printf(“Give the Number of years”);
scanf(“%d”,&noOfYears);
/* Compute the simple Interest*/
Print Simple simpleInterest=amount*noOfYears*rateOfInterest / 100
Interest ;
/* Print the result*/
printf(“The simple Interest on amount %7.2f for %d
years at the rate %4.2f is %6.2f”, amount,
stop noOfYears, rateOfInterest, simpleInterest);
}

Self Activity

1. Type the sample program given above. Execute it for the different values as given below and fill the last
column from the output given by the program. Follow the following guidelines
a. At $ prompt type gedit followed by filename. The filename should have .c as extension for
example $gedit pnr.c
b. Type the sample program and save it. Compile the program using cc compiler available in Linux
$cc pnr.c
It will give errors if any or it will give back the $ prompt if there are no errors
A executable file a.out is created by the compiler. The program can be executed by typing name of the file
as follow $ ./a.out
Alternatively, the executable file can be given name by using –o option while compiling as follows $cc
pnr.c –o pnrexec
$./pnrexec

Sr. No Principal sum No of years Rate of interest Simple Interest


1 2000 3
2 4500 4.5
3 6 8.3

K.T.H.M.COLLEGE, NASHIK 13
Set A. Apply all the three program development steps for the following examples.

1. Accept dimensions of a cylinder and print the surface area and volume
(Hint: surface area = 2πr2 + 2πrh, volume = πr2h)
2. Accept temperatures in Fahrenheit (F) and print it in Celsius(C) and Kelvin (K)
(Hint: C=5/9(F-32), K = C + 273.15)
3. Accept initial velocity (u), acceleration (a) and time (t). Print the final velocity (v) and
distance (s) travelled. (Hint: v = u + at, s = u + at2)
4. Accept inner and outer radius of a ring and print the perimeter and area of the ring
(Hint: perimeter = 2 π (a+b) , area = π (a2-b2) )
5. Accept two numbers and print arithmetic and harmonic mean of the two numbers
(Hint: AM= (a+b)/2 , HM = ab/(a+b) )
6. Accept three dimensions length (l), breadth(b) and height(h) of a cuboid and print
surface area and volume (Hint : surface area=2(lb+lh+bh ), volume = lbh )
7. Accept a character from the keyboard and display its previous and next character in
order. Ex. If the character entered is ‘d’, display “The previous character is c”, “The
next character is e”.
8. Accept a character from the user and display its ASCII value.

Set B . Apply all the three program development steps for the following examples.

1. Accept the x and y coordinates of two points and compute the distance between the
two points.
2. Accept two integers from the user and interchange them. Display the interchanged

numbers.

3. A cashier has currency notes of denomination 1, 5 and 10. Accept the amount to be
withdrawn from the user and print the total number of currency notes of each
denomination the cashier will have to give.

Assignment Evaluation

0: Not Done [ ] 1: Incomplete [ ] 2: Late Complete [ ]

3: Needs Improvement [ ] 4: Complete 5: Well Done [ ]

K.T.H.M. COLLEGE, NASHIK 14


Assignment 2 Date:
Decision Making Control Structures
Exercise 1:
Objective:
To demonstrate use of decision-making statements such as if and if-else.
Reading:

You should read following topics before starting this exercise


1. Different types of decision-making statements available in C.
2. Syntax for these statements.

During problem solving, we come across situations when we have to choose one of the alternative
paths depending upon the result of some condition. Condition is an expression evaluating to true or
false. This is known as the Branching or decision-making statement. Several forms of If and else
constructs are used in C to support decision-making.
1) if statements
2) if – else

K.T.H.M.COLLEGE, NASHIK 15
3. Nested if
If ( a >= b)
if (condition) {
{ if ( a >= c)
printf(“ %d is maximum”,a);
if else
(condition) { printf(“ %d is maximum”,c);
statement;} }
else else
{ statement;} {
if ( b >= c) printf(“ %d is maximum”,b);
else
} False True printf(“ %d is maximum”,c);
a>=b
else }
{
b>= c
if (condition) a>=c
False True
{ statement; False True

} else c is b is c is a is
{ statement; } max max max max

4. Sample program- to check whether a number is within range.

Step 1: Writing the Step 2: Draw the flowchart Step 3: Writing Program
Algorithm

K.T.H.M. COLLEGE, NASHIK 16


start #include <stdio.h>
Algorithm Range
main( )
Begin
Input llimit, ulimit Read {
Input num number
/* variable declarations */
If n≥llimit and
n≤ulimit then int n;
False
Output “in If(n in range) int llimit=50, ulimit = 100;
range”
Else True /* prompting and accepting input */
Output “not in
printf(“Enter the number”);
range”
End Number is scanf(“%d”,&n);
within range
if(n>=llimit && n <= ulimit)
Number is printf(“Number is within range”);
of range
else
printf(“Number is out of range”);
stop
}

K.T.H.M.COLLEGE, NASHIK 17
Self Activity

1. Execute the following program for five different values and fill in the adjoining table

main() n output
{
int n;
printf(“Enter no.”);
scanf(“%d”,&n);
if(n% ==0)
printf(“divisible);
else
printf(“not divisible ”);
}

2. Type the above sample program 4 and execute it for the following values.

n Output message
50
100
65

3. Using the sample code 3 above write the complete program to find the maximum of three
numbers and execute it for different set of values.

Set A: Apply all the three program development steps for the following examples.

1. Write a program to accept an integer and check if it is even or odd.


2. Write a program to accept three numbers and check whether the first is between the other

two numbers. Ex: Input 20 10 30. Output: 20 is between 10 and 30

3. Accept a character as input and check whether the character is a digit.


(Check if it is in the range ‘0’ to ‘9’ both inclusive)
4. Write a program to accept a number and check if it is divisible by 5 and 7.
5. Write a program, which accepts annual basic salary of an employee and calculates and displays
the Income tax as per the following rules. ***
Basic: < 1,50,000 Tax = 0
1,50,000 to 3,00,000 Tax = 20%
> 3,00,000 Tax = 30%

K.T.H.M. COLLEGE, NASHIK 18


6. Accept a character from the user and check whether the character is a vowel or consonant.
(Hint: a,e,i,o,u, A, E, I, O, U are vowels)
7. Accept any year as input through the keyboard. Write a program to check whether the year
is a leap year or not. (Hint leap year is divisible by 4 and not by 100 or divisible by 400)

Set B: Apply all the three program development steps for the following examples.

1. Write a program to check whether given character is a digit or a character in

lowercase or uppercase alphabet. (Hint ASCII value of digit is between 48 to 58

and Lowercase characters have ASCII values in the range of 97 to122, uppercase is

between 65 and 90)

2. Accept the x and y coordinate of a point and find the quadrant in which the point lies.

3. Write a program to calculate the roots of a quadratic equation. Consider all possible

cases. Accept the cost price and selling price from the keyboard. Find out if the seller

has made a profit or loss and display how much profit or loss has been made.

4. Write a program to accept marks for three subjects. Calculate the average and also

display the class obtained. (Distinction – above Class I – above %, class II –

% to %, pass class – % to % and fail otherwise)

Assignment Evaluation

0: Not Done [ ] 1: Incomplete [ ] 2: Late Complete [ ]

3: Needs Improvement [ ] 4: Complete 5: Well Done [ ]

K.T.H.M.COLLEGE, NASHIK 19
Date:
Exercise 2:
Objective:

To demonstrate decision making statements (switch case)

Reading:

You should read following topics before starting this exercise


1. Different types of decision-making statements available in C.
2. Syntax for switch case statements.

The control statement that allows us to make a decision from the number of choices is called a switchcase
statement. It is a multi-way decision making statement.

1. Usage of switch statement

Statement Syntax Flowchart Example


switch(expression) switch (color)
start
{ {
case value1: block1; case ’r’ : case ’R’ :
break; case 1
True Block 1 printf (“RED”);
case value2: block2; break;
False
break; case ’g’ : case ’G’ :
True
. case 2 Block 2 printf (“GREEN”);
. break;
. False case ’b’ : case ’B’ :
default: default block; True printf (“BLUE”);
case 3 Block 3
break; break;
} default :
False
printf (“INVALID COLOR”);
True
case 4 Block 4 }

False

Default Block

stop

K.T.H.M. COLLEGE, NASHIK 20


2. The switch statement is used in writing menu driven programs where a menu displays several

options and the user gives the choice by typing a character or number. A Sample program to display
the selected option from a menu is given below.

Step 1: Writing the Step 2: Draw the flowchart Step 3: Writing Program
Algorithm

Algorithm Menu start


#include <stdio.h>
Begin main( )
Output menu Display {
Options
Read choice /* variable declarations */
Execute statements int choice;
Read choice
depending on choice /* Displaying the Menu */
End printf(“\n 1. Option 1\n”);
True
case 1 Statement 1 printf(“ 2. Option 2\n”);
False printf(“ 3. Option 3\n”);
True printf(“Enter your choice”);
case 2 Statement 2
scanf(“%d”,&choice);
False
True
switch(choice)
case 3 Statement 3 {
case 1: printf(“Option 1 is selected”);
False True
break;
Default statement
case 2: printf(“Option 2 is selected”);

stop break;
case 3: printf(“Option 3 is selected”);
break;
default: printf(“Invalid choice”);
}
}

K.T.H.M.COLLEGE, NASHIK 21
Self Activity

1. Write the program that accepts a char–type variable called color and displays appropriate message
using the sample code 1 above. Execute the program for various character values and fill in the
following table. Modify the program to include all rainbow colours

Input character Output Message


V
I
B
g
R
y

Set A: Apply all the three program development steps for the following examples.

1. Accept a single digit from the user and display it in words.


For example, if digit entered is 9, display Nine.

2. Write a program, which accepts two integers and an operator as a character (+ - * /),
performs the corresponding operation and displays the result.

3. Accept two numbers in variables x and y from the user and perform the following operations

Options Actions
1. Equality Check if x is equal to y
2. Less Than Check if x is less than y
3. Quotient and Remainder Divide x by y and display the quotient and remainder
4. Range Accept a number and check if it lies between x and y (both inclusive)
5. Swap Interchange x and y

K.T.H.M. COLLEGE, NASHIK 22


Set B: Apply all the three program development steps for the following examples.

1. Accept radius from the user and write a program having menu with the following options and
corresponding actions

Options Actions
1. Area of Circle Compute area of circle and print
2. Circumference of Circle Compute Circumference of circle and print
3. Volume of Sphere Compute Volume of Sphere and print

2. Write a program having a menu with the following options and corresponding actions

Options Actions
1. Area of square Accept length, Compute area of square and print
2. Area of Rectangle Accept length and breadth, Compute area of rectangle and print
3. Area of triangle Accept base and height, Compute area of triangle and print

Assignment Evaluation

0: Not Done [ ] 1: Incomplete [ ] 2: Late Complete [ ]

3: Needs Improvement [ ] 4: Complete 5: Well Done [ ]

K.T.H.M.COLLEGE, NASHIK 23
Assignment 3 Date:
Loop Control Structures
Exercise 1:
Objective:
To demonstrate use of simple loops.

Reading:
You should read following topics before starting this exercise
1. Different types of loop structures in C.
2. Syntax and usage of these statements.

We need to perform certain actions repeatedly for a fixed number of times or till some condition holds
true. These repetitive operations are done using loop control statements. The types of loop structures
supported in C are
1. while statement
2. do-while statement

K.T.H.M. COLLEGE, NASHIK 24


3. for statement /* display first 10 multiples of 2 */
for (expr1; expr2; expr3) expr1 {
{ for(i=1; i <= 10; i++)
statement 1 printf (“2 X %d = %d\n”, i, 2*i);
.
. Test False }
} expr2
expr1 = initialization
expression True
expr2 = loop condition Loop Body
expr3 = alteration
expression which alters
the loop variable Expr3

3. Sample program- to print sum of 1+2+3+….n.

Step 1: Writing the Step 2: Draw the flowchart Step 3: Writing Program
Algorithm
Algorithm SumofN #include <stdio.h>
Begin main( )
Input n {
Sum=0 /* variable declarations */
While n>0 do int sum = 0, n;
sum-sum+n printf(“enter the value of n : “);
n=n-1 scanf(“%d”,&n);
Output sum while (n>0)
End {
sum = sum + n;
n--;
}
printf(“\n The sum of numbers is %d”, sum);
}

K.T.H.M.COLLEGE, NASHIK 25
4. Sample program- To read characters till EOF (Ctrl+Z) and count the total number of characters

entered.

Step 1 : Writing the Step 2 : Draw the flowchart Step 3 : Writing Program
Algorithm
Algorithm CharCount #include <stdio.h> main( )
Begin start
{
Count=0
Input ch count = 0 char ch; int count=0;
While ch ≠EOF do
while((ch=getchar())!=EOF)
Count=count+1 Read ch
Input ch count++;
Output count
printf(“Total characters =%d”, count);
End
Ch=EOF
? }
False

Count = count+1

Print count

stop

Self Activity

1. Execute example 1 given above. Execute the program for different values.
2. Write a program that accepts numbers continuously as long as the number is positive and

prints the sum of the numbers read. Refer example code 2 given above.

Execute the program for different values.

3. Write a program to accept n and display its multiplication table. Refer to sample code 3 given
above.
4. Type the sample program to print sum of first n numbers and execute the program for
different values of n.
5. Write a program to accept characters till the user enters EOF and count number of times ‘a’
Is entered. Refer to sample program 5 given above.

K.T.H.M. COLLEGE, NASHIK 26


Set A . Apply all the three program development steps for the following examples.

1. Write a program to accept an integer n and display all even numbers upto n.
2. Accept two integers x and y and calculate the sum of all integers between x and y
(both inclusive)
3. Write a program to accept two integers x and n and compute xn
4. Write a program to accept a character, an integer n and display the next n characters.
5. Write a program to accept an integer and check if it is prime or not.
6. Write a program to accept an integer, count number of digits and calculate sum of digits in the

number. Example: Number = 1234 Output: Digits = 4, Sum = 10

7. Write a program to accept an integer and reverse the number.


Example: Input: 546, Reverse = 645.

Set B. Apply all the three program development steps for the following examples.

1. Write a program to display the first n Fibonacci numbers. (1 1 2 3 5 ……)


2. Write a program to accept real number x and integer n and calculate the sum of first n terms
of the series x+ 3x+5x+7x+…
3. Write a program to accept real number x and integer n to calculate sum of first n terms of the
Series 1 2 3
x + x 2 + x3 + ……

4. Write a program to accept characters till the user enters EOF and count number of alphabets

and digits entered. Refer to sample program 5 given above.

5. Write a program, which accepts a number n and displays each digit in words.
Example: 6702 Output = Six-Seven-Zero-Two.
(Hint: Reverse the number and use a switch statement)

Assignment Evaluation

0: Not Done [ ] 1: Incomplete [ ] 2: Late Complete [ ]

3: Needs Improvement [ ] 4: Complete [ ] 5: Well Done [ ]

K.T.H.M.COLLEGE, NASHIK 27
Exercise 2 Date:
Objective:
To demonstrate use of nested loops
Reading
In the previous exercise, you used while, do-while and for loops. You should read following topics
before starting this exercise
1. Different types of loop structures in C.
2. Syntax for these statements.
3. Usage of each loop structure
Nested loop means a loop that is contained within another loop. Nesting can be done upto any levels.
The inner loop has to be completely enclosed in the outer loop. No overlapping of loops is allowed.
Sr. No Format Sample Program
1. Nested for loop #include <stdio.h>
void main()
for(exp1; exp2 ; exp3) {
{ …………………… int n , line_number , number;
for(exp11; exp12 ; exp13) printf(“How many lines: ”);
scanf(“%d”,&n);
{ …………………… for(line_number =1 ;line_number <=n; line_number++ )
} {
……………………. for(number = 1; number <= line_number; number++)
printf (“%d\t”, number);
}
printf (“\n”);
}
}
2. Nested while loop / do while loop #include <stdio.h>
void main( )
while(condition1) {
{ …………………… int n , sum;
while(condition2) printf(“Give any number ”);
{ …………………… scanf(“%d”,&n);
} do
……………………. {
} sum =0;
printf(“%d --->”,n);
do while ( n>0)
{ …………………… {
while(condition1) sum +=n%10;
{ ……………….. n= n/10;
} }
………………. n=sum;
} while (condition2); } while( n >9);
printf ( “ %d” , n);
}

K.T.H.M. COLLEGE, NASHIK 28


Self Activity
1. The Sample program 1 displays n lines of the following triangle. Type the program and
execute it for different values of n.
1
1 2
1 2 3
1 2 3 4

2. Modify the sample program 1 to display n lines of the Floyd’s triangle as follows (here n=4).
1
2 3
4 5 6
7 8 9 10

3. The sample program 2 computes the sum of digits of a number and the process is repeated till
the number reduces to a single digit number. Type the program and execute it for different
values of n and give the output

Input number Output


6534

67

Set A . Write C programs for the following problems.


1. Write a program to display all prime numbers between and .
2. Write a program to display multiplication tables from to having n multiples each.
The output should be displayed in a tabular format. For example, the multiplication tables
of 2 to 9 having 10 multiples each is shown below.
2×1=2 3 × 1 = 3 ………….9 × 1 = 9
2×2=4 3 × 2 = 6…………..9 × 2 = 18
…………. ………….
2 × 10 = 20 3 × 10 = 30………..9 × 10 = 90

3. Modify the sample program 1 to display n lines as follows (here n=4).


A
B C
D E F
G H I J
K.T.H.M.COLLEGE, NASHIK 29
Set B. Write C programs for the following problems.

1. Write a program to display all Armstrong numbers between 1 and 500. (An Armstrong number is a

number such that the sum of cube of digits = number itself. Ex. 153 = 1*1*1 + 5*5*5 + 3*3*3

2. Accept n numbers and display the number having the maximum sum of digits.

3. Display all perfect numbers below 500. [A perfect number is a number, such that the sum of its
factors is equal to the number itself]. Example: 6 (1 + 2 + 3), 28 (1+2+4+7+14)

Assignment Evaluation

0: Not Done [ ] 1: Incomplete [ ] 2: Late Complete [ ]

3: Needs Improvement [ ] 4: Complete [ ] 5: Well Done [ ]

K.T.H.M. COLLEGE, NASHIK 30


Assignment 3 Date:
Functions (User Defined functions, Library functions and Recursion).
Exercise 1:
To demonstrate menu driven programs and use of standard library functions
Reading
You should read following topics before starting this exercise
1. Use of switch statement to create menus as in exercise3
2. Use of while and do while loops as in
ctype.h : contains function prototypes for performing various operations on characters.
Function Purpose Example
isalpha() Check whether a character is a alphabet if (isalpha(ch))
isalnum() Check whether a character is alphanumeric if (isalnum(ch))
isdigit() Check whether a character is a digit if (isdigit(ch))
isspace() Check whether a character is a space if (isspace(ch))
ispunct() Check whether a character is a punctuation if (ispunct(ch))
symbol
isupper() Check whether a character is uppercase if (isupper(ch))
alphabet
islower() Check whether a character is lowercase if (isupper(ch))
alphabet
toupper() Converts a character to uppercase ch = toupper(ch)
tolower() Converts a character to lowercase ch = tolower(ch)

math.h : contains function prototypes for performing various mathematical operations on numeric data.
Name Description
ceil smallest integer not less than parameter
cos cosine
cosh hyperbolic cosine
exp(double x) exponential function, computes ex
fabs absolute value
floor largest integer not greater than parameter
fmod floating point remainder
log natural logarithm
log10 base-10 logarithm
pow(x,y) compute a value taken to an exponent, xy
sin sine
sinh hyperbolic sine
sqrt square root
tan tangent
tanh hyperbolic tangent

K.T.H.M.COLLEGE, NASHIK 31
A program that does multiple tasks, provides a menu from which user can choose the appropriate task
to be performed. The menu should appear again when the task is completed so that the user can choose
another task. This process continues till the user decides to quit. A menu driven program can be written
using a combination of do-while loop containing a switch statement. One of the options provided in a
menu driven program is to exit the program.

K.T.H.M. COLLEGE, NASHIK 32


Self Activity
1. Write a menu driven program to perform the following operations on a character type variable.
i. Check if it is an alphabet
ii. Check if it is a digit.
iii. Check if it is lowercase.
iv. Check if it is uppercase.
v. Convert it to uppercase.
vi. Convert it to lowercase.

Refer to the sample code given above and use standard functions from ctype.h
Set A . Write C programs for the following problems

1. Write a program, which accepts a character from the user and checks if it is an alphabet, digit or
punctuation symbol. If it is an alphabet, check if it is uppercase or lowercase and then change
the case.

2. Write a menu driven program to perform the following operations till the user selects Exit.
Accept appropriate data for each option. Use standard library functions from math.h

i. Power ii. Square Root iii. Floor iv. Ceiling v. Exit

Set B. Write C programs for the following problems

1. Accept two fractions (numerator, denominator) and perform the following operations till the user
selects Exit.
i. Addition
ii.Subtraction
iii.Multiplication
iv.EXIT
2. Accept x and y coordinates of two points and write a menu driven program to perform the
Following operations till the user selects Exit.
iv. Distance between points
v. Slope of line between the points.
vi. Check whether they lie in the same quadrant.
vii. EXIT

Assignment Evaluation

0: Not Done [ ] 1: Incomplete [ ] 2: Late Complete [ ]

3: Needs Improvement [ ] 4: Complete [ ] 5: Well Done [ ]

K.T.H.M.COLLEGE, NASHIK 33
Exercise 2: Date:
Objective:
To demonstrate writing C programs in modular way (use of user defined functions)

You should read following topics before starting this exercise


1. Declaring and Defining a function

2. Function call

3. Passing parameters to a function

4. Function returning a value

A function is a named sub-module of a program, which performs a specific, well-defined task. It can
accept information from the calling function and return only 1 value. In C, every program has a function
named main. main in turn calls other functions.
Sr. Actions involving Syntax Example
No functions
1. Function returntype function(type arg1, type arg2 … ); void display();
declaration int sum(int x, int y);
2. Function definition returntype function(type arg1, type arg2 … ) float calcarea (float r)
{ {
/* statements*/ float area = Pi *r*r ;
} return area;
}
3. Function call function(arguments); display();
variable = function(arguments); ans = calcarea(radius);

1. Sample code
The program given below calculates the area of a circle using a function and uses this function to
calculate the area of a cylinder using another function.

main()
{
float areacircle (float r);
float areacylinder(float r, int h);
float area, r;
printf(“\n Enter Radius: “);
scanf(“%f”,&r);
area=areacircle(r);
printf(“\n Area of circle =%6.2f”, area);
printf(“\n Enter Height: “);
scanf(“%d”,&h);
area=areacylinder(r,h);
printf(“\n Area of cylinder =%6.2f”, area);
}

K.T.H.M. COLLEGE, NASHIK 34


float areacircle (float r)
{
const float pi=3.142;
return(pi * r*r );
}
float areacylinder (float r, int h)
{
return 2*areacircle(r)*h;
}

2. Sample code

The function iswhitespace returns 1 if its character parameter is a space, tab or newline character.
The program accepts characters till the user enters EOF and counts the number of white spaces.

main()
{
int iswhitespace (char ch);
char ch;
int count=0;
printf(“\n Enter the characters. Type CTRL +Z to terminate: “);
while((ch=getchar())!=EOF)
if(iswhitespace(ch))
count++;
printf(“\n The total number of white spaces =%d”, count);
}
int iswhitespace (char ch)
{
switch(ch)
{
case ‘ ‘:
case ‘\t’ :
case ‘\n’ : return 1;
default : return 0;
}
}

Self Activity

1. Type the program given in sample code 1 above and execute the program. Add another function
to calculate the volume of sphere and display it.
2. Type the program given in sample code 2 above and execute the program. Modify the function
such that it returns 1 if the character is a vowel. Also count the total number of vowels entered.

K.T.H.M.COLLEGE, NASHIK 35
Set A. Write C programs for the following problems
1. Write a function isEven, which accepts an integer as parameter and returns 1 if the number is

even, and 0 otherwise. Use this function in main to accept n numbers and check if they are

even or odd.

2. Write a function, which accepts a character and integer n as parameter and displays the next n
characters.

Set B . Write C programs for the following problems

1. Write a function isPrime, which accepts an integer as parameter and returns 1 if the number is
prime and 0 otherwise. Use this function in main to display the first 10 prime numbers.

2. Write a function that accepts a character as parameter and returns 1 if it is an alphabet, 2 if it is a


digit and 3 is it is a special symbol. In main, accept characters till the user enters EOF and use
the function to count the total number of alphabets, digits and special symbols entered.

3. Write a function power, which calculates xy. Write another function, which calculates n! Using
For loop. Use these functions to calculate the sum of first n terms of the Taylor series:
x3 x5
sin(x) = x - + + ……
3! 5!

Assignment Evaluation

0: Not Done [ ] 1: Incomplete [ ] 2: Late Complete [ ]

3: Needs Improvement [ ] 4: Complete [ ] 5: Well Done [ ]

K.T.H.M. COLLEGE, NASHIK 36


Exercise 3: Date:

Objective:
To demonstrate Recursion.

You should read the following topics before starting this exercise
1. Recursive definition

2. Declaring and defining a function

3. How to call a function

4. How to pass parameters to a function

Recursion is a process by which a function calls itself either directly or indirectly. The points to be
remembered when recursive functions
i. Each time the function is called recursively it must be closer to the solution.
ii. There must be some terminating condition, which will stop recursion.
iii. Usually the function contains an if –else branching statement where one branch makes recursive
call while other branch has non-recursive terminating condition
Expressions having recursive definitions can be easily converted into recursive functions
Sr. No Recursive definition Recursive Function Sample program

1. The recursive definition long int factorial (int n) #include <stdio.h>


main()
for factorial is given {
If (n==0)||(n==1)) {
below: int num;
/* terminating condition */
/* function declaration */
return(1); long int factorial(int n);
n!= 1 if n = 0 or 1 else printf(“\n enter the number:”);
return(n* factorial(n-1)); scanf(“%d”,&num);
= n * (n-1)! if n > 1 printf(“\n The factorial of %d is
/* recursive call */
} %ld”,num,factorial(num));
}
/* function code*/
2. The recursive definition long int nCr( int n, int r) #include <stdio.h>
/* function code*/
for nCr (no of {
main()
combinations of r if(n==r || r==0) {
int n,r; ;
objects out of n objects) /* terminating condition */ printf(“\n enter the total number of objects:”);
is as return(1); scanf(“%d”,&n);
printf(“\n enter the number of objects to be
follows else selected”);
nCn = 1 return( nCr(n-1,r)+nCr(n, r-1)); scanf(“%d”,&r);
printf(“\n The value %dC%d is
nC0 = 1 /* recursive call */ %ld”,n, r, nCr(n,r));
nCr = n-1Cr + nCr-1 } }

K.T.H.M.COLLEGE, NASHIK 37
Self Activity
1. Write the sample program 1 given above and execute the program. Modify the program to
Define a global integer variable count and increment it in factorial function. Add a printf
statement in main function for variable count. Execute the program for different values and
fill in the following table.

Sr. No. num factorial count


1. 0
2 1
3 5
4
5

2. Write the sample program 2 given above and execute the program for different values of n and
r. Modify the program to define a global integer variable count and increment it in nCr
function.
Add a print statement in main function for variable count. Execute the program for different
values and fill in the following table

Sr. No. n r nCr count


1. 5 0
2 5 5
3 5 2
4 5
5

Set A . Write C programs for the following problems

1. Write a recursive C function to calculate the sum of digits of a number. Use this function in main
to accept a number and print sum of its digits.
2. Write a recursive C function to calculate the GCD of two numbers. Use this function in main.
The GCD is calculated as : gcd(a,b) = a if b = 0
= gcd (b, a mod b) otherwise
3. Write a recursive C function to calculate xy. (Do not use standard library function)

K.T.H.M. COLLEGE, NASHIK 38


Set B . Write C programs for the following problems

1. Write a recursive function to calculate the nth Fibonacci number. Use this function in main to
Display the first n Fibonacci numbers. The recursive definition of nth Fibonacci number is as
follows:
fib(n) = 1 if n = 1 or 2
= fib(n-2) + fib(n-1) if n>2

2. Write a recursive function to calculate the sum of digits of a number till you get a single digit
number.
Example: 961 -> 16 -> 5. (Note: Do not use a loop)

3. Write a recursive C function to print the digits of a number in reverse order. Use this function in
main to accept a number and print the digits in reverse order separated by tab.
Example: 3456 6 4 5 3

(Hint: Recursiveprint(n) = print n if n is single digit number


= print n % 10 + tab + Recursiveprint( n/10)

Assignment Evaluation

0: Not Done [ ] 1: Incomplete [ ] 2: Late Complete [ ]

3: Needs Improvement [ ] 4: Complete [ ] 5: Well Done [ ]

K.T.H.M.COLLEGE, NASHIK 39
Assignment 5 Date:
Arrays (1-D and 2-D)
Exercise 1
Objective
To demonstrate use of 1-D arrays and functions.
Reading
You should read the following topics before starting this exercise
1. What are arrays and how to declare an array?
2. How to enter data in to array and access the elements of an array.
3. How to initialize an array and how to check the bounds of an array?
4. How to pass an array to a function
An array is a collection of data items of the same data type referred to by a common name. Each
element of the array is accessed by an index or subscript. Hence, it is also called a subscripted variable.
Actions involving syntax Example
arrays
Declaration of array data-type array_name[size]; int temperature[10];
float pressure[20];
Initialization of array data-type int marks[]={45,57,87,20,90};
array_name[]={element1,
marks[3] refers to the fourth element which equals 20
element2, ……, element n};
int count[3]={4,2,9};
data-type
array_name[size]={element-1, count[2] is the last element 9 while 4 is count[0]
element-2, ……, element-size};
Accessing elements of The array index begins from 0 Value = marks[3];
an array (zero) To access an array element,
This refers to the 4th element in the array
we need to refer to it as
array_name[index].
Entering data into an for(i=0; i<=9; i++)
array.
scanf(“%d”, &marks[i]);
Printing the data from for(i=0; i<=9; i++)
an array
printf(“%d”, marks[i]);
Arrays and We can pass an array to a function /* Passing the whole array*/ void modify(int
function using two methods. a[5])
Pass the array element by element {
Pass the entire array to the int i;
function for(i=0; i<5 ; i++)
a[i] = i;
}

K.T.H.M. COLLEGE, NASHIK 40


Sample program to find the largest element of an array

#include<stdio.h> int
main()
{
int arr[20]; int n;
void accept(int a[20], int n);
void display(int a[20], int n);
int maximum(int a[20], int n);

printf(”How many numbers :”);


scanf(“%d”, &n);
accept(arr,n);
display(arr,n);
printf(“The maximum is :%d” , maximum(arr,n));
}
void accept(int a[20], int n)
{
int i;
for(i=0; i<n ; i++)
scanf(“%d”, &a[i]);
}
void display(int a[20], int n)
{
int i;
for(i=0; i<n ; i++)
printf(“%d\t”, a[i]);
}
int maximum(int a[20], int n)
{
int i, max = a[0];
for(i=1; i<n ; i++)
if(a[i] > max)
max = a[i];
return max;
}

Self Activity
1. Write a program to accept n numbers in an array and display the largest and smallest number.
Using these values, calculate the range of elements in the array. Refer to the sample code
given above and make appropriate modifications.

2. Write a program to accept n numbers in an array and calculate the average. Refer to the sample
code given above and make appropriate modifications.

K.T.H.M.COLLEGE, NASHIK 41
Set A. Write programs to solve the following problems

1. Write a program to accept n numbers and display the array in the reverse order. Write separate
functions to accept and display.

2. Write a function for Linear Search, which accepts an array of n elements and a key as parameters
and returns the position of key in the array and -1 if the key is not found. Accept n numbers from
the user, store them in an array. Accept the key to be searched and search it using this function.
Display appropriate messages.

3. Write a function, which accepts an integer array and an integer as parameters and counts the
occurrences of the number in the array.
Example: Input 1 5 2 1 6 3 8 2 9 15 1 30
Number : 1
Output: 1 occurs 3 times

4. Write a program to accept n numbers and store all prime numbers in an array called prime.
Display this array.

Set B. Write programs to solve the following problems

1. Write a function to sort an array of n integers using Bubble sort method. Accept n numbers from
the user, store them in an array and sort them using this function. Display the sorted array.

2. Write a program to accept a decimal number and convert it to binary, octal and hexadecimal.
Write separate functions.

3. Write a program to find the intersection of the two sets of integers. Store the intersection in
another array.

4. Write a program to merge two sorted arrays into a third array such that the third array is also in
the sorted order.

a1 10 25 90
a2 9 16 22 26 100

a3 9 10 16 22 25 26 90 100

Assignment Evaluation

0: Not Done [ ] 1: Incomplete [ ] 2: Late Complete [ ]

3: Needs Improvement [ ] 4: Complete [ ] 5: Well Done [ ]

K.T.H.M. COLLEGE, NASHIK 42


Exercise 2
Objective
To demonstrate use of 2-D arrays and functions.

You should read the following topics before starting this exercise
1. How to declare and initialize two-dimensional array

2. Accessing elements

3. Usage of two-dimensional arrays

Actions involving syntax Example


2-D arrays
Declaration of 2-D data-type array_name[size][size]; int mat[10][10];
array float sales[4][10];

Initialization of 2- data-type array_name[rows][cols]= int num[][2] = {12, 34, 23, 45, 56,45};
D array { {elements of row 0},{ elements of row
int num[3][2] = { {1,2}, {3,4}, {5,6}};
1},…..};
data-type int num[3][2] = { 1,2,3,4, 5,6};
array_name[][cols]={element1,
element2, ……, element size};
Accessing elements Accessing elements of 2-dimensional int m[3][2];
of 2-D array array - in general, the array element is m is declared as a two dimensional array
referred as: (matrix) having 3 rows (numbered 0 to 2)
array_name[index1][index2] and 2 columns (numbered 0 to 1). The
where index1 is the row location of and
index2 is the column location of an first element is m[0] [0] and the last is m
element in the array. [2][1]. value = m[1][1];
Entering data into a int mat[4][3];
2-D array.
for (i=0; i<4; i++)
/* outer loop for rows */
for (j=0;j<3; j++)
/* inner loop for columns */
scanf(“%d”, &mat[i][j]);
Printing the data for (i=0; i<4; i++)
from a 2-D array
/* outer loop for rows */
{
for (j=0;j<3; j++)
/* inner loop for columns */
printf(“%d\t” , mat[i][j]);
printf(”\n”);
}

K.T.H.M.COLLEGE, NASHIK 43
Sample program to accept, display and print the sum of elements of each row of a matrix.
#include<stdio.h>
int main()
{
int mat[10][10], m, n;
void display(int a[10][10], int m, int n);
void accept(int a[10][10], int m, int n);
void sumofrows(int a[10][10], int m, int n);
printf(“How many rows and columns? ”);
scanf(“%d%d”,&m, &n);

printf(“Enter the matrix elements :”);


accept(mat, m, n);
printf(“\n The matrix is :\n”);
display(mat, m, n);
sumofrows(mat,m,n);
}
void accept(int a[10][10], int m, int n)
{
int i,j;
for (i=0; i<m; i++) /* outer loop for rows */ for
(j=0;j<n; j++) /* inner loop for columns */
scanf(“%d”, &a[i][j]);
}
void display(int a[10][10], int m, int n)
{
int i,j;
printf(”\nThe elements of %d by %d matrix are\n”, m, n); for
(i=0; i<m; i++) /* outer loop for rows */
{
for (j=0;j<n; j++) /* inner loop for columns */
printf(“%d\t” , a[i][j]);
printf(”\n”);
}
}
void somofrows(int a[10][10], int m, int n)
{
int i,j, sum;
for (i=0; i<m; i++) /* outer loop for rows */
{
sum=0’
for (j=0;j<n; j++) /* inner loop for columns */
sum= sum+a[i][j];
printf(“Sum of elements of row %d = %d”, i, sum);
}
}

1. Write a program to accept, display and print the sum of elements of each row and sum of elements of
each column of a matrix. Refer to sample code given above.

K.T.H.M. COLLEGE, NASHIK 44


Set A . Write C programs for the following problems.

1. Write a program to accept a matrix A of size m X n and store its transpose in matrix B. Display
matrix B. Write separate functions.

2. Write a program to add and multiply two matrices. Write separate functions to accept, display,
add and multiply the matrices. Perform necessary checks before adding and multiplying the
matrices.

Set B . Write C programs for the following problems.

1. Write a menu driven program to perform the following operations on a square matrix. Write
separate functions for each option.
i) Check if the matrix is symmetric.
ii) Display the trace of the matrix (sum of diagonal elements).
iii) Check if the matrix is an upper triangular matrix.
iv) Check if the matrix is a lower triangular matrix.
v) Check if it is an identity matrix.

2. Write a program to accept an m X n matrix and display an m+1 X n+1 matrix such that the m+1th
row contains the sum of all elements of corresponding row and the n+1th column contains the
sum of elements of the corresponding column.
Example:
A B
1 2 3 1 2 3 6
4 5 6 4 5 6 15
7 8 9 7 8 9 24
12 15 18 45

Assignment Evaluation

0: Not Done [ ] 1: Incomplete [ ] 2: Late Complete [ ]

3: Needs Improvement [ ] 4: Complete [ ] 5: Well Done [ ]

K.T.H.M.COLLEGE, NASHIK 45

You might also like