You are on page 1of 67

RNS INSTITUTE OF TECHNOLOGY

(AICTE Approved, VTU Affiliated and NAAC 'A' Accredited)


UG Programs - CSE, ECE, ISE, EIE and EEE have been Accredited by NBA for three Academic years
DR. VISHNUVARDHAN ROAD, CHANNASANDRA, RR NAGAR POST, BENGALURU – 560 098

C PROGRAMMING
LABORATORY MANUAL

For First / Second Semester B.E


[VTU/CBCS, 2018-19 syllabus]
Subject Code – 18CPL17/27

NAME : .......................................................................................................................................................................................................................................................................................................................................................................................................................................

BRANCH : .....................................................................................................................................................................................................................................................................................................................................................................................................................................

SECTION : ..................................................................................................................................................................................................................................................................................................................................................................................................................................

USN :..........................................................................................................................................................................................................................................................................................................................................................................................................................................
VISION AND MISSION OF INSTITUTION

Vision

Building RNSIT into a World Class Institution

Mission
To impart high quality education in Engineering, Technology and Management
with a Difference, Enabling Students to Excel in their Career by
1. Attracting quality Students and preparing them with a strong foundation in fundamentals
so as to achieve distinctions in various walks of life leading to outstanding contributions
2. Imparting value based, need based, choice based and skill based professional education to
the aspiring youth and carving them into disciplined, World class Professionals with social
responsibility
3. Promoting excellence in Teaching, Research and Consultancy that galvanizes academic
consciousness among Faculty and Students
4. Exposing Students to emerging frontiers of knowledge in various domains and make them
suitable for Industry, Entrepreneurship, Higher studies, and Research & Development
5. Providing freedom of action and choice for all the Stake holders with better visibility
[DOCUMENT TITLE]
C PROGRAMMING LABORATORY-18CPL17/27
INTERNAL EVALUATION SHEET

EVALUATION (MAX MARKS 40)


TEST REGULAR RECORD TOTAL MARKS
EVALUATION
A B C A+B+C
10 10 20 40

R1: REGULAR LAB EVALUATION WRITE UP RUBRIC (MAX MARKS 10)


Sl. Needs
Parameters Good Average
No. improvement
a. Understanding of Clear understanding of problem Problem statement is understood Problem statement is not
problem statement while designing and clearly but few mistakes while clearly understood while
(3 marks) implementing the program (3) designing and implementing designing the program
program (2) (1)
b. Writing program Program handles all possible Average condition is defined and Program does not handle
(4 marks) conditions (4) verified. (3) possible conditions (1)

c. Result and Meticulous documentation and Acceptable documentation shown Documentation does not
documentation all conditions are taken care (3) (2) take care all conditions
(3 marks) (1)

R2: REGULAR LAB EVALUATION VIVA RUBRIC (MAX MARKS 10)


Sl. Needs
Parameter Excellent Good Average
No. Improvement
a. Conceptual Answers 80% of the Answers 60% of the viva Answers 30% of the Unable to relate the
understanding viva questions asked questions asked (7) viva questions asked concepts (1)
(10 marks) (10) (4)

R3: REGULAR LAB PROGRAM EXECUTION RUBRIC (MAX MARKS 10)

Sl.
Parameters Excellent Good Needs Improvement
No.
a. Design, implementation Program follows syntax and Program has few logical Syntax and semantics
and demonstration semantics of C programming errors, moderately of C programming is
(5 marks) language. Demonstrates the demonstrates all possible not clear (1)
complete knowledge of the concepts implemented in
program written (5) programs (3)
b. Result and All test cases are successful, all Moderately debugs the Test cases are not taken
documentation errors are debugged with own programs , few test case are care , unable to debug
(5 marks) practical knowledge and clear unsuccessful and Partial the errors and no proper
documentation according to the documentation documentation (1)
guidelines (5) (3)

R4: RECORD EVALUATION RUBRIC (MAX MARKS 20)


Sl. Needs
Parameter Excellent Good Average
No. Improvement
a. Documentation Meticulous record writing Write up contains Write up contains Program written
(10 marks) including program, comments program and test only program with few
and test cases as per the cases, but comments (15) mistakes (10)
guidelines mentioned (20) are not included (18)

Departments of CSE & ISE, RNSIT


[DOCUMENT TITLE]
TEST /LAB INTERNALS MARKS (MAX MARKS 10)
Write up Execution Viva Sign Total Avg. Final
TEST # 6 28 6 40 40 10

TEST-1

TEST-2

REGULAR LAB EVALUATION (MAX MARKS 10)


Write
Lab Date of Exen. Viva Total Teacher
Additional programs up
program Execution (10) (10) 30 Signature
(10)

10

11

12

13

14

15

Total
Marks

Final Marks obtained from test (10) Lab in charge :


+ regular evaluation (10)
HOD :

Departments of CSE & ISE, RNSIT


PREFACE

We have developed this comprehensive laboratory manual on C Programming Lab with two
primary objectives: To make the students comfortable with basic principles of problem solving and to
train them in evolving as an efficient C programmer by strengthening their programming abilities.

This material is divided into two parts: Part-A and Part-B, which provides the students an exposure to
problem solving approaches and solution to number of problems using C programming language. The
problems discussed in this manual comprises of an algorithm, programming solution, alternative logic
and extensive test cases. Viva questions, frequently appeared examination questions and practicing
programming problems constitute an indispensable part of this material.

Our profound and sincere efforts will be fruitful only when students acquire the extensive knowledge
by reading this manual and apply the concepts learnt apart from the requirements specified in C
Programming Laboratory as prescribed by VTU, Belagavi.

Departments of CSE and ISE


C Programming Lab (18CPL17/27)

[DOCUMENT TITLE]

TABLE OF CONTENTS

SL.NO. CONTENTS PAGE NO.

1 Computer hardware and programming environment 1


1.1 Functional block diagram of computer 1
1.2 Operating system and its types 3
1.3 Programming environments 4
1.4 Problem solving techniques 7

PART A
2 Simple Calculator 10
2.1 Algorithm 10
2.2 Program 11
2.3 Test Cases 11

3 Quadratic Equation 13
3.1 Algorithm 13
3.2 Program 14
3.3 Test Cases 15

4 Palindrome 17
4.1 Algorithm 17
4.2 Program 17
4.3 Test Cases 18

5 Electricity Bill 20
5.1 Algorithm 20
5.2 Program 21
5.3 Test Cases 21

6 Binary Search 23
6.1 Algorithm 23
6.2 Program 23
6.3 Test Cases 24

7 To Check Prime or Not 25


7.1 Algorithm 25
7.2 Program 25
7.3 Test Cases 26

PART B
8 Matrix Multiplication 28
8.1 Algorithm 28
8.2 Program 29
8.3 Test Cases 30

9 sine Series 32
9.1 Algorithm 32
9.2 Program 33
9.3 Test Cases 33

10 String Manipulation Functions 35


10.1 Algorithm 35
10.2 Program 36

Departments of CSE & ISE, RNSIT ~i~


C Programming Lab (18CPL17/27)

[DOCUMENT TITLE]

10.3 Test Cases 37

11 Bubble Sort 39
11.1 Algorithm 39
11.2 Program 40
11.3 Test Cases 40

12 Square Root 42
12.1 Algorithm 42
12.2 Program 42
12.3 Test Cases 43

13 Student Record using Array of Structures 44


13.1 Algorithm 44
13.2 Program 45
13.3 Test Cases 46

14 Use of Pointers 47
14.1 Algorithm 47
14.2 Program 48
14.3 Test Cases 48

15 Binary to Decimal Conversion 50


15.1 Algorithm 50
15.2 Program 50
15.3 Test Cases 51

Appendix –A : list of module-wise exercise problems 52

Departments of CSE & ISE, RNSIT ~ ii ~


C Programming Lab (18CPL17/27)

[DOCUMENT TITLE]

SYALLABUS
SEMESTER I/ II

C PROGRAMMING LABORATORY
Sub Code : 18CPL17 / 18CPL27 CIE Marks : 40

Hrs/ Week : 03 Exam Hours : 03

Credits : 01 SEE Marks : 60

Course Learning Objectives:


This course enable will students to:
 Write flowcharts, algorithms and programs.
 Familiarize the processes of debugging and execution.
 Implement basics of C programming language.
 Illustrate solution to the laboratory programs.

LABORATORY PROGRAMS

1. Familiarization with computer hardware and programming environment, concept of


naming the program files, storing, compilation, execution and debugging. Taking any
simple C- code.

PART A

2. Develop a program to solve simple computational problems using arithmetic expressions


and use of each operator leading to simulation of a commercial calculator. (No built-in
math function)
3. Develop a program to compute the roots of a quadratic equation by accepting the
coefficients. Print appropriate messages.
4. Develop a program to find the reverse of a positive integer and check for palindrome or
not. Display appropriate messages.
5. An electricity board charges the following rates for the use of electricity: for the first 200
units 80 paise per unit: for the next 100 units 90 paise per unit: beyond 300 units Rs 1 per
unit. All users are charged a minimum of Rs. 100 as meter charge. If the total amount is
more than Rs 400, then an additional surcharge of 15% of total amount is charged. Write a
program to read the name of the user, number of units consumed and print out the charges.
6. Introduce 1D Array manipulation and implement Binary search.
7. Implement using functions to check whether the given number is prime and display
appropriate messages. (No built-in math function)

PART B
8. Develop a program to introduce 2D Array manipulation and implement Matrix
multiplication and ensure the rules of multiplication are checked.
9. Develop a Program to compute Sin(x) using Taylor series approximation .Compare your
result with the built- in Library function. Print both the results with appropriate messages.

Departments of CSE & ISE, RNSIT ~ iii ~


C Programming Lab (18CPL17/27)

[DOCUMENT TITLE]

10. Write functions to implement string operations such as compare, concatenate, string
length. Convince the parameter passing techniques.
11. Develop a program to sort the given set of N numbers using Bubble sort.
12. Develop a program to find the square root of a given number N and execute for all possible
inputs with appropriate messages. Note: Don’t use library function sqrt(n).
13. Implement structures to read, write, compute average- marks and the students scoring
above and below the average marks for a class of N students.
14. Develop a program using pointers to compute the sum, mean and standard deviation of all
elements stored in an array of n real numbers
15. Implement Recursive functions for Binary to Decimal Conversion.

Laboratory Outcomes: The student should be able to:


 Write algorithms, flowcharts and program for simple problems.
 Correct syntax and logical errors to execute a program.
 Write iterative and wherever possible recursive programs.
 Demonstrate use of functions, arrays, strings, structures and pointers in problem solving.

Practical Examination Procedure:


 All laboratory experiments, excluding the first, are to be included for practical examination.
 Experiment distribution
 For questions having only one part: Students are allowed to pick one experiment from
the lot and are given equal opportunity.
 For questions having part A and B: Students are allowed to pick one experiment from
part A and one experiment from part B and are given equal opportunity.
 Strictly follow the instructions as printed on the cover page of answer script for breakup of
marks
 Change of experiment is allowed only once and marks allotted for procedure part to be made
zero.
 Marks Distribution (Subjected to change in accordance with university regulations)
a) For questions having only one part :
Procedure + Execution + Viva-Voce = 15+70+15 =100 Marks
b) For questions having part A and B :
i. Part A – Procedure + Execution + Viva = 4 + 21 + 5 = 30 Marks
ii. Part B – Procedure + Execution + Viva = 10 + 49+ 11 = 70 Marks

Departments of CSE & ISE, RNSIT ~ iv ~


ACKNOWLEDGMENT

A material of this scope would not have been possible without the contribution of
many people. We express our sincere gratitude to Dr. R N Shetty, Chairman, RNS
Group of Companies for his magnanimous support in all our endeavors.

We are grateful to Dr. M K Venkatesha, Principal, RNSIT, Dr. P Kiran, HOD, CSE
and Dr. Sathish Kumar S, HOD, ISE for extending their constant encouragement and
support.

