FYBScCS - Sem I - LabBook C Programming CS 102 P
FYBScCS - Sem I - LabBook C Programming CS 102 P
WorkBook
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:
Updated By
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.
2) Bringing uniformity in the way the course is conducted across different colleges
4) Bring in variation and variety in the experiments carried out by different students in a batch
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
5) After a student completes a specific set, the instructor has to verify the outputs and sign in the provided
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 *
CERTIFICATE
K.T.H.M.COLLEGE, NASHIK 5
Savitribai Phule Pune University,Pune
Section A
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
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
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
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%
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
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
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’
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
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
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
Step 1: Writing the Step 2: Draw the flowchart Step 3: Writing Program
Algorithm
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.
Set B: Apply all the three program development steps for the following examples.
and Lowercase characters have ASCII values in the range of 97 to122, uppercase is
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
Assignment Evaluation
K.T.H.M.COLLEGE, NASHIK 19
Date:
Exercise 2:
Objective:
Reading:
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.
False
Default Block
stop
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
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
Set A: Apply all the three program development steps for the following examples.
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
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
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
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.
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.
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
Set B. Apply all the three program development steps for the following examples.
4. Write a program to accept characters till the user enters EOF and count number of alphabets
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
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);
}
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
67
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
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.
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
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
K.T.H.M.COLLEGE, NASHIK 33
Exercise 2: Date:
Objective:
To demonstrate writing C programs in modular way (use of user defined functions)
2. Function call
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);
}
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.
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.
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
Objective:
To demonstrate Recursion.
You should read the following topics before starting this exercise
1. Recursive definition
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
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.
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
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)
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
Assignment Evaluation
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;
}
#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);
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.
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
You should read the following topics before starting this exercise
1. How to declare and initialize two-dimensional array
2. Accessing elements
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);
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.
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.
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
K.T.H.M.COLLEGE, NASHIK 45