Professional Documents
Culture Documents
C PROGRAMMING
LABORATORY MANUAL
NAME : .......................................................................................................................................................................................................................................................................................................................................................................................................................................
BRANCH : .....................................................................................................................................................................................................................................................................................................................................................................................................................................
SECTION : ..................................................................................................................................................................................................................................................................................................................................................................................................................................
USN :..........................................................................................................................................................................................................................................................................................................................................................................................................................................
VISION AND MISSION OF INSTITUTION
Vision
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
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)
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)
TEST-1
TEST-2
10
11
12
13
14
15
Total
Marks
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.
[DOCUMENT TITLE]
TABLE OF CONTENTS
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
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
[DOCUMENT TITLE]
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
14 Use of Pointers 47
14.1 Algorithm 47
14.2 Program 48
14.3 Test Cases 48
[DOCUMENT TITLE]
SYALLABUS
SEMESTER I/ II
C PROGRAMMING LABORATORY
Sub Code : 18CPL17 / 18CPL27 CIE Marks : 40
LABORATORY PROGRAMS
PART A
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.
[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.
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.
[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.
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:
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.
[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.
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:
Output Unit: It is used to display or print results from a computer. Monitor, printer and
plotters are commonly used output devices.
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.
[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.
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.
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.
[DOCUMENT TITLE]
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.
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.
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.
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.
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:
[DOCUMENT TITLE]
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).
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
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.
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.
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.
[DOCUMENT TITLE]
Click Applications -> System Tools -> Terminal on desktop to open terminal
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).
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
After compilation, run the program using ./a.out command or Compile with optional
executable filename: $cc – o Hello Hello.c
[DOCUMENT TITLE]
There are three approaches to problem solving, namely: Algorithm, Flowchart and Pseudocode
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.
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
[DOCUMENT TITLE]
[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.
Begin
Input length, breadth
Area=length*breadth
Print Area
End
SAMPLE C PROGRAM
#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;
}
[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.
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
[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
}
[DOCUMENT TITLE]
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
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.
[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:
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]
[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
[DOCUMENT TITLE]
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
[DOCUMENT TITLE]
8 a = 2, b= -7, c=0
9 a = 2, b= -7, c=8
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
Other alternatives:
Find the roots of quadratic equation program using
i) only if statement ii) Combination of if and switch statement
[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
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
{
[DOCUMENT TITLE]
[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.
-----------
[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.
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
[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
[DOCUMENT TITLE]
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);
} }
[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.
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
[DOCUMENT TITLE]
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
[DOCUMENT TITLE]
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.
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
[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
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.
[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?
[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.
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
[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
}
}
}
[DOCUMENT TITLE]
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 = *
Matrix A Size= 2, 3
5 Give your input and find the result
Matrix B Size=3, 2
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)
[DOCUMENT TITLE]
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.
[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
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]
[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",°ree);
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;
}
5 Degree = 10
6 Degree = 90
[DOCUMENT TITLE]
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
Other alternative:
This program can be executed by reading number of terms.
[DOCUMENT TITLE]
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.
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]
[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 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);
}
[DOCUMENT TITLE]
len++;
return (len);
}
[DOCUMENT TITLE]
Viva Questions
[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.
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
[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;
}
[DOCUMENT TITLE]
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
[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)
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
[DOCUMENT TITLE]
6 N =2
7 N = 16.25
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
[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 (.)
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
[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);
}
[DOCUMENT TITLE]
Viva Questions
[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.
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
[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;
}
[DOCUMENT TITLE]
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)
[DOCUMENT TITLE]
The process in which a function calls itself directly or indirectly is called recursion and the
corresponding function is called as recursive function.
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));
}
[DOCUMENT TITLE]
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
[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
[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
[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.
[DOCUMENT TITLE]
END
[DOCUMENT TITLE]
[DOCUMENT TITLE]