Our heartfelt thanks to Dr. M J Sudhamani, Mrs. Vidya Y, Mrs. Soumya N G,


Mr. Chetan D S, Mr. Shrinivas Biradar, Mrs. Akshata S Bhayyar, Mr. Ramesh S
Chakrasali, Mrs. Geetanjali C M and Mrs. Deepa S for their unparalleled
contribution throughout the preparation of this comprehensive manual. We also
acknowledge our colleagues for their timely suggestions and unconditional support.

Departments of CSE and ISE


C Programming Lab (18CPL17/27)

[DOCUMENT TITLE]

LABORATORY PROGRAMS
1. Familiarization with computer hardware and programming environment, concept of
naming the program files, storing, compilation, execution and debugging. Taking any
simple C- code.

1.1 Description about Functional block diagram of Computer

A computer is an electronic device, which mainly performs the four functions as reading,
processing, displaying and storing on data. Fig. 1 portrays various functional units of
computer system. These functions of a computer system can be carried out by using the three
main units namely input unit, system unit and output unit. The block diagram of a computer
system is as follows:

Fig 1: Block Diagram of a Computer

Notations:
 Data and Results flow
 Control instructions to other units from control unit ---------------------------
 Instructions from memory unit to control unit

System Unit or Central Processing Unit (CPU): is commonly known as “processor” that
executes the instructions of a computer program. It has Control Unit (CU) and Arithmetic &
Logical Unit (ALU).

Input unit: is used to enter data and information into a computer. The devices like keyboard,
mouse and scanner are commonly used input devices.

 A keyboard is used to enter alphanumeric characters and symbols.


 The mouse is used to pick or select a command from the monitor screen.
 A scanner is used to scan an image or read a barcode and so on.

Departments of CSE & ISE, RNSIT Page | 1


C Programming Lab (18CPL17/27)

[DOCUMENT TITLE]

Arithmetic and Logic Unit (ALU): is a digital circuit that performs arithmetic (Add, Sub,
Multiplication, Division) and logical (AND, OR, NOT) operations.

Control unit (CU): is the circuitry that controls the flow of information through theprocessor
and coordinates the activities of the other units within the processor.

Functions of Control unit

 Accessing data and instructions from memory unit.


 Interpreting instructions.
 Controlling input and output units.
 Overall supervision of a Computer system.

Memory Unit (MU): is the unit where all the input data and results are stored either
temporarily or permanently. The memory of a computer has two types:

 Main Memory / Primary Memory units


 Random Access Memory (RAM)
 Read Only memory(ROM)
 Secondary Memory / Auxiliary Memory

Output Unit: It is used to display or print results from a computer. Monitor, printer and
plotters are commonly used output devices.

Bus: A bus is a collection of wires that carries data/instructions. It connects physical


components such as printed circuit boards, CPU, memory, peripherals etc., for sharing of
information and communication with one another.

Types of Buses:

System Buses: The system buses are used to transfer the data and instructions between Main
memory (Random Access Memory) and CPU. Table 1 lists the different types of system buses.

Table 1: Types of system buses

Data Bus Address Bus Control Bus

It is used to transfer the It is used to transfer the It is used to transfer the


data between Processor, addresses of data and control signals between
Memory and I/O devices instructions stored in CPU, Memory and I/O
Memory. devices.
Bidirectional in nature Unidirectional in nature Unidirectional or
Bidirectional in nature

Departments of CSE & ISE, RNSIT Page | 2


C Programming Lab (18CPL17/27)

[DOCUMENT TITLE]

I/O Buses: The buses which are used to connect all I/O devices with CPU and Memory
are called I/O buses. Table 2 shows three types of I/O buses.

Table 2: Types of I/O buses


PCI Bus ISA Bus USB Bus
PCI stands for Peripheral ISA stands for Industry USB stands for
Component Interconnect Standard Architecture Universal Serial Bus
The motherboard will be It helps to connect various
having 3 or 4 PCI connectors, This s simple and slowest bus I/O devices like
so that we can insert various used in IBM PCs keyboard, mouse, pen drives,
chips. printer, etc.
Fastest and presently Oldest, simplest and Newest and widely
more powerful bus slowest bus used bus

Mother Board: Mother Board is a set of Integrated Chips (ICs) which are designed to work
together. It controls the flow of data/instructions within computer. It is the main board on
which other hardware components are connected to enable the computer system to work as an
integrated unit. It consists of sockets, slots, power connectors and bus.

Chip sets: Chip set is the set of integrated chips that are designed to work together. These set of
chips controls the flow of information on computer. Fig. 2 depicts chip sets. The chips may be
controllers for memory, cache, hard drive, key board and peripherals.

Fig. 2: Chip Sets

1.2 Operating System and its types

An Operating System (OS) is system software that controls and supervises the hardware
components of a computer system and it provides the services to computer users. Also called
as Resource Manager that manages the resources such as CPU, Memory, I/O devices,
Job/Task/Process etc., a computer cannot run without OS. Fig. 3 depicts architecture of
operating system. The major functions of OS includes: CPU Management, Memory
Management, File Management, Device Management, Process/Task/Job Management and
Security Management.

Some of the examples of Operating Systems are Windows, UNIX, XENIX, Macintosh OS,
Fedora, and Android, etc.

Departments of CSE & ISE, RNSIT Page | 3


C Programming Lab (18CPL17/27)

[DOCUMENT TITLE]

Fig 3: Operating System

1.3 Programming Environments

1.3.1 C Program Execution in Windows Operating System

The C Developing Environment is a screen display with windows and pull-down menus. The
menus may be used to invoke all the operations necessary to develop the program, including
editing, compiling, linking, and debugging and program execution.

Invoking the Turbo C Integrated Development Environment (IDE)

The default directory of Turbo C compiler is c:\tc\bin. So to invoke the IDE from the windows
you need to double click the TC icon in the directory. The alternate approach is that we can
make a shortcut of tc.exe on the desktop.

Opening New Window in Turbo C

To type a program, you need to open an Edit Window. For this, open file menu and click
“new”. A window will appear on the screen where the program may be typed.

Saving a Program in Turbo C

To save the program, select save command from the file menu. This function can also be
performed by pressing the [F2] button. A dialog box will appear asking for the path and name
of the file. Provide an appropriate and unique file name. You can save the program after
compiling too but saving it before compilation is more appropriate.

Making an Executable File in Turbo C

The source file is required to be turned into an executable file. This is called “Making” of the
.exe file. The steps required to create an executable file are:

Departments of CSE & ISE, RNSIT Page | 4


C Programming Lab (18CPL17/27)

[DOCUMENT TITLE]

i. Create a source file, with a .c extension.


ii. Compile the source code into a file with the .obj extension.
iii. Link your .obj file with any needed libraries to produce an executable program

All the above steps can be done by using Run option from the menu bar or using key
combination Ctrl+F9 (By this linking & compiling is done in one step).

Compiling and linking in the Turbo C IDE

In the Turbo C IDE, compiling and linking can be performed together in one step. There are
two ways to do this: you can select Make EXE from the compile menu, or you can press the
[F9] key

Correcting Errors in Turbo C

If the compiler recognizes some error, it will let you know through the Compiler window.
You‟ll see that the number of errors is not listed as 0, and the word “Error” appears instead of
the word “Success” at the bottom of the window. The errors are to be removed by returning to
the edit window. Usually these errors are a result of a typing mistake. The compiler will not
only tell you what you did wrong, they‟ll point you to the exact place in your code where you
made the mistake.

Executing a Programs in Turbo C

If the program is compiled and linked without errors, the program is executed by selecting Run
from the Run Menu or by pressing the [Ctrl+F9] key combination.

Exiting Turbo C IDE

An Edit window may be closed in a number of different ways. You can click on the small
square in the upper left corner, you can select close from the window menu, or you can press
the Alt+F3 combination. To exit from the IDE, select Exit from the File Menu or press Alt+X
Combination.

Open Turbo C and click on File -> New to open the editor to type the program.

Departments of CSE & ISE, RNSIT Page | 5


C Programming Lab (18CPL17/27)

[DOCUMENT TITLE]

1.3.2 C Program Execution in Linux Operating System:

Click Applications -> System Tools -> Terminal on desktop to open terminal

Get Into gedit

To start gedit: To use gedit on a file, type in vi filename. Fig. 4 shows the command to open a
new file. If the file named filename exists, then the first page (or screen) of the file will be
displayed; if the file does not exist, then an empty file and screen are created into which you
may enter text (refer figure 5).

* gedit filename edit filename starting at line 1

recover filename that was being edited when system


gedit -r filename crashed

Example: gedithello.cwhere hello is file name and it is programmer‟s choice.

Fig 4: To open editor

Fig 5: Editor Window

To compile C program

The figure given in Fig. 6 demonstrates the commands to compile and run the program file.
Type cc command followed by filename.c

Ex: $cc Hello.c

After compilation, run the program using ./a.out command or Compile with optional
executable filename: $cc – o Hello Hello.c

Fig 6: Compiling and executing hello.c

Departments of CSE & ISE, RNSIT Page | 6


C Programming Lab (18CPL17/27)

[DOCUMENT TITLE]

1.4 Problem Solving Techniques

There are three approaches to problem solving, namely: Algorithm, Flowchart and Pseudocode

Algorithm: The algorithm is a step-by-step procedure to be followed in solving a problem. It


provides a scheme to solve a particular problem in finite number of unambiguous steps. It
helps in implementing the solution of a problem using any of the programming languages.

In order to qualify as an algorithm, a sequence of instructions must possess the following


characteristics:

Definiteness: Instructions must be precise and unambiguous i.e. each and every instruction
should be clear and should have only one meaning.
Finiteness: Not even a single instruction must be repeated infinitely. i.e., each instruction
should be performed in finite time.
Termination: At some finite step the algorithm should terminate.

Example: To compute the Area of Rectangle

ALGORITHM: AREA_of_RECTANGLE

[This algorithm takes length and breadth, thesides of the rectangle as input and computes the
area of rectangle using the formula area=length * breadth. Finally it prints the area of
rectangle]

Step 1:[Initialize]
Start
Step 2:[Input the sides of Rectangle]
Read length, breadth
Step 3:[Compute the area of rectangle]
Area=length*breadth
Step 4:[Display the Area]
Print Area
Step 5:[Finished]
Stop

Flowchart: A flowchart is a graphical or symbolic representation of an algorithm. They are


basically used to design and develop complex programs to help the users to visualize the logic
of the program so that they can gain a better understanding of the program and find flaws,
bottlenecks, and other less-obvious features within it. The following Table 3 shows the
symbols used in flowchart along with its descriptions. Fig. 7 depicts the flowchart to compute
area of rectangle.

Departments of CSE & ISE, RNSIT Page | 7


C Programming Lab (18CPL17/27)

[DOCUMENT TITLE]

Table 3: Common flowchart symbols

Symbol Name Description

Represents the starting and terminal


Oval
point

Represents the process steps defined


Rectangle
in algorithm

Indicate the reading operation used


for input/output or data or
Parallelogram
information from/to any device
Indicates the decisions(questions)
and consequently the branch points
or the paths to be followed based on
Rhombus
the result of the question
Shows the flowchart direction and
connects the various flow chart
Arrows
symbols
Shows the continuation from one
Small circle
point in the process flow to another

Represents Looping structures


Hexagon

Predefined process Indicates Subroutines

Fig 7: To compute the area of rectangle

Departments of CSE & ISE, RNSIT Page | 8


C Programming Lab (18CPL17/27)

[DOCUMENT TITLE]

Pseudocode: A compact and informal high-level description of an algorithm that uses the
structural conventions of a programming language. Details such as keywords, variable
declarations and system-specific code are not used while writing pseudocode.

Example: To compute the area of Rectangle

Begin
Input length, breadth

Area=length*breadth

Print Area
End

SAMPLE C PROGRAM

/*program to print area of a triangle*/

#include<stdio.h>
int main()
{
int b, h, area;
clrscr();
printf("enter the values for b and h\n");
scanf("%d%d",&b,&h);
area=0.5*b*h;
printf("Area of a triangle =%d",area);
return 0;
}

Departments of CSE & ISE, RNSIT Page | 9


C Programming Lab (18CPL17/27)

[DOCUMENT TITLE]

PART – A
SIMPLE CALCULATOR
2. Develop a program to solve simple computational problems using arithmetic expressions
and use of each operator leading to simulation of a commercial calculator (No built-in
math function).

A calculator is a machine which allows people to do math operations more easily. For example,
most calculators will add, subtract, multiply, and divide. There are two types of electronic
calculators available, namely: simple calculator and scientific calculator.

Purpose: To demonstrate SWITCH conditional statements.


Procedure: To read arithmetic operator and operands from the user to demonstrate the
working of a simple calculator.
Input: Arithmetic operators like „+‟, ‟-„, „*‟, ‟/‟ and two operands.
Expected Output: Result of the arithmetic expression.

2.1 Algorithm
Step 1: Start
Step 2: [Input Operator]
Read oper
Step 3: [Input two operands]
Read op1 & op2
Step 4: [If the user enters + or - or * or / then follow
the below steps else GOTO Step 7 and exit the program]
Step 5: IF oper = ‟+‟ then
Res ← op1+op2
ELSE IF oper = ‟-‟ then
Res ← op1-op2
ELSE IF oper = ‟*‟ then
Res ← op1*op2
ELSE IF op2 = 0
Print “Divide by zero error"
GOTO Step 7
ELSE if(oper = ‟/‟)
Res ← op1/op2
ELSE
Print “Not a valid operator”
ENDIF
Step 6: [Display Result]
Print Res
Step 7: Stop

Departments of CSE & ISE, RNSIT Page | 10


C Programming Lab (18CPL17/27)

[DOCUMENT TITLE]

2.1 Program
#include<stdio.h>
#include<stdlib.h>
void main()
{
int op1,op2,res; // Declaration of variables
char oper;
printf("Enter the operator\n"); // Reading Operator
scanf("%c",&oper);
// Reading Two Numbers
printf("Enter two operands( Only integers) \n");
scanf("%d%d",&op1,&op2);
switch(oper)
{
case '+': res=op1+op2; // Addition
break;
case '-': res=op1-op2; // Subtraction
break;
case '*': res=op1*op2; // Multiplication
break;
// Checking for Division by zero error
case '/': if(op2==0)
{
printf("Divide by zero error");
exit(0); // Program Termination
}
else
res=op1/op2;
break;
default: printf("Not a valid operator");
exit(0);
}
printf("Result=%d",res); // Displaying the Result
}

2.3 Test Cases


Test No Input Parameters Expected Output Obtained Output
Operator= +
1 Res = 19 Res = 19
a = 9, b = 10
Operator= /
2 Divide by zero error Divide by zero error
a = 9, b = 0
Operator= /
3 Res = 4 Res = 4
a = 8, b = 2
Operator = #
4 Not a valid operator Not a valid operator
a = 9, b = 10
Test for the following cases and record your observation
Operator = *
5
a = 5, b = 3

Departments of CSE & ISE, RNSIT Page | 11


C Programming Lab (18CPL17/27)

[DOCUMENT TITLE]

Frequently Appeared Exam Problems related to if –else and switch case


constructs

1 List all operators used in C Language and evaluate the expression. (Jan 2019)
 X=a-b/3-c*2-1 when a=9,b=12 and c=3
 10 !=10 || 5<4&&8
2 Write a C Program to compute Simple Interest. Draw the flow chart for (Jan 2019)
same.
3 Write the basic structure of C program. Explain each section briefly (July 2019)
with suitable example

Viva Questions

1 List C- tokens and explain them.


2 Define variables, keywords and identifiers?
3 What is ASCII code? What is a Unicode character? Mention their applications.
4 Half byte is known as …………………………………………………………..…………………..

5 List different data types available in C along with their size specifications.
6 Give the syntax for ternary operator
7 When to use backslash constants?
8 What is a sizeof () operator?
9 Can the case value be a float data in switch statement?
10 Compare switch case and else if ladder.
11 What is the difference between “=” and “= =”?
12 List unformatted input/output statements.
13 What is the difference between “&” and “&&”?
14 What is default case? What is the significance of using it in switch case?
15 List different unconditional branching statements.
16 What is the purpose of ampersand in scanf () function?
17 Which control characters are used to input octal and hexadecimal data?
18 Determine the output of the following statements
printf(“%-20.9s”,”RNS INSTITUTE”);
printf(“*.*f, 8,5,19.4333);
printf(“%5d”,10);
19 In response to the input statement
scanf(“%4d%*%d”, &year, &code, &count);
the data is keyed in is 19883745
What value does the computer assign to the variables year, code and count?
20 Consider the evaluation of the following function:
Y=1.5x+3 for x<=2
Y=2x+5 for x.2
Express the above function using conditional/ternary operator.

Alternative Solution
Demonstrate simple calculator using cascading if.

Departments of CSE & ISE, RNSIT Page | 12


C Programming Lab (18CPL17/27)

[DOCUMENT TITLE]

QUADRATIC EQUATION
3. Develop a program to compute the roots of a quadratic equation by accepting the
coefficients. Print appropriate messages.

A quadratic equation is an equation in the form of ax2+bx+c=0, where „a‟ is not equal to 0.
There are different ways to find out the value of x. Plotting the function on a graph is one way.
Graphing a quadratic equation makes it is very easy to find the roots, but it is not always
convenient. We can find the roots by using Quadratic Equation formula:

Where a, b and c are coefficients and disc = b2 - 4ac

Purpose: To demonstrate IF, IF-ELSE conditional constructs.


Procedure: The program reads the coefficients a, b and c. Prints appropriate error message if
any of the coefficients value is 0, otherwise calculates Discriminant. Based on the discriminate
value, classify and calculate all possible roots and print them with suitable messages.
Input: Three coefficients a, b and c of quadratic equation
Expected Output: all possible roots of a quadratic equation for the given set of coefficients
along with appropriate message. The possible roots are:
i. Linear equation and its roots
ii. Real and equal roots
iii. Imaginary roots

3.1 Algorithm
Step 1: [Initialize] Start
Step 2: [Input coefficients of quadratic equation]
read a ,b, c
Step 3: [Check for valid coefficients]
If a =0 and b= 0 then
print “Roots cannot be determined”
[Check for linear equation]
else a=0 then
root1 ← (-c/b)
print “Linear equation”,root1
goto step 5
Step 4: [Compute discriminant value]
disc ← b*b-4*a*c
Step 5:[Based on discriminant value, classify and
calculate all possible roots and print them]
5.1[If discriminant value is 0, roots are real & equal]

Departments of CSE & ISE, RNSIT Page | 13


C Programming Lab (18CPL17/27)

[DOCUMENT TITLE]

if disc=0 then
root1← root2 ← (-b/2*a)
print “Real & equal roots”, root1, root2
5.2 [If discriminant value is >0, roots are real
distinct]
else if disc>0then
root1← (-b+√disc)/2*a)
root2 ← (-b-√disc)/2*a)
print “Real & distinct roots”, root1, root2
5.3 [If discriminant value is <0, roots are imaginary]
else
real ← -b/(2*a)
imag ← √(fabs(disc))/(2*a)
root1 ← (real) + i (imag)
root2 ← (real) - i (imag)
print “Imaginary roots”, root1, root2
endif
endif
Step 6: [Finished] End

3.2 Program
#include<stdio.h>
#include<math.h>
int main()
{
float a, b, c, disc; // Declaration of variables
float root1,root2,real,imag;
// Reading Co-efficient of Quadratic Equation
printf("Enter a, b and c values\n");
scanf("%f%f%f",&a,&b,&c);
if( (a == 0) && (b == 0) )
{
printf("Invalid coefficients\n");
printf (" Try Again with valid inputs!!!!\n");
}
else if(a == 0) // Linear equation and its root
{
printf("Linear equation\n");
root1 = -c / b;
printf("Root=%.3f", root1);
}
else // Quadratic Equation
{
// b2 - 4ac is known as discriminant

Departments of CSE & ISE, RNSIT Page | 14


C Programming Lab (18CPL17/27)

[DOCUMENT TITLE]

disc = b*b - 4*a*c;


if(disc == 0) // Real & equal roots
{
printf("The roots are real and equal\n");
root1 = root2 = -b/(2*a);
printf("Root1=%.3f\n Root2 = %.3f", root1, root2);
}
else if(disc>0) // Real & distinct roots
{
printf("The roots are Real and Distinct\n");
root1 = (-b + sqrt(disc)) / (2*a);
root2 = (-b - sqrt(disc)) / (2*a);
printf("Root1=%.3f\nRoot2 = %.3f",root1,root2);
}
else //Imaginary roots
{
printf("The roots are Real and Imaginary\n");
real = -b / (2*a);
//fabs() returns only number ignoring sign
imag = sqrt(fabs(disc))/(2*a);
printf("Root1=%.3f + i %.3f \n",real, imag);
printf("Root2 = %.3f - i %.3f",real,imag);
}
}
return 0;
}

3.3 Test Cases


Test No Input Parameters Expected output Obtained output

Invalid coefficients Invalid coefficients


1 a = 0, b = 0, c = 0
Try Again with valid inputs!!!! Try Again with valid inputs!!!!
Linear equation Linear equation
2 a = 0, b = 2, c = 8
Root = - 4 Root = - 4.000
Roots are real and equal Roots are real and equal
3 a = 1, b = 6, c= 9
Root1 = -3 and Root2 = -3 Root1 = -3.000 and Root2 = -3.000

Roots are real and distinct Roots are real and distinct
4 a = 1, b = -5, c = 3
Root1 = 4.30 and Root2= 0.69 Root1 = 4.303 and Root2 = 0.697

Roots are real and imaginary Roots are real and imaginary
6 a = 1, b = 4, c = 7 Root1 = - 2 + i 1.73 Root1 = - 2.000 + i 1.732
Root2 = - 2 – i 1.73 Root2 = - 2.000 – i 1.732
Test for the following cases and record your observations
7 a =0, b= 4, c= 5

Departments of CSE & ISE, RNSIT Page | 15


C Programming Lab (18CPL17/27)

[DOCUMENT TITLE]

8 a = 2, b= -7, c=0

9 a = 2, b= -7, c=8

Frequently Appeared Exam Problems related to conditional constructs

1 Define a variable. Explain the rules for constructing variables in C Language (Jan 2019)
2 Explain the formatted I/O functions of C language with syntax and example (Jan 2019)
3 Define data type. Explain Primitive Data Types supported by C language with (Jan 2019)
examples.
4 State whether the following are valid identifiers or not: integers, float, I am, (July 2019)
123_AbC.
5 Convert the following mathematical expression into C equivalent statements (Jan 2020)

Viva Questions

1 How do you recognize the function as a built-in function?


2 Differentiate between abs() and fabs()?
3 List the decision making statements available in C language.
4 Write the syntax and flow chart of if statement.
5 Differentiate between if and switch statements.
6 What is meant by dangling else problem?
7 List unconditional control statements in C.
8 Mention the real time application of multi-way decision statement.
9 What is the difference between multiple if and else if ladder?
10 When to use break statement in a program?
11 What is the output of the below code snippet?
int i=5, j=6,k=7;
if(i = =(1,2) printf(“ hai”);
else printf(“hello”);

12 What is the output of the below code snippet?


int i=5, j=6,k=7;
if(i > j = =k) printf(“%d %d %d”, i++,++j,--k);
else printf((“%d %d %d”, i, j, k);

Other alternatives:
Find the roots of quadratic equation program using
i) only if statement ii) Combination of if and switch statement

Departments of CSE & ISE, RNSIT Page | 16


C Programming Lab (18CPL17/27)

[DOCUMENT TITLE]

PALINDROME
4. Develop a program to find the reverse of a positive integer and check for palindrome or
not. Display appropriate messages

A palindromic number is a number (such as 16461) that remains the same when its digits are
reversed. Palindrome is reversing a given object that gives the same result as original. Object
can be anything, a number, a string, phrase, etc. For example 121, MADAM

Purpose: To demonstrate the working of WHILE loop.


Procedure: Input a number num; reverse it to rev. Check whether original number num is
same as its reverse number rev. If it is same, the number is palindrome. Otherwise, the given
number is not palindrome.
Input: An integer number num.
Expected Output: Reversed number rev and checks whether it is palindrome or not.

4.1 Algorithm
Step 1: Start
Step 2: [Input the original number]
Read num
Step 3: [Preserve the input number in temporary variable]
n=num
Step 4: [Iterate to find the reverse of the given number]
WHILE num! =0
remainder← (num mod 10)
num =num/10
rev= rev*10+remainder
end WHILE
Step 5: [Display the reversed number]
Print rev
Step 6: [Check if reversed number is same as the original]
IF rev = n then
Print “The given number is a palindrome “
ELSE
Print “The given number is not a palindrome “
ENDIF
Step 7: Stop

4.2 Program
#include<stdio.h>
int main()
{
int n,rev=0,num, remainder ;//Variables declaration
printf("Enter the number\n");
scanf("%d",&num); //Read variable num
n=num; //Preserving original value to „n‟
while(num!=0) //Reversing the number
{

Departments of CSE & ISE, RNSIT Page | 17


C Programming Lab (18CPL17/27)

[DOCUMENT TITLE]

remainder = num%10; //Digit Separation


num = num/10; //Eliminate the right-most digit
rev = rev*10+ remainder;//Reversing the number
}
//Print the value of rev
printf("The reverse number is %d",rev);
if(rev == n) //Comparing „n‟ with “rev”
//Print the value of „n‟
printf("\n %d is a palindrome",n);
else
printf("\n %d is not a palindrome",n);
return 0;
}

4.3 Test cases


Input
Test No Expected output Obtained output
Parameters
Reverse number is 1441 Reverse number is: 1441
1 N = 1441
Palindrome 1441 is a palindrome
Reverse number is 7899 Reverse Number: 7899
2 N = 9987
Not a palindrome 9987 is not a palindrome
Reverse number is -12221 Reverse number : -12221
3 N = -12221
Palindrome -12221 is a palindrome
Reverse number is -8576 Reverse Number: -8576
4 N = -6758
Not a palindrome -6758 is not a palindrome
Reverse number is 0 Reverse number : 0
5 N=0
Palindrome 0 is a palindrome
Test for the following cases & record your observations
8 N = 1234
9 N = 1100
10 N = 0203

Frequently Appeared Exam Problems related to looping constructs

1 Differentiate between while loop and do-while loop (Dec2018/Jan2019 )


2 Write the syntax of different branching statement and explain (Dec2018/Jan2019 )
their working
3 Write a program to find factorial of a number using while loop (Dec2018/Jan2019 )
4 Write a program to find given integer is palindrome or not (Dec2019/Jan2020 )
5 Write a program to convert binary to decimal and vice versa using (Dec2019/Jan2020 )
while loop
6 Write a program to find sum of n natural numbers using while (Dec2018/Jan2019 )
loop
7 Write a program to find factorial of a number using do-while loop (Dec2018/Jan2019 )
8 Write a program to convert binary to decimal and vice versa using (Dec2018/Jan2019 )
do-while loop

Departments of CSE & ISE, RNSIT Page | 18


C Programming Lab (18CPL17/27)

[DOCUMENT TITLE]

Viva Questions
1 What is a palindrome?
2 When do we use looping statements? Explain the syntax and flowchart of while loop.
3 Write the syntax and flowchart for „do-while‟ loop.
4 Find the output of the below code:
i = 20;
while(i>0)
{
printf(“%d”,i);
if(i%5= =0)
continue;
}
5 Differentiate between entry controlled and exit controlled loops.
6 The minimum times do-while loop will work ………………………………………………………………..

7 How to achieve early exit from the loop? How to skip a part of the body of the loop under
some conditions?
8 When do we use the following statement?
for (; ;)
9 In an exit controlled loop, if the body is executed n times, the test condition is evaluated --------

times.
-----------

10 What is the output of the below code snippet?


int i=9;
for (i = 0; i< =3; i+ +);
printf( “%d”, i);

Departments of CSE & ISE, RNSIT Page | 19


C Programming Lab (18CPL17/27)

[DOCUMENT TITLE]

SELECTION STATEMENTS
5. An electricity board charges the following rates for the use of electricity: for the first 200
units 80 paise per unit: for the next 100 units 90 paise per unit: beyond 300 units Rs 1 per
unit. All users are charged a minimum of Rs. 100 as meter charge. If the total amount is
more than Rs 400, then an additional surcharge of 15% of total amount is charged. Write
a program to read the name of the user, number of units consumes and print out the
charges.

The else...if statement in C-programming


The else...if statement is useful when you need to check multiple conditions within the
program, nesting of if-else blocks can be avoided using else...if statement.

Purpose: To demonstrate the working of else-if statement.


Procedure: Input the Consumer name and consumed electricity in number of units. Calculate
the electricity bill based on the charges provided and print appropriate messages as per the
number of units they have consumed.
Input: Consumer name and units consumed.
Expected Output: Consumer name and electricity bill.

5.1 Algorithm
Step 1: Start
Step 2: [Input the consumers name and units]
Read name and units
Step 3: [Check the units with the below steps]
IF units < 200 then
amount ← units*80
ELSE IF n>200 && n<=300 then
amount ← 200*80;
amount ← amount + (n-200) *90
ELSE
amount ← (n-300)*100;
amount ← amount+100*90;
amount =amount+200*80;
END IF
amount=amount/100;
amount=amount+100;
IF amount>400 then
amount=amount+15*amount/100
END IF
Step 4: [Display Result]
Print the amount
Step 5: Stop

Departments of CSE & ISE, RNSIT Page | 20


C Programming Lab (18CPL17/27)

[DOCUMENT TITLE]

5.2 Program
#include<stdio.h>
void main()
{
char name[20]; //Variable declaration
int units;
float amount;
printf("Enter the consumer name\n");
scanf("%s", name); //Read the name
printf("Enter no. of units consumed \n");
scanf("%d",&units); //Read the value for units
if(units<=200)
{
amount=units*80; // Calculate amount
}
else if(n>200 && n<=300)
{
amount=200*80;
amount=amount+(n-200)*90;
}
else
{
amount=(n-300)*100;
amount=amount+100*90;
amount=amount+200*80;
}
amount=amount/100; //Converting amount to rupees

amount=amount+100; //Adding Meter Charges


if(amount>400)
{
amount=amount+15*amount/100;
}
}

5.3 Test Cases


Test No Input Parameters Expected output Obtained output
1 N=100 Total Amount to be paid=180 Rs Total Amount to be paid=180Rs
2 N=250 Total Amount to be paid=305 Rs Total Amount to be paid=305Rs
3 N=400 Total Amount to be paid=517.5 Rs Total Amount to be paid=517.5Rs
Test for the following cases & record your observations
4 N=500
5 N=1000
6 N=770

Departments of CSE & ISE, RNSIT Page | 21


C Programming Lab (18CPL17/27)

[DOCUMENT TITLE]

Frequently Appeared Exam Problems related to if else ladder:

1 State the drawback of ladder if-else. Explain how you resolve with an (June/July2019 )
example
2 Explain else-if ladder control statement with syntax and flow chart (June/July2018)
3 Write the syntax of nested if else statement and explain its working (June/July2018)

Viva Questions
1 Explain the syntax and flowchart of for loop.
2 Illustrate the working of nested for loop wrt flow of control.
3 Explain the syntax for goto statement. Why it is not recommended in C?
4 Differentiate between event controlled and counter controlled loop.
5 Identify the header file in which pow() is defined.
6 What is the output of the below code snippets?
for(i=0;i<5;i++) for(i=0;i<5;i++)
{ {
if(i==3) if(i==3)
continue; break;
printf(“%d”,i); printf(“%d”,i);
} }

7 What is the output of below code snippet?


int main()
{
int x = -1;
if(! x)
printf ("Hello”);
else
printf(“ hai”);
return 0;
}
8 What is output of below code snippet?
int main()
{
int x = 0, y = - 433;
if( x )
printf("Hello");
if( ! x && ! y )
printf(“ hey”);
else printf(“ fine”);
}
return 0;
}
9 Write the output of below code.
int x=3,y=4,z=4;
printf(“%d”,(z>=y>=x)?100:200);

Departments of CSE & ISE, RNSIT Page | 22


C Programming Lab (18CPL17/27)

[DOCUMENT TITLE]

BINARY SEARCH
6. Introduce 1D Array manipulation and implement Binary search.

Binary search is the search technique which works efficiently on the sorted lists. The list is
divided into two halves and the item is compared with the middle element of the list. If the
match is found then, the location of middle element is returned, search is over. If the search
key value is less than the middle value, then first half of the list contains the key value.
Otherwise the key value is greater than the middle value, and then the second half contains the
key value. The divide and conquer approach is repeated until the match is found or till the list
is reduced to one non matching element.

Purpose: To demonstrates the concept of looping construct and arrays in C programming.


Procedure: Input N elements of an array and to find whether key element is present or not
Input: Array elements
Expected Output: Successful search or unsuccessful search

6.1 Algorithm
Step 1: Start
Step 2: [Input the number and array elements]
Read num, a[30], key
Step 3: [assign values to variable “low” and variable “high”]
low=0, high=n-1
Step 4: [Iterate until low is less than or equal to high]
WHILE low <= high
mid← (low + high)/2;
IF a[mid]=key then
print successful result
ELSE IF a[mid] > key then
high←mid-1;
ELSE
low←mid+1;
END IF
END WHILE
Step 5:[Print result as unsuccessful search]
Print message as unsuccessful search.
Step 6: Stop.

6.2 Program
#include<stdio.h>
int main()
{
int a[30],i,num,key,low,mid,high;//Variables declaration
printf("\n Enter the Number of Elements");
scanf("%d",&num); //Read num

Departments of CSE & ISE, RNSIT Page | 23


C Programming Lab (18CPL17/27)

[DOCUMENT TITLE]

printf("\n Enter the Elements in Sorted Order : ");


for(i=0;i<num ;i++) scanf("%d", &a[i]);
printf("\n Enter the key element to be searched\n");
scanf("%d", &key); //Read key
low=0; //Assigning low to 0
high=num-1; // Assigning high to n-1
while(low<=high)
{
mid=(low + high)/2; //Find out mid value
if(a[mid]==key) //Compare a[mid] with key
{
printf("element %d is found at %d position:",key,mid+1);
exit(0); //Exit from the program
}
else if(a[mid]>key)
high=mid-1;
else low=mid+1;
}
printf("UNSUCCESSFULL SEARCH\n");
return 0;
}

Frequently Appeared Exam Problems related to array

1 Define array. Write the syntax for declaring and initializing 1-D and (Dec2018/Jan2019 )
2-D arrays.
2 Write a C program to search an element using linear search and binary (Jun/July2019 )
search
3 Write a C program to generate Fibonacci numbers using arrays (July2016)
4 Write a C program to read N integers into an array and find the sum of ( June/July2018)
positive integers.

Viva Questions

1 What is data structure? Why an array is called a data structure?


2 Define array and list its categories.
3 What does the name of an array hold?
4 Is it possible to declare an array size as a negative number?
5 What is the meaning of run time and compile time initialization of array elements?
6 Is the size of an array mutable? Or can we change the size of the array during run time?
7 Does C compiler allow declaring an array without assigning the size of an array?
8 List the different types of searching techniques.
9 Trace the binary search program considering an example array.
10 What are advantages and disadvantages of binary search technique?
11 How binary search is more efficient than linear search? Justify.
12 Consider the array declaration float a[10];
A[15]= 1.234;
Is this a valid C statement? Justify your answer.

Departments of CSE & ISE, RNSIT Page | 24


C Programming Lab (18CPL17/27)

[DOCUMENT TITLE]

TO CHECK IF THE NUMBER IS PRIME OR NOT


7. Implement using functions to check whether the given number is prime and display
appropriate messages (No built-in math function).

A natural number with exactly two factors: 1 and the number itself is called as prime number.
For example 13 is a prime number because it is only divisible by itself and 1, while 14 is not a
prime number because it is divisible by 2 and 7 along with the number itself and 1.

Purpose: To demonstrate user defined functions.


Procedure: The program accepts an integer number and passes it to user defined function. The
used defined function isprime(int) checks whether the parameter passed is prime or not, if the
value is prime then it returns true(1), else it returns false(0). The program works based on the
assumption that the factors of a number will be always be less than the half of given number.
Input: An integer value.
For example 13
Expected Output: value is prime or not

7.1 Algorithm
Step 1: [Initialize] Start
Step 2: [Input integer value (positive integer)]
Read op
Step 3: [To check whether op is prime or not]
For i=2 to op/2
IF op % i==0 then
GOTO Step 4
ELSE
GOTO Step 5
ENDIF
Step 4: [Display result]
Print message not a prime number
Step 5: [Display result]
Print message prime number
Step 6: Stop

7.2 Program
#include<stdio.h>
int isprime(int num) // Function definition
{
int i; //Variable declaration

Departments of CSE & ISE, RNSIT Page | 25


C Programming Lab (18CPL17/27)

[DOCUMENT TITLE]

if(num==0 || num==1)
return 0;
//num/2 reduces the number of iterations
//during conditional checking
for(i=2;i<= num/2;i++)
if(num % i==0){ return 0;}
return 1;
}

int main()
{
int op1; //Variable declaration
printf("Enter a number\n");
scanf("%d",&op1);
if(isprime(op1)) //Function Call
printf("%d is a prime number\n",op1);
else
printf("%d is not a prime number",op1);
return 0;
}

7.3Test Cases
Test No Input Parameters Expected output Obtained output
1 Op = 7 7 is a Prime number 7 is a Prime number
2 Op = 4 4 is not a Prime number 4 is not a Prime number
4 Op = 10

5 Op = 0

6 Op = 1

5 Op = 56

Frequently appeared exam problems:

1 What is a function? Explain the different types of function based on (Dec 2018)
parameter.
2 Write a C program to find the factorial of a given number using function. (Dec 2018)
3 Write a program in C to find GCD and LCM of two numbers using (Jan 2019)
concept of function.
4 Write a C function isprime (num) that accepts an integer argument and (Jan 2015)
returns 1 if the argument is a prime or 0 otherwise. Write a program that
invokes this function to generate prime numbers between the given
ranges.
5 Write a program in C using functions to swap two numbers. (Jan 2017)
6 What are actual parameters and formal parameters? Illustrate with (Jun 2015)
example.

Departments of CSE & ISE, RNSIT Page | 26


C Programming Lab (18CPL17/27)

[DOCUMENT TITLE]

7 Give the scope and life time of the following (Jan 2019)
(i) External variable (ii) Static variable
(iii) Automatic variable (iv) Register variable

Viva Questions

1 Differentiate between
a) Function definition and function declaration
b) Recursion and iteration
c) Global and local variables
d) Auto and static variables
e) Formal parameters and actual parameters.
2 Compare call by value with call by reference.
3 What is the default value returned by a function?
4 What type of variable can be used for counting the number of times a function is called?
5 Is main a function? How does it differ from other functions? Justify.
6 Trace the above program 7 assuming that the end-user types 3 as input.
7 Which keyword is used to transfer control from a function back to the calling function?
8 How compiler ensures protection if any type mismatch happened between function call
and function definition parameters?
9 Alter the above program to find all prime numbers between given interval using
functions.
10 What does a function declaration a( ); mean?
11 Should return always be the last statement? What is the use of return statement?
12 What is meant by nesting of function? Does C support nesting?

Departments of CSE & ISE, RNSIT Page | 27


C Programming Lab (18CPL17/27)

[DOCUMENT TITLE]

PART-B
MATRIX MULTIPLICATION
8. Develop a program to introduce 2D Array manipulation and implement Matrix
multiplication and ensure the rules of multiplication are checked.

Matrix multiplication is to calculate the product of two matrices (two-dimensional arrays).

Purpose: To demonstrate 2D Array manipulation


Procedure: Program accepts two matrices along with the dimensions of each matrix. Finds the
product if they are compatible otherwise displays error message.
Input: 2D array elements in matrix form.
Expected Output: The product of two matrices or multiplication is not possible message.

8.1 Algorithm
Step 1:[Initialize]
Start
Step 2:[Input the order of both matrices m,n,p,q]
Read m,n,p,q
Step 3:[Input the elements of matrix A]
Read elements of matrix A
Step 4:[Input the elements of matrix B]
Read elements of matrix B
Step 5:[If n is equivalent to p]
IF(n==p) then
GOTO Step6
ELSE
GOTO Step7
ENDIF
Step 6:[Initially set matrix C[i,j] ←0]
[And multiplication on two matrices A,B]
For k=0 to n
C[i,j] ← C[i,j]+A[i, k]*B[k,j]
GOTO Step8
Step 7:[Display message]
Multiplication is not possible
Step 8:[Display result]
Print matrix C
Step 9: Stop

Departments of CSE & ISE, RNSIT Page | 28


C Programming Lab (18CPL17/27)

[DOCUMENT TITLE]

8.2 Program
#include<stdio.h>
int main()
{
//Variable declaration
int a[5][5],b[5][5],c[5][5],m, n, p, q, i, j, k;
printf("Enter the size of first matrix\n");
// m,n indicates rows columns of first matrix respectively
scanf("%d %d", &m, &n);
// p,q indicates rows columns of first matrix respectively
printf("Enter the size of second matrix\n");
scanf("%d %d",&p,&q);
if(n==p)
{
// Reading elements of first matrix
printf("Enter the elements of first matrix\n");
for(i=0;i<m; i++)
{
for(j=0;j<n; j++)
{
scanf("%d", &a[i][j]);
}
}
printf("Enter the elements of the second matrix\n");
// Reading elements of second matrix
for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
{
scanf("%d", &b[i][j]);
}
}
for(i=0;i<m; i++)
{
for(j=0;j<q; j++)
{
c[i][j]=0;
for(k=0;k<n; k++)
{
c[i][j]=c[i][j]+a[i][k]*b[k][j];
//Matrix Multiplication formula
}
}
}

Departments of CSE & ISE, RNSIT Page | 29


C Programming Lab (18CPL17/27)

[DOCUMENT TITLE]

printf("The product of two matrix is\n");


//The resultant matrix
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
printf("%d\t",c[i][j]);
}
printf("\n");
}
}
else
printf("Multiplication is not possible\n");
return 0;
}

8.3 Test Cases

Test No Input Parameters Expected output Obtained output


The product of two
Matrix A Size= 2, 2
matrix The product of two matrix
1 Matrix B Size= 2, 2
Elements= *

Matrix A Size= 2, 3
2 Invalid input Multiplication not possible
Matrix B Size= 2, 2
Matrix A Size= 2, 3 The product of two
Matrix B Size= 3, 2 matrix The product of two matrix
3
Elements = *

The product of two


Matrix A Size= 2, 2
matrix The product of two matrix
4 Matrix B Size= 2, 2
Elements = *

Matrix A Size= 2, 3
5 Give your input and find the result
Matrix B Size=3, 2

Frequently appeared exam problems 1D and 2D arrays

1 Write a C program to read N integers into an array A and to find the (i) sum
of odd numbers, (ii) sum of even numbers, (iii) average of all numbers. (Jun 2015)
Output the results computed with appropriate headings
2 Write a C program to search an element using linear and binary techniques (Jun 2019)
3 Write a C program for [consider integer data] (i) Bubble sort (ii) Linear (Jan 2019)
search
4 Write a C program to read N numbers into an array & perform linear search (Dec 2016)

Departments of CSE & ISE, RNSIT Page | 30


C Programming Lab (18CPL17/27)

[DOCUMENT TITLE]

5 Write a C program to find the transpose of a given matrix (Jan 2019)


6 Define array. Write syntax for and declaring and initializing 1D and 2D (Jan 2019)
array with example.
7 Write a C program to find the transpose of a given matrix (Jan 2019)

Viva Questions
1 What do you understand by row-major and column-major order memory allocation wrt
2D array?
2 How to initialize two dimensional arrays?
3 How to pass a two dimensional array to function as parameter?
4 Illustrate the memory allocation of 2D array with an example.
5 How do we access the value stored in 2D array?
6 Write a code snippet to access the principal diagonal elements of a matrix.
7 What is the output of C Program with strings?
int main()
{
char ary[]="RNSIT CSE";
printf("%s",ary);
return 0;
}
8 What will be the output of the C program?
#include<stdio.h>
int main()
{
int i = 0;
printf("Hello");
char s[4] = {'\b', '\t', '\r', '\n'};
for(i = 0;i<4;i++){
printf("%c", s[i]);
}
return 0;
}
9 What will be the output of the C program?
#include<stdio.h>
int main()
{
int i = 0;
char s[4] = {'\0', '\0', '\0', '\0'};
for(i = 0;i<4;i++)
{
printf("%c", s[i]);
}
return 0;
}
10 Illustrate how addresses are computed for each memory locations of the 2D array
considering an example. Consider base address of 2D array is 2000.

Departments of CSE & ISE, RNSIT Page | 31


C Programming Lab (18CPL17/27)

[DOCUMENT TITLE]

SINE SERIES
9. Develop a Program to compute sin(x) using Taylor series approximation .Compare your
result with the built- in Library function. Print both the results with appropriate messages.

A Taylor series is a representation of a function as an infinite sum of terms that are calculated
from the values of the function‟s derivatives at a single point.

This program calculates the sine of an angle using Taylor Series Approximation using the
below formula

Purpose: To evaluate sin(x) using Taylor series.


Procedure: The program reads the angle x in degrees and converts it to radians using the
formula x* (π/180). The code iterates until the desired accuracy (four decimal points) is
achieved, to get the final result.
Input: Read the angle in degree.
Expected Output: result after evaluating the sin(x) without using library function.

9.1 Algorithm
Step1: [Initialize] Start
Step2: [Input angle in degree]
Read degree x
Step3: [Initialization & Radians conversion]
nume = x;
deno = 1;
i=2;
x = x * (π /180);
Step4: [Compute sin value]
Repeat While (term>=0.00001)
term = nume/deno;
nume = -nume*x*x;
deno = deno*i*(i+1);
sum=sum+term;
i=i+2;
Step5: [Display result]
Print sin(x) without using library function
Print sin(x) with using library function
Step6: [Stop]

Departments of CSE & ISE, RNSIT Page | 32


C Programming Lab (18CPL17/27)

[DOCUMENT TITLE]

9.2 Program
#include<stdio.h>
#include<math.h>
#define PI 3.142

int main()
{
int i, degree;
float x, sum=0,term,nume,deno;
printf("Enter the angle in degree\n");
scanf("%d",&degree);
x = degree * (PI/180);//converting degree into radian
nume = x;
deno = 1;
i=2;
do
{ //calculating the sine value.
term = nume/deno;
nume = -nume*x*x;
deno = deno*i*(i+1);
sum=sum+term;
i=i+2;
} // Accurate to 4 decimal point digits
while (fabs(term) >= 0.00001);
printf("The sine of %d is %.3f\n", degree, sum);
printf("The sine function of %d is %.3f", degree,
sin(x));
return 0;
}

9.3 Test Cases


Test Input
Expected output Obtained output
No Parameters
The sine of 0 is= 0.000
1 Degree = 0 The sine of 0 is = 0
Using inbuilt function sin(0)= 0.000
The sine of 30 is= 0.500
2 Degree = 30 The sine of 30=0.500
Using inbuilt function sin(30)= 0.500
The sine of 60 is= 0.866
3 Degree = 60 The sine of 60= 0.866
Using inbuilt function sin(60)= 0.866

The sine of -10 is= - 0.174


4 Degree = -10 The sine of -10= -0.17
Using inbuilt function sin(-10)= -0.174

5 Degree = 10
6 Degree = 90

Departments of CSE & ISE, RNSIT Page | 33


C Programming Lab (18CPL17/27)

[DOCUMENT TITLE]

Frequently appeared exam problems related to loops

1 Write a program to find the sum of N numbers using for loop. (Jan 2019)
2 Write a C program to find the factorial of a number using does-while, where (Jun 16)
the number n is entered by user.
3 List the differences between while loop and do-while loop. Write a C ( Jun 16)
program to find sum of Natural numbers from 1 to N using for loop.
4 Write a C program to find the factorial of a number using does-while, where (Jun 16)
the number n is entered by user.
5 Write a C program to find GCD of two numbers using ternary operator and (Model QP)
for loop

Viva Questions

1 What is pre-processor directive?


2 What is difference between const and #define.
3 Write the output of the following program.
#define ABC 20
#define XYZ 10
#define XXX ABC - XYZ
void main()
{
int a;
a = XXX * 10;
printf("%d ", a);
}
4 What do you mean by macro?
5 Trace the above sin(x) using Taylor series program by accepting degree 50
6 In #include directives, some file names are enclosed in angle brackets while others are
enclosed in double quotation marks. Why?

Other alternative:
This program can be executed by reading number of terms.

Departments of CSE & ISE, RNSIT Page | 34


C Programming Lab (18CPL17/27)

[DOCUMENT TITLE]

STRING MANIPULATION FUNCTIONS


10. Write functions to implement string operations such as compare, concatenate, string
length. Convince the parameter passing techniques.

Strings are defined as an array of characters and terminated with a special character '\0'. String
is declared as a one-dimensional array as given below:
char str[]=”RNSIT”
In built C functions in string.h are:
i. strlen (str ): This function counts and returns number of characters in a string
ii. strcmp (str1,str2 ): Compares two string until a character in either string is NULL or
the characters are unequal. Returns zero if they are equal or the numeric difference
between the first nonmatching characters in the strings
iii. strcat (dst,src ): This function will append a copy of the source string to the end of
destination string.

Purpose: To demonstrate string parameter passing to a function and implementation of built in


string manipulation functions.
Procedure: Find the length of the input strings. Compare both the strings to check whether
they are equal or not and then display the concatenated string.
Input: Two strings s1 and s2
Expected Output: Print whether the two strings are equal or not, concatenated string and
length of the strings.

10.1 Algorithm
Step 1: Start
Step 2:[Input Strings]
Read two strings s1, s2
Step 3:[Find the length of strings]
i=0
while(s[i]!=‟\0‟)
i++
return i
Step 4:[Compare both the strings]
j ←0
while(s1[j] == s2[j])
{
IF(s1[j] == '\0' || s2[j] == '\0') break;
Else count++;
}
IF(s1[count] == '\0' && s2[count] == '\0')return 0;
Else return -1;
Step 5:[Print Strings are equal or not]
Step 6:[Concatenate both the strings s1 and s2]

Departments of CSE & ISE, RNSIT Page | 35


C Programming Lab (18CPL17/27)

[DOCUMENT TITLE]

int i, j;
i ←strlen(s1);
for (j = 0; s2[j] != '\0'; i++, j++)
s1[i] = s2[j];

s1[i] = '\0';
Step 7:[Print concatenated string]
Step 8:Stop

10.2 Program
#include<stdio.h>

int Length(char s1[]);


int compare(char s1[], char s2[]);
void concat(char s1[], char s2[]);

int main()
{
char s1[200], s2[100]; // Declaration of variable
int len,res,count;
printf("\n Enter the String s1: ");
gets(s1);
printf("\n Enter the String s2 :");
gets(s2);
len = Length(s1);
printf("\n Length of the String s1 is : %d", len);
len = Length(s2);
printf("\n Length of the String s2 is : %d", len);
res = compare(s1, s2);
if(res == 0)
printf("\n Both the Strings are Equal \n");
else
printf("\n The Strings are not Equivalent \n");
concat(s1, s2);
printf("\n Concatenated string is :%s", s1);
getch();
return(0);
}

int Length(char s1)// Function definition


{
int len = 0;
while (s1[len] != '\0') //find length of the string

Departments of CSE & ISE, RNSIT Page | 36


C Programming Lab (18CPL17/27)

[DOCUMENT TITLE]

len++;
return (len);
}

//Function to compare two strings


int compare(char s1[], char s2[])
{
int count = 0;
while(s1[count] == s2[count])
{
if(s1[count] == '\0' || s2[count] == '\0') break;
else count++;
}
if(s1[count] == '\0' && s2[count] == '\0') return 0;
else return -1;
}

//Function to concatenate two strings


void concat(char s1[], char s2[])
{
int i, j;
i = strlen(s1);
for (j = 0; s2[j] != '\0'; i++, j++)
s1[i] = s2[j]; //copy content of s2 to s1
s1[i] = '\0'; // Assign null character at the end
of s1
}

10.3 Test cases


Test Input Expected output Obtained output
no Parameters

1 S1 = RNS Length of the string s1 is : 3 Length of the string s1 is : 3


S2 = CSE Length of the string s2 is : 3 Length of the string s2 is : 3
Strings are not equivalent Strings are not equivalent
Concatenated string is : RNSCSE Concatenated string is :
RNSCSE
3 S1 = CSE Length of the string s1 is : 3 Length of the string s1 is : 3
S2 = CSE Length of the string s2 is : 3 Length of the string s2 is : 3
Both the strings are equal Both the strings are equal
Concatenated string is : CSECSE Concatenated string is : CSECSE
4. S1 =
COMPUTER
S2 =
SCIENCE

Departments of CSE & ISE, RNSIT Page | 37


C Programming Lab (18CPL17/27)

[DOCUMENT TITLE]

Frequently appeared exam problems related to functions

1 Discuss different methods of passing parameters to functions with an (July 2009)


example for each.
2 What is a function? Write a C program to find the cube of a number using (Jan 2016)
function.
3 Write a C program to sort the elements by passing array as function (Jan 2016)
parameter
4 Explain any two string manipulation functions (Jan 2018)
5 Write a C program to find the sum of array elements by passing array as a (Jan 2018)
function
6 How would you explain categories of user defined function? (Jan 2020)

Viva Questions

1 What is a string? Explain about string delimiter?


2 Compare character vs. string and string vs. character constants?
3 List and illustrate the working of string manipulation functions with examples.
4 Why address operator is not used while reading a string?
5 Differentiate between gets() and scanf().
6 On what basis string comparison is done using the function strcmp( ).
7 What does „\0‟ represents? What is the size of 0 and \0?
8 Mention the purpose of getchar(), putchar(), getche(), getch(), putch() functions.
Compare printf() with putchar().
9 Declare a variable to store names of n-students.
10 Can a string variable name be used on the left side of the assignment operator?
11 Is it possible to manipulate strings using operators?
12 Mention the limitations of getchar() and scanf() functions for reading strings.
13 What will be the ouput of the following statement?
printf(“%d”, strcmp(“push”, “pull”));
14 Passing strings to functions used pass by address technique. Justify this statement

Departments of CSE & ISE, RNSIT Page | 38


C Programming Lab (18CPL17/27)

[DOCUMENT TITLE]

BUBBLE SORT
11. Develop a program to sort the given set of N numbers using Bubble sort.

Arranging the data in ascending or descending order is known as sorting. Different sorting
techniques are: selection sort, bubble sort, insertion sort, merge sort, quick sort. The program
given below demonstrates bubble sort. Bubble sort is also known as sinking sort. This
algorithm compares each pair of adjacent items and swaps them if they are in the wrong order,
and this same process goes on until no swaps are needed, and array is sorted completely.

Purpose: To demonstrate nested for loop.


Procedure: To read „n‟ elements of an array. While iterating, compare each pair of adjacent
items in every pass. If the former value is greater than the latter one, their positions are
swapped. Over a number of passes, at most equal to the number of elements in the list, all of
the values drift into their correct positions. Then print sorted array elements.
Input: Number of Elements – n and an array of unsorted elements – a
Expected Output: An array of sorted elements – a

11.1 Algorithm
Step 1:Start
Step 2:[Input number of elements]
Read n
Step 3:[Input n array elements ]
Read a[n]
Step 4:[Initialize i]
i← 0 for number of passes.
Step 5:[Initialize j]
j←0 Repeat step 6 if a[j]>a[j+1]
Step 6:[Swap elements]
IF( a[j]>a[j+1])
temp ← a[j];
a[j] ← a[j+1];
a[j+1] ←temp;
END IF
Step 7:[Print the sorted array elements]
Step 8: Stop

Departments of CSE & ISE, RNSIT Page | 39


C Programming Lab (18CPL17/27)

[DOCUMENT TITLE]

11.2 Program
#include<stdio.h>
int main()
{
int n,i,j,a[10],temp; // Declaration of variable
printf("Enter number of array elements : \n");
scanf("%d",&n);
printf("Enter the array elements \n");
for(i = 0 ; i < n ; i++) scanf("%d",&a[i]);
printf("The original elements are : \n");
for(i = 0 ; i < n ; i++)
printf("%d \t",a[i]);
for(i= 0 ; i < n-1 ; i++) // Number of Passes
{
for(j= 0 ; j< n-i-1; j++) // Comparisons
if(a[j] > a[j+1]) // Swap elements
{
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
// Print sorted list
printf("\n The Sorted elements are : \n");
for(i = 0 ; i < n ; i++) printf("%d \t ",a[i]);
return 0;
}

11.3 Test Cases


Test No Input Parameters Expected output Obtained output
N=5 Sorted elements are: A ={23, 4, 6, 12, 40}
1
A[5]={23, 4, 6,12, 40} A[5]={4, 6, 12, 23, 40} Sorted A ={4, 6, 12, 23, 40}

N=4 Sorted elements are: A ={67, 5, 0, 34}


2
A[4]={67, 5, 0, 34} A[4]={0, 5, 34, 67} Sorted A={0, 5, 34 ,67}
N=4 Sorted elements are: A ={-3, -9, 12, 6}
3
A[4]={-3, -9, 12, 6} A[4]={-9, -3, 6, 12} Sorted A={-9, -3, 6, 12}
N=5 Sorted elements are: A ={12, 23, 6, 54, 6}
4
A[5]={12, 23, 6,54, 6} A[5]={6, 6, 12, 23, 54} Sorted A={6, 6, 12, 23, 54}
Test for the following cases & record your observations
5 N=8
6 N=15

Departments of CSE & ISE, RNSIT Page | 40


C Programming Lab (18CPL17/27)

[DOCUMENT TITLE]

Frequently appeared exam problems related to loops

1 Write a C program to sort elements of array using bubble sort. (Jan 2018)
2 Print the following series (Jan 2018)
1
1 2
1 2 3
1 2 3 4

Viva Questions

1 Mention the working of bubble sort algorithm.


2 List the different types of sorting techniques.
3 The given array is arr = {1, 2, 4, 3}. If Bubble sort is used to sort the array elements.
How many iteration are needed to sort the array?
4 What is nested for loop? Illustrate the control transfer in nested for loop.
5 How can the efficiency of bubble sort algorithm be determined?
6 Is bubble sort an efficient sorting technique? Justify your answer.
7 How to measure the efficiency of an algorithm/ program?
8 Trace the bubble sort program taking an array as an example.
9 What happens when an array with specified size is assigned with values
i) Fewer than the specified size; and
ii) More than the specified size.
10 A char and float type variable cannot be used as subscript in an array- True/False
11 A for loop without test condition is known as loop.
…………………..

Departments of CSE & ISE, RNSIT Page | 41


C Programming Lab (18CPL17/27)

[DOCUMENT TITLE]

SQUARE ROOT
12. Develop a program to find the square root of a given number N and execute for all
possible inputs with appropriate messages. Note: Don’t use library function sqrt(n).

A square root of a number is a value that, when multiplied by itself, gives the number.
Example: 4 × 4 = 16, so a square root of 16 is 4. Note that (−4) × (−4) = 16 too, so −4 is also a
square root of 16. The symbol is √ which always means the positive square root.
Example: √36 = 6 (because 6 x 6 = 36)

Purpose: To demonstrate the working of while loop.


Procedure: Input a number; reduce it by half to proceed further. The code inside the loop
iterates as long as the value (x*x – number) is greater than the accuracy (accuracy is set
according to the requirement).
Input: Read a Number
Output: Square root of the given number

12.1 Algorithm
Step 1: Start
Step 2:[Initialize]
Accuracy ← 0.001
Step 3:[Input a number]
Read N
Step 4:[Reduce number N by half]
x ← N/2
Step 4:[Repeat loop until square root of N is found]
while((x*x - number) > ACCURACY)
x ←(x + number/x )/2;
Step 5:[Print square root]
Step 6:Stop

12.2 Program
#include <stdio.h>
#define ACCURACY 0.001
// tolerance : you can set by yourself according to requirement

int main() // Uses Babylonian method


{
float number, x, square_root;
printf("Enter a number to find square root of it:\n");
scanf("%f",&number);
x=number/2; // initializing
//loop runs until the square root is found

Departments of CSE & ISE, RNSIT Page | 42


C Programming Lab (18CPL17/27)

[DOCUMENT TITLE]

while((x*x - number) > ACCURACY)


x = (x+ number/x )/2; // updating the number
square_root = x;
printf("square root of %.2f = %.4f",number,square_root);
getch();
return 0;
}

12.3 Test cases


Test Input
Expected output Obtained output
No Parameters
Square root is 7.000
1 N=49 Square root is 7
Using built in function Sqrt() is 7.00
Square root is 5.477
2 N=30 Square root is 5.477
Using built in function Sqrt() is 5.48
Square root is 7.106
3 N=50.5 Square root is 7.106
Using built in function Sqrt() is 7.11
4 N= -4 No square root to a negative number No square root to a negative number
5 N=0 Square root is 0 Square root = 0

Test for the following cases & record your observations

6 N =2
7 N = 16.25

Frequently appeared exam problems related to loops

1 Explain syntax of do-while loop (Jan 2016)


2 Write a C program to find factorial of a number using do-while loop (Jan 2016)
3 Explain syntax of while statement. Write a program to find a given number is (Jan 2018)
palindrome or not using while loop.
4 Explain break and continue statement with respect to while, do-while and for (Jan 2018)
loop
5 Differentiate between while and do-while loop (July 2018)

Viva Questions

1 Trace the above program considering the input numbers: 4, 36,174 and 200.
2 What is typecasting? Explain with an example.
3 Mention the differences between continue and break statement.
4 In the above given solution, why we have to reduce the number by half?

Alternative method
Find square root of a given number using Brute-Force method

Departments of CSE & ISE, RNSIT Page | 43


C Programming Lab (18CPL17/27)

[DOCUMENT TITLE]

STRUCTURES
13. Implement structures to read, write, and compute average- marks and the students
scoring above and below the average marks for a class of N students.

A structure is a user defined data type in C/C++. A structure is a mechanism for packing data of
different types. The struct keyword is used to declare a structure. To access any member of a
structure, we use the member access operator (.)

Purpose: To demonstrate use of structures.


Procedure: This program inputs the student details and computes average- marks. The
students scoring above and below the average marks will also be displayed.
Input: marks of N students
Expected Output: average- marks and the students scoring above and below the average
marks for a class of N students.

13.1 Algorithm
Step 1: [Initialize] Start
Step 2: [Input the number of students]
Read n
Step 3: [Input USN, name, marks of n students]
for i-0 to n-1 in step of 1
Read details of n-students
End for
Step 4: [Display USN, name, marks of n students]
for i-0 to n-1 in step of 1
display details of n-students
End for
Step 5: [Compute average ]
for i-0 to n-1 in step of 1
sum=sum+s[i].marks;
End for
average=sum/n;
Step 6: [Compute above average and below average]
for i-0 to n-1 in step of 1
if(s[i].marks>=average)
countav++;
else
countbv++;
End for
[print above average and below average]
Step 7: Stop

Departments of CSE & ISE, RNSIT Page | 44


C Programming Lab (18CPL17/27)

[DOCUMENT TITLE]

13.2 Program
#include <stdio.h>
struct student
{
char usn[50]; // structure members
char name[50];
int marks;
} s[10]; //structure variable declaration
void main()
{ // Declaring and initializing variables
int i,n,countav=0,countbv=0;
float sum=0,average;
printf("Enter number of Students\n");
scanf("%d",&n);
printf("Enter information of students:\n");
for(i=0; i<n;i++)
{
printf("Enter USN: ");
scanf("%s",s[i].usn); //Read USN
printf("Enter name: ");
scanf("%s",s[i].name); //Read name
printf("Enter marks: ");
scanf("%d",&s[i].marks); //Read marks
printf("\n");
}
printf("Displaying Inform
// displaying information
for(i=0; i<n; i++)
{
printf("\nUSN: %s\n",s[i].usn);
printf("Name: ");
puts(s[i].name);
printf("Marks: %d",s[i].marks);
printf("\n");
}
for(i=0;i<n;i++)
sum=sum+s[i].marks; //calculate sum
average=sum/n; //calculate average
printf("\nAverage marks: %f",average);
countav=0;
countbv=0;
for(i=0;i<n;i++)
{
if(s[i].marks>=average) countav++; //compute above average
else countbv++; //compute below average
}
printf("\nTotal No of students above average= %d",countav);
printf("\nTotal No of students below average= %d",countbv);
}

Departments of CSE & ISE, RNSIT Page | 45


C Programming Lab (18CPL17/27)

[DOCUMENT TITLE]

13.3 Test Cases


Test
Input Parameters Expected output Obtained output
No
1 N=3, Enter the student details Average marks:520 Average marks:520
USN Name Marks Total No of students Total No of students
above average=1 above average=1
S[0] 1RN18CS001 Chetan 500 Total No of students Total No of students
below average=2 below average=2
S[1] 1RN18CS002 Darshan 510

S[2] 1RN18CS003 Pallavi 550


2 N=2, Enter the student details Average marks:540 Average marks:540
USN Name Marks Total No of students Total No of students
above average=1 above average=1
S[0] 1RN18IS001 Rajesh 520 Total No of students Total No of students
below average=1 below average=1
S[1] 1RN18IS002 Darshan 560

Test for the following cases & record your observations


N=2, Enter the student details
USN Name Marks

3 S[0] 1RN18IS009 Rama 520

S[1] 1RN18IS006 Sita 560

Frequently appeared exam problems

1 What is structure? Explain C syntax of structure declaration with example (Jan2017)


2 Explain structure within a structure with an example (July2018)
3 Write a C program to pass structure variable as function argument (Jan2019)
4 Explain with example how to create a structure using typedef. (Jan2018)

Viva Questions

1 List the derived data types available in C programming.


2 Define structure and union. When to use structures and unions? List their advantages
and disadvantages.
3 What is the advantage of using structure over an array?
4 How to access the members of structure? How does the memory allotted for structure?
5 Why do we need structure data type? What is meant by structure members?
6 What are the difference between structure and union?
7 How do you access the starting address of a structure variable? What is advantage of
using the typedef keyword in a structure variable?
8 Differentiate between structure declaration and definition.

Departments of CSE & ISE, RNSIT Page | 46


C Programming Lab (18CPL17/27)

[DOCUMENT TITLE]

USE OF POINTERS
14. Develop a program using pointers to compute the sum, mean and standard deviation of
all elements stored in an array of n real numbers.

The pointer in C language is a variable which stores the address of another variable. This
variable can be of type int, char, array, function, or any other pointer. A pointer can be
incremented/ decremented to point to the next/ previous memory location. An integer value can
be added or subtracted from a pointer variable. But two pointer variables cannot be added and
multiplied by a constant.

Purpose: To demonstrate use of pointers.


Procedure: This program makes use of pointers to compute the sum, mean and standard
deviation of all elements stored in an array.
Input: An array containing „n‟ elements
Expected Output: sum, mean and standard deviation of array elements

14.1 Algorithm:
Step 1: Start
Step 2: [Input the elements]
Read n, a[i]
Step 3: [Initialization]
sum=0, sumstd=0
Step 4:[Compute sum, mean, standard deviation]
Ptr=a
For i = 0 to n
sum=sum+*ptr
ptr++
End For
mean=sum/n
ptr=a
For i= 0 to n
sumstd=sumstd+pow((*ptr-mean),2)
ptr++
End For
Step 5:std=sqrt(sumstd/n)
Step 6:[Output sum, mean and standard deviation]
Print sum, mean, std
Step 7:[ Finished ]
Stop

Departments of CSE & ISE, RNSIT Page | 47


C Programming Lab (18CPL17/27)

[DOCUMENT TITLE]

14.2 Program
#include<stdio.h>
#include<math.h>

int main()
{ float a[10], *ptr, mean, std, sum=0, sumstd=0;
Int n,i;//declaration of variables
printf("Enter the number of elements\n");
scanf("%d",&n);
printf("Enter the array elements\n");
for(i=0;i<n;i++)
{
scanf("%f",&a[i]);
}
ptr=a;
for(i=0;i<n;i++)
{
sum=sum+ *ptr;
ptr++;
}
mean=sum/n; // calculate mean
ptr=a;
for(i=0;i<n;i++)
{
sumstd=sumstd + pow((*ptr - mean),2); ptr++;
}
std= sqrt(sumstd/n); // calculate standard deviation
printf("Sum=%.3f\t",sum);
printf("Mean=%.3f\t",mean);
printf("Standard deviation=%.3f\t",std);
return 0;
}

14.3 Test Cases


Test No Input Parameters Expected output Obtained output
N=5 Sum=28 Mean=5.6 Sum=28.000 Mean=5.600
1
Array elements = {1, 5, 9, 6, 7} Standard deviation=2.09 Standard deviation=2.098
N=4 Sum=10.68 Mean=2.67 Sum=10.680 Mean=2.670
2
Array elements = {2.3, 1.1, 4.5 ,2.78} Standard deviation=0.863 Standard deviation=0.863
Test for the following cases & record your observations
N=5
3
Array elements = {2, 3, 4, 8, 10}
N=4
4
Array elements = {2.4, 5.6, 2.0, 4.12}

Departments of CSE & ISE, RNSIT Page | 48


C Programming Lab (18CPL17/27)

[DOCUMENT TITLE]

Frequently appeared exam problems related to pointers

1 What is a pointer? Explain how the pointer variable declared and initialized. (Jan2018)
2 What is pointer? give the advantages and disadvantages of pointer data type (July2017)
3 Write a c program to swap the contents of two variables by passing address (July2018)
to the function.

Viva Questions

1 What is the difference between address and pointer? How is a pointer represented in C?
2 How a pointer variable is initialized? Is it possible to initialize a pointer variable with
NULL?
3 What is * and & in pointer concept.
4 What are the advantages and disadvantages of using pointer?
5 Give the difference between static allocation and dynamic allocation of memory space.
6 What is the effect of the ++ and -- operators on pointer variable
7 Explain the pointers to arrays concept.
8 What is void pointer? What is the specialty?
9 What is Dangling pointer?
10 What is pointer to a pointer?
11 Can a function return pointer to an array?
12 Why are pointers to array enclosed in parenthesis?
13 Can you represent a[3] through a pointer declaration?
14 How are parameters passed to functions when the actual value of variable has to be changed?
15 Between indirection operation and indexing which has higher priority?
16 Using a pointer, write a single line code that copies a string „s1‟ to string „s2‟.
17 When we pass parameter by address, the corresponding formal parameters must be a pointer
variable- True/False.
18 Distinguish between (*m)[5] and *m[5].
19 Given the following declarations :
int x = 10, y = 10; int *p1 = &x, *p2 = &y;
What is the value of each of the following expressions?
a. (*p1)++
b. - - (*p2)
c. *p1 + (*p2) - -

20 Assuming name as an array of 15 character length, what is the difference between the
following two expressions?
a) name + 10
b) *(name + 10)

Departments of CSE & ISE, RNSIT Page | 49


C Programming Lab (18CPL17/27)

[DOCUMENT TITLE]

BINARY TO DECIMAL CONVERSION


15. Implement Recursive functions for Binary to Decimal Conversion.

The process in which a function calls itself directly or indirectly is called recursion and the
corresponding function is called as recursive function.

Purpose: To demonstrate the concept of recursive function.


Procedure: Extract the Least Significant Bit (LSB) of the binary number in each iteration until it
becomes zero and multiply with proper base (Power of 2). The partial result should be added to
get the equivalent decimal number. For example: consider the binary number 111, its
corresponding decimal number is calculated as below
dec_value = 1*(2^2) + 1*(2^1) + 1*(2^0) = 7
Input: binary number.
Expected Output: Decimal equivalent of the given input

15.1 Algorithm
Step 1: [Initialize]
Start
Step 2: [Input the binary number]
Read bin
Step 3: [call the binary to decimal recursive function]
dec = convert(bin)
Step 4: [display the result which gives decimal equivalent ]
Print dec
Step 5:[Finished]
Stop

15.2 Program
#include <stdio.h>
int convert(int);
int main()
{
int dec, bin; //variable declaration
printf("Enter a binary number: "); scanf("%d", &bin);
dec = convert(bin); //recursive function
printf("The decimal equivalent of %d is %d.\n", bin, dec);
return 0;
}
int convert(int bin) //Function to convert binary to decimal
{
if (bin == 0) return 0;
else return (bin % 10 + 2 * convert(bin / 10));
}

Departments of CSE & ISE, RNSIT Page | 50


C Programming Lab (18CPL17/27)

[DOCUMENT TITLE]

15.3 Test Cases


Test No Input Parameters Expected output Obtained output

1 The decimal equivalent


Binary Number=110 Decimal Number=6
of 110 is 6
2 The decimal equivalent
Binary Number=010 Decimal Number=2 of 010 is 2

3 The decimal equivalent


Binary Number=011 Decimal Number=3 of 011 is 3

Test for the following cases & record your observations


4 Binary Number=101

Frequently appeared exam problems related to recursion

1 Write a C program for evaluating the binomial coefficients using a function (June 2019)
factorial(n)
2 Explain recursion. and write a program to find nth term of Fibonacci series (Jan 2019)
3 Write a program to find GCD of two numbers using recursion. (June2018)
4 Write a program using recursive to generate the Fibonacci series. (June2017)
5 Write a program to find the sum of all numbers from 1 to N using recursion.) (Jan2018)
6 Recursive solution for Linear and Binary Search. (Jan2017)

Viva Questions

1 Define the term recursion.


2 What are the advantages and disadvantages of recursive function?
3 Give the general syntax of a recursive function.
4 What is the necessity of base case in recursion?
5 When the return statement will be executed in recursion?
6 Which data structure can be used to implement recursion? Justify your answer.
7 List the application of recursion.
8 Differentiate between iteration and recursion.
9 What is the output of below program?
void main( )
{
printf(“ how do you stop execution?”);
main();
}

Departments of CSE & ISE, RNSIT Page | 51


C Programming Lab (18CPL17/27)

[DOCUMENT TITLE]

Appendix-A
This section lists the additional exercise problems from each module which should be designed,
implemented and executed by all students in each laboratory session.

Module 1- Overview of C

Write a C program to:


1 Print HELLO WORLD on the output screen.
2 Display size of the different data types.
3 Print ASCII value of a character.
4 Read the character in upper case and print it in lower case.
5 Convert degree Celsius to degree Fahrenheit and vice versa.
6 Compute simple interest by accepting appropriate inputs from the user.
7 Obtain the radius of a circle and compute its area and perimeter.
8 Swap two integer numbers using third variable.
9 Swap two integer numbers without using third variable.
10 Obtain the length and width of a rectangle from the user and compute its area and
perimeter.
11 Find the area of triangle given all the 3 sides of it.
12 Read a floating point number and display the right-most digit of the integral part of the
number.
13 Modify the above program to display the two right-most digits of the integral part of the
number.
14 Compute addition, subtraction, multiplication of 3 integer numbers.
15 Compute gross salary of an employee.
16 Print the average of two numbers and also their deviation.
17 Demonstrate the use of relational, bitwise, shift and logical operators.
18 Convert a floating point number into corresponding integer.
19 Read the values of x and y and print the results of the following expressions in one line:
a) b) c) (x + y) (x - y)
20 Distance between two points (x1, y1) and (x2, y2) is governed by the formula
D2 = (x2 - x1)2 + (y2 - y1)2
Compute D given the coordinate points.

Module 2- Branching and Looping

Write a C program to:


21 Print the greatest number among the given three numbers.
22 Check whether number is positive or negative.
23 Input any alphabet and check whether it is vowel or consonant.
24 Input any character and check whether it is alphabet, special character or digit.
25 Check whether number is odd or even
26 Check whether input year is leap year or not.
27 Input age of a person and check whether he is eligible for voting or not.
28 Check whether a character is an uppercase or lowercase alphabet.

Departments of CSE & ISE, RNSIT Page | 52


C Programming Lab (18CPL17/27)

[DOCUMENT TITLE]

29 Find radius, circumference and volume of cylinder using switch case statement.
30 Check whether an alphabet is a vowel or consonant using switch case statement.
31 Read 10 numbers from keyboard and find their sum and average.
32 Display the n terms of odd natural numbers and their sum.
33 Display the Floyd‟s triangle.
34 Display the below patterns

a) 1 b) * c) 1 d) 12345
01 ** 22 1234
101 *** 333 123
0101 **** 4444 12
10101 ***** 55555 1

35 Check whether the given number is Armstrong number or not (A number is an


Armstrong number if number is equal to the sum of the cubes of its digits like 0,
1,153,370,371 etc.).
36 Display the n terms of even natural numbers and their sum.
37 Find the sum of natural numbers.
38 Display the first n- Fibonacci numbers.
39 Find the sum of the series 1 + 22/2 + 32/3 + 42/4 - - - - - + n2/n.
40 Find LCM and GCD of two numbers
41 Read a four digit integer and print the sum of its digits.
42 Display multiplication table of given number.
43 Find the factorial of a given number.
44 Determine and print the sum of the following harmonic series for a given value of n
1 + 1/2 + 1/3 + - - - - - + 1/n.
45 Compute the value of Euler‟s number e, that is base of natural logarithms using the
following formula:
e=1 + 1/1! + 1/2! + ………. + 1/n!
Use a suitable loop construct. The loop must terminate when the difference between two
successive values of e is less than 0.00001.
46 Find the sum of all integers greater than 100 and less than 200 that are divisible by 7.

Module 3-Arrays and Strings

Write a C program to:


47 Read and print elements of the 1D array.
48 Insert an element at desired or specific position in an array.
49 Remove duplicates items in an array.
50 Read n array elements and print only negative numbers.
51 Find sum of all array elements.
52 Find a maximum and minimum element in an array.
53 Display the second largest and second smallest element in an array of n-elements.
54 Count the total number of even and odd elements in an array.
55 Copy all elements from an array to another array.
56 Count frequency of each element in an array.
57 Merge two arrays to the third array.
58 Find reverse of an array.
59 Search an element in an array using linear search technique.

Departments of CSE & ISE, RNSIT Page | 53


C Programming Lab (18CPL17/27)

[DOCUMENT TITLE]

60 Accept array inputs from user, sort them using selection sort method and determine
median.
61 Find number of characters in string without using string built in function.
62 Copy one string to another string without using string built in function.
63 Read two strings and print the concatenated string without using string built in function.
64 Read two strings and compare them, print appropriate message.
65 Read two strings and print the concatenated string without using string built in function.
66 Read a string in lowercase, convert to uppercase and print the string.
67 Read a string in uppercase convert to lowercase and print the string.
68 Count total number of vowels and consonants in a string.
69 Count total number of words in a string.
70 Calculate SGPA and CGPA of n-students by reading marks in all subjects.
71 Read your name and output the list of ASCII codes, which represent your name.
72 Read a sentence and count all occurrences of a particular word.
73 Read a string and rewrite it in alphabetical order. For example, the word STRING
should be displayed as GINRST.
74 Read a sentence and replace a particular word by another word.
75 Read a string and determine it is palindrome or not.
76 Read two matrices and perform addition and subtraction of those two matrices.
77 Perform scalar matrix multiplication.
78 Sum of the principal diagonal elements of a matrix. (Find trace of a matrix)
79 Find the sum of each row and column of a matrix.
80 Find the sum of upper and lower triangular matrix.
81 Print transpose of a matrix.
82 Find determinant of a matrix.

Module 4-User defined functions and Recursion

Write a C program to:


83 Print Cube of any number using the function.
84 Find diameter, circumference and area of a circle using functions.
85 Maximum and minimum between two numbers using functions.
86 Check whether a number is even or odd using functions.
87 Check whether a number is prime, Armstrong or perfect number using functions.
88 Calculate standard deviation of an of array n elements using functions.
89 Read marks of n-students, sort them using functions.
90 Swap two values using call by reference and call by value method.
91 Write a function that will round a floating point number to an indicated decimal place.
For ex: 17.457 would yield the value 17.46 when it is rounded off to two decimal place.
92 Find the power of any number using recursion.
93 Print all natural numbers between 1 to n using recursion.
94 Find reverse of any number using recursion.
95 Generate and print the first n- Fibonacci numbers using recursion.
96 Perform calculator operations using functions
97 Write a function that can be called to find the largest element of m by n matrix.
98 Function to read m by n matrix, find the column averages and row averages and print
the entire matrix with averages shown in respective rows and columns. Implement this
program using separate functions for each operation.
99 Invoke a function find( ) to perform the following tasks :

Departments of CSE & ISE, RNSIT Page | 54


C Programming Lab (18CPL17/27)

[DOCUMENT TITLE]

a) Receives a character array and a single character


b) Returns 1 if the specified character is found in the array, 0 otherwise.
100 Design a function locate ( ) that takes two strings s1 and s2 and one integer value m as
parameters. The function inserts the string s2 into s1 immediately after the index m.

Module 5-Structures and pointers

Write a C program to:


101 Add two numbers using pointers.
102 Compute the sum of all elements stored in an array using pointers.
103 Input and print array elements using a pointer.
104 Copy one array to another using pointer.
105 Swap two arrays using pointers.
106 Implement a function to reverse the elements of the given array using pointers.
107 Return multiple values from a function using pointers.
108 Find reverse of a string using pointers.
109 Implement a function using pointers to add two matrices and to return the resultant
matrix to the calling function.
110 Using pointers, write a function that receives a character string and a character as
argument and deletes all occurrences of this character in the string. The function should
return the corrected string with no holes.
111 Implement a function (using pointer parameter) that compares two integer arrays to
whether they are identical. The function should return1 if they are identical, 0 otherwise.
112 Read student information (name, roll number and marks) using structure and display it.
113 Read student information (name, roll number and marks) of 10 students using array of
structures.
114 Access structure members through pointer.

END

Departments of CSE & ISE, RNSIT Page | 55


C Programming Lab (18CPL17/27)

[DOCUMENT TITLE]

Departments of CSE & ISE, RNSIT Page | 56


C Programming Lab (18CPL17/27)

[DOCUMENT TITLE]

Departments of CSE & ISE, RNSIT Page | 57

You might also like