C Language Staff Manual
C Language Staff Manual
C Language Staff Manual
Exercise 5
Write a C program for the following:
a) Calculate the area of triangle using the
formula area = (s (s-a) (s-b)(s-c))1/2
where 54-60
s= (a+b+c)/2
b) Find the largest of three numbers using
ternary operator.
c) Find the roots of a quadratic equation.
Exercise 7
Design a C program for the following: 74-99
a) Find the largest and smallest numbers in
the array.
b) Search whether the given element is in
the array.
c) Perform Addition, subtraction and
multiplication of Matrices
d) Delete n Characters from a given
Page |1 position in a given string.
Department of Computer Science & Engineering GEC
e) Illustrate at least five string handling
functions.
REFERENCES
GUIDELINES TO STUDENTS
Equipment in the lab for the use of student community. Students need to maintain a
proper decorum in the computer lab.
Students must use the equipment including PCs, Keyboard and Mouse with care. Any
damage is caused is punishable.
Students are required to carry their observation and record books with completed
exercises while entering the lab.
Students are supposed to occupy the machines allotted to them and are not
supposed to talk or make noise in the lab..
Lab can be used in free time / lunch hours by the students. Students who need to
use the systems should take prior permission from the lab in-charge.
Students are not supposed to use floppy disks/CDs/Pen drives etc during the Lab
session.
PART - A
A Computer is a programmable electronic machine that can store, retrieve and process
data.
It was designed to automatically carry out a sequence of arithmetic or logical operations.
1. MOTHERBOARD:
The Motherboard is the main circuit board in a computer. It interconnects all the
parts of a computer together.
It provides a way for hardware in a computer to communicate with each other.
The CPU, Memorym hard Drives, optical drives, Video card, Sound card and all other
ports and expansion cards all connect to the motherboard directly or via cables.
It can be thought of as the “backbone” of the computer and is also called as Main board,
system board or logic board.
NorthBridge:
It is the focal point of the motherboard. It connects CPU/Socket, RAM slots and AGP slots. It handles
communication among the CPU, RAM, Agp and the Southbridge.
7
SouthBridge:
It is not directly connected to the CPU. NorthBridge ties the Southbridge to the CPU. It handles all of a
computer Input/Output functions such as USB, audio etc. It consists of Real time clock and controller to I/O
port.
Ports:
8
Ports are an Interface between the computer and the external world. The various ports of the
motherboard are:
PS/2 Mouse port - used to connect Mouse
or
PS2 ports Keyboard port - used to connect Keyboard
Parallel port - used to connect devices like printer
Serial port - used to connect devices like mouse ans external modem
VGA Port - Video Graphics Array
used to hold on board VGA card. Generally monitor is connected to this
port.
Ethernet/RJ 45 port - used with LAN card. It is an outerview of RJ 45 Jack associated with LAN
cards.
USB port - Universal Serial Bus. It is a high speed serial interface that is used with all
devices like pendrives etc.
Gaming port - used to connect gaming devices like Joysticks.
Sound ports - Line in, Line out and Micro phone
RAM Slots:
There are 2 types of RAM slots
1) SDRAM (Synchronous Dynamic Random Access Memory) slots
2) DDR RAM (Double Data Rate Random Access Memory) slots
These RAM slots holds the corresponding RAM modules
SDRAM slots hold SD RAM
DDR RAM slots hold DDR RAM
These two slots differ in the number of Notches (gaps). SDRAM slot has 3 Notches while DDR RAM has only
one Notch.
9
AGP Slot: AGP stands for Accelerated Graphics Port
It holds AGP card. It is a high speed point-to-point channel for attaching a graphics card to a computer
motherboard. It is faster than PCI slot..
PCI Slots: PCI stands for peripheral Component Interconnect.
It is used as an expansion slot. It holds external cards which are used to increase the capabilities of the
system. There are more than one PCI slot.
CNR Slot: CNR Stands for Communications and Networking Raiser
It is a dedicated connector for cards apecific to the motherboard design to offer communications and
networking options.
10
This is the point from which the motherboard derives the power to work. It has 20 pins.
Floppy Drive Connector: Used to power floppy drive.
CD in Jacks:
This is the point from which the cable from the CD Drive is to be connected in order to listen to audio
while playing an audio CD.
11
The missing pins on the CPU indicate Pin1 indication which must coincide with thw pin1 indication of the
Socket while installing the CPU.
4. CABINET:
It holds all the components of a computer.
Power switch: Starts the computer
Reset switch: Restarts the computer
Power LED: Glows when computer is working
HDD LED: glows when ever hard disk is accessed
12
Front view Back view Inner view of the Cabinet
13
2. DDR RAM – 1 Notch, speed 266 MHz
9. CD ROM DRIVE: CD ROM stands for Compact Disk Read Only Memory
It can read data from a CD but cannot write data onto it.
14
Head phones jack: used to listen to audio when the CD Drive is playing an audio CD
Volume control: used to control the volume level coming out of the head phones jack
Access LED: glows whenever the CD inside the CD drive is accessed
Pin hole: used to unlock the drive to remove the CD in the drive in case of a power failure.
Open/Close button: used to open/close the drive
CD Audio Connectors: A cable from this is to be connected to the sound card in order to listen sound while
playing an audio CD
Jumper pins: used to change the settings of the drive
IDE Connector: An IDE connector from motherboard is connected to this inorder to
exchange signals
Power Connector: This is the point from which the CD ROM Drive derives the power to work
15
52X speed at which the drive can write data onto a CD
24X speed at which the drive can rewrite data onto a rewritable CD
52X speed at which the drive can read data from a CD
16
13. LAN CARD/ETHERNET CARD/NETWORK INTERFACE CARD:
LAN stands for Local Area Network
This card is used to connect two or more devices hence making communication between them possible.
LINK LED – Glows when there is any active connection to the card
ACT LED – Glows when ever the card sends/receives data
17
ACT stands for Acknowledgement
14. CABLES:
Floppy Drive Cable – Always has a Twist
IDE Cables – Used to connect IDE devices such as the Hard disk, CD Drive etc
IDE cables are available in 2 versions
1. 40 conductor cable – low speed
2. 80 conductor cable – high speed
18
EXERCISE 1(B): DEMONSTRATION OF ASSEMBLING A COMPUTER
19
2. Installing the Motherboard
Always hold the motherboard on the RAM slots/PCI slots or CNR slots
Place the Motherboard in such a way that the ports of the motherboard correctly fit into the I/O
shield
Fix the screws to the motherboard
Don’t touch the motherboard with the sharp edge of the screw driver as it may damage some of the
components of the motherboard.
20
3. Installing the CPU
Unlock the lever of the socket 478 and move it up until it is perpendicular to the motherboard
Place the CPU in the socket 478 and make sure that the pin1 indication of the CPU must coincide with
the pin1 of the socket 478. Never press CPU into the socket.
Now, lock the socket 478 by restoring the locking lever to its original position.
21
4. Installing the CPU heat sink and fan assembly
Put the CPU heat sink and fan assembly into the COU heat sink and fan retention module and secure
(lock) it to the CPU heat sink and fan retention module
Power the CPU heat sink and fan by plugging 9in the power connector into the CPU fan connector on
the Motherboard.
22
6. Installing the SMPS
Place the SMPS in the SMPS case and secure (lock) it to the chasis with the help of 4 outer screws
23
9. Installing the FDD
Remove the cover on the front side of the cabinet pertaining to the Floppy disk drive
Push the FDD into the case from front
Secure the FDD to the chasis with Inner screws
Connect one end of the FDD cable to the Motherboard and the other end to the FDD
Connect the cable to the FDD in such a way that when we install the power connector, the red wire of
the power connector and the red wire on the FDD data cable come adjacent to each other.
24
11. Installing the CD ROM drive/ CD Writer drive
Remove the cover on the front side of the cabinet pertaining to the CD Rom drive
Push the CD ROM drive into the case from front
Secure the CD ROM drive into the chasis with Inner screws
Connect one end of the CD ROM drive data cable to the IDE channel on the Motherboard and the
other end to the CD ROM Drive.
Connect the cable to the CD ROM drive in such a way that, when we install the power connector, the
red wire of the power connector and the red wire on the data cable come adjacent to each other.
Connect the power connector from the SMPS to the CD ROM Drive
Follow the similar steps for Installing the CD Writer Drive
25
12. Installing the LAN card
Put the LAN card into the desired PCI slot and press it until the pins on the LAN card go into the slot
up to 3/4th of the height
Fix the LAN card to the chasis with an Inner screw
26
Connect the front panel connectors to the Motherboard as specified in the Motherboard specifications
manual.
Fix the peripheral devices such as the keyboard, mouse, monitor etc to the ports
This completes the assembling of the P-IV computer
27
EXERCISE 1(C): DEMONSTRATING INSTALLATION OF OS AND APPLICATIONS
28
4. Press F8 to accept the Licence Aggrement
5. The screen will now list all existing partitions and un-partitioned space for each hard disk. Use the
cursor/arrow keys to choose where to create the new partition.
6. Press D to delete an existing partition or
7. Press C to create a new partition in un-partitioned space.
8. If you press D to delete an existing partition, you must then press L to confirm that you want to
delete that partition.
29
9. Repeat this process for each of the existing partitions that you want to move (or remove) in order to
create your new partition.
10. When all necessary partitions are deleted, you can then select the remaining un-partitioned space and
then press C to create new partitions.
Type the size in megabytes (MB) that you want the new partition to be. Then press ENTER.
Alternatively, you can just press ENTER to create the partition using all the available space (i.e. create
the biggest possible partition).
11. If you want to install Windows XP, use the arrow keys to select the partition where you want to install
Windows XP and then press ENTER.
12. To format the partition, use the arrow keys to select the partition where you want to install Windows
XP.
13. Select the NTFS formatting option and press ENTER
30
14. Setup will start formatting the disk and will then start copying files from the CD-ROM to the disk
31
15. The system will then need to reboot
32
16. After the restart, Windows XP starts the first time with the Graphical User Interface
33
18. Personalize your system by setting regional and language settings, entering your name and organization ,
Type your product key, define name and password for the administrator account, set up date and time
34
35
36
19. Setup continues with "Finalizing installation "
37
This completes installing Windows XP
Aim: Write a leave letter to the Principal by using different alignments, correct formats in MS-Word.
Description:
Microsoft word is a powerful text editor which supports different font types, styles, image operations
etc. It is widely used for detailed documentation in various sectors like educational institutes, business
documentation, academic projects etc.
Procedure:
Step 1: Open MS-Word by click on START button; go to All Programs, then select Microsoft Office Word
2007.
Step 2: To open a new document, Click on Office Button then select New - > Blank Document then click
on create option.
Step 3: Then select TEXT AREA, and then write Leave Letter as a heading, Select the text, click on bold
button to make it bold as “LEAVE LETTER”, and change the font size to 16.
Step 4: Then write date and place in a format as follows
DATE: 15/09/2014,
Guntur.
Then Select the text and make it right by clicking on right alignment button
Step 5: Then write To address as follows and select this text and make it left by clicking on left alignment
38
button
To
The Principal,
College of Engineering,
Guntur.
Step 6: Then write Subject according to your letter. And select this text and press tab button for two times. Step
7: Then write the body of the letter according to your letter. And select this text and make it justification
button
Step 9: Now write the “From address” as
follows Yours Faithfully, xxxxx.
39
OUTPUT:
LEAVE LETTER
D:15/9/2014,
Guntur.
To
The Principal,
College of Engineering,
Guntur.
Respected Sir,
Yours Faithfully,
XXXXX,
B.Tech I year,
CSE Branch.
Viva Questions:
40
EXERCISE 2(B): CREATING A DOCUMENT USING LATEX
Description:
It is a“typesetting program” written by Leslie Lamport of MIT. It usesTeX
engine written by Donald E. Knuth. It is designed for producing beautiful books, thesis’s,
papers, articles etc. and the De facto standard for writing academic papers.
What is LaTeX
Disadvantages
41
LaTeX Skeleton
% my first LaTeX file
\documentclass[options]{class}
\begin{document}
Hello, world!
\end{document}
Syntax
Viva Questions:
Method1: Method2:
1. Click on start button 1. Click on Start button
42
2. Click on programs 2. click run
3. Click on Ms-office 3. type the Excel
4. Click on Excel 4. After click ok button
43
Default setting Insert the
Rename the
1. Sheets -- 3 work Sheet:
work sheet:
2. Font - Arial
3. Font size - 10 1. Click on the
1. Click on
4. Row Hight- 12.75 insert menu
format menu
5. Column Width- 8.43 2. Click in work
2. Click on the
6. Font Style regular sheet
sheet
7. Font Color- Black Delete the
3. Click on the
8. Text alignment- Left work Sheet:
rename
9. Numbering alignment =- Right alignment 1. Click on the
4. type the sheet
edit menu
name
2. Click on delete
Navigation in spread Sheet
To move the cell pointer to the left row Side -- (left arrow)
To move the cell pointer to the up row Side - (up arrow)
To move the cell pointer to the down t row Side -- (down arrow)
To move the cell pointer to the right row Side (right arrow)
To move the cell pointer to the first column in same row (“HOME”)
To move the cell pointer to the last column in last row (“CTRl+RIGHT ARROW”)) To
move the cell pointer to the first column in same row CTRl+LEFT ARROW”)) To move
the cell pointer to the same row column same row (CTRl+LEFT ARROW”)
Functions:
1. Text functions
2. Date and Time Functions
3. Math functions
4. Logical functions
Mathematical Function:
NAMES SYNTAX SYNATX
SUM =A1+B1+C1 =SUM(A1:E1)
AVERAGE = (A1+B1+C1)/3 =AVERAGE(A1:C1)
MAX =MAX(A1+B1+C10 =MAX(A1:C1)
FACT =FACT(A1) =FACT(B1)
MUTLIFLICATION =A1*B1 =MMULT(A1,B1)
44
Aim: Create a marks sheet for 10 students using EXCEL.
Steps:
5 Write S.no’s from 1-10 in A4 - A13 cell addresses and H.T.No’s from B4- B13.
6 Now enter the marks in C4 – M13 cell addresses.
7 Now in the G.Total cell,select N4 cell and apply the formula for adding the marks
contained in C4 – M4 cell addresses in the formula bar as
fx= C4+D4+E4+F4+G4+H4+I4+J4+K4+L4+M4 then press ENTER key.
8 Select the N4 cell and drag towards down for further students calculations.
9 Now calculate the Percentage.For that select O4 cell and type % calculation formula in
Formula bar as
fx=N4/1000*100
10 Select the O4 cell and drag towards down for further students results.
11 Now the % appears in decimal values,now in order to appear the values as rounded
values,select the O4 cell then right click the mouse button , select Format cells then
Numbers and now make decimal places to 0(zero) then click OK.Now again drag for
other cell values to be rounded.
12 Now for keeping the borders,select cells from A1 – O13 and select All Borders on the
home Menu.
13 Now for saving click on OFFICE button and click on Save and type file name as
“Marks Sheet”,then click OK.
45
OUTPUT:
Viva Questions:
46
Description: Microsoft PowerPoint is a presentation program. It features an intuitive
interface with a wide variety of presentation themes, styles and types. These tool could be used
for paper presentations, conference papers, business seminars etc.
Inserting a Slide:
To insert a new slide…
–From the Hometab, select “New Slide”
‐As well, you can right‐click between any 2 slides in the preview frame located on the left‐
hand side of the Normal view and select “New Slide”
Deleting a Slide:
To delete a slide…
–Select the slide you’d like to delete (eg. by highlighting it) and selecting “Delete “from
the Hometab –As well, you can right-click on any slide in the preview frame located on the
left-hand side of the Normal view and select “Delete Slide”
Inserting Pictures:
To insert pictures…
–From the Inserttab you can insert pictures from your computer, clip art, shapes, etc…
–Also, when you have a blank slide (or parts of a blank slide), you can also click on
options within these blank compartments to insert pictures.
47
Inserting Charts:
To insert charts…
–From the Inserttab you can insert pictures from your computer, clip art, shapes, etc…
–Also, when you have a blank slide (or parts of a blank slide), you can also click on options
within these blank compartments to insert charts
•Once you’ve selected to insert a chart, it will ask you choose what kind of chart you’d like to
insert.
•After you’ve picked a type, the screen will split in half with the chart on one side and an excel
spreadsheet on the other
–To modify the chart, make changes in the data presented in the spreadsheet
– Charts from Excel can also be copied and pasted into PowerPoint
Inserting Tables:
To insert a table…
–From the Insert tab, select “Table “and a box will drop down giving you more options for
inserting a table. –Also, when you have a blank slide (or parts of a blank slide), you can also
click on options w/n these blank compartments to insert tables
48
OUTPUT
Viva Questions:
49
An integrated development environment (IDE) is a programming environment that has
been packaged as an application program, typically consisting of a code editor, a compiler, a
debugger and a graphical user interface (GUI) builder. The IDE may be a stand-alone
application or may be included as part of one or more existing and compatible applications
Turbo C Integrated Development Environment
IDE is nothing but Integrated Development Environment in which one can develop, run, test
and debug the application. The Turbo C IDE appears as shown in figure.
The C Developing Environment is a screen display with windows and pull-down menus. The
program listing, error messages and other information are displayed in separate windows. The
menus may be used to invoke all the operations necessary to develop the program, including
editing, compiling, linking, and debugging and program execution. If the menu bar is inactive,
it may be invoked by pressing the [F10] function key. To select different menu, move the
highlight left or right with cursor (arrow) keys. You can also revoke the selection by pressing
the key combination for the specific menu.
Invoking the Turbo C 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 c:\tc\bin.
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.
Writing a Program in Turbo C
When the Edit window is active, the program may be typed. Use the certain key combinations
to
perform specific edit functions.
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.
50
The steps required to create an executable file are:
1. Create a source file, with a .c extension.
2. Compile the source code into a file with the .obj extension.
3. 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
Viva Questions:
PART- B
5 a) Write a C program to calculate the area of triangle using the formula area
A= (s (s-a) (s-b)(s-c))1/2 where s= (a+b+c)/2
Description: The area of a triangle depends on the size of all the three sides of the triangle. We
use the mathematical function “sqrt” for performing the square root operation using the
mathematical header file <math.h>
51
Algorithm
1. Start.
2. Read three sides of a triangle a,b,c.
3. Calculate s= (a+b+c)/2.
4. Display Area=sqrt(s*(s-a)*(s-b)*(s-c)).
5. Display area of triangle.
6. Stop.
Flowchart
start
calculate s= (a+b+c)/2
Display Area=sqrt(s*(s-a)*(s-b)*(s-c))
Display area of
triangle Area
Stop
Program
#include<stdio.h>
#include<math.h>
int main()
{
float a,b,c;
52
float s,area;
clrscr();
printf("Enter size of each sides of triangle");
scanf("%f%f%f",&a,&b,&c);
s = (a+b+c)/2;
area = sqrt(s*(s-a)*(s-b)*(s-c));
printf("Area of triangle is: %.3f",area);
return 0;
}
Output
1. Enter size of each sides of triangle 4.5 2.5 5
Area of triangle is: 5.612
2. Enter size of each sides of triangle 5 6 3
Area of triangle is: 7.483
Viva questions:
Description: A ternary operator is a special operator that can check for two conditions in a
single statement. If the condition is true, a sequence of instructions is executed. Else, another
sequence is executed.
Algorithm
1. Start.
2. Read three numbers a,b,c .
3. If a>b goto step 3.1 otherwise goto step 4
3.1. If a>c goto step 3.2 otherwise goto step 3.3
3.2. Display a is largest of three numbers ,goto step 5
53
3.3. Display c is largest of three numbers ,goto step 5
4. If b>c goto step 4.1 otherwise goto bstep 4.2
4.1. Display b is largest of three numbers goto step 5
4.2. Display c is largest of three numbers
5. Stop.
Flowchart
start
T F
a>b
?
T T F
a>c b>c
F
? ?
Stop
Program
#include<stdio.h>
int main()
{
int a,b,c,big;
clrscr();
printf("\nEnter 3 numbers:");
scanf("%d %d %d",&a,&b,&c);
big=a>b?a>c?a:c:b>c?b:c;
54
printf("\nThe biggest number is: %d",big);
return 0;
}
Output
1. Enter 3 numbers:345 29 2
The biggest number is: 345
2. Enter 3 numbers: 8 10 9
The biggest number is: 10
Viva questions:
Description:
Nature of roots of quadratic equation can be known from the determinant d = b2-4ac
if b2-4ac >0 then roots are real and unequal
if b2-4ac =0 then roots are real and equal
if b2-4ac <0 then roots are imaginary
Algorithm:
Step 1: start
Step 2: read the a,b,c value
Step 3: assign pow((b*b-4*a*c),0.5) value to d
Step 4: if d==0 compute r1=-b/(2*a) , r2=-b/(2*a) go to step 7 otherwise go to step5
Step 5: if d<0 print roots are imaginary and compute real and imaginary parts for r1 and r2
goto step 8 otherwise go to step 6
55
Step 6: compute r1 = ((-b+d) / (2*a)) r2 = ((-b-d) / (2*a)) go to step 7
Step 7: print r1, r2
Step 8: stop
Flowchart:
Start
Read a,b,c
d = pow((b*b-4*a*c),0.5)
F T
d= = 0 d< 0
T F
r1 = ((-b+d) / (2*a)) Display
r1=r2= r2 = ((-b-d) / (2*a)) roots are
-b / (2 * a ) imaginary
r2= -b / (2 *
a)
Display
r1, r2
Stop
56
Program:
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int a,b,c;
double r1,r2,d;
clrscr();
printf("Enter the values of a,b,c:");
scanf("%d%d%d",&a,&b,&c);
d=((b*b)-(4*a*c));
if(d==0)
{
r1=r2=(-b/(2*a));
printf("Roots are Equal:%lf,%lf",r1,r2);
}
else if(d<0)
printf("Roots are Imaginary");
else
{
r1=(-b+sqrt(d))/(2*a);
r2=(-b-sqrt(d))/(2*a);
printf("Roots are:%lf,%lf",r1,r2);
}
getch();
}
Output:
Viva Questions:
1) What are various types of loop statements?
2) What is the difference between while and do-while statements?
3) List out the C features?
57
Exercise 6 :
6 a) Write a c program to read two integer operands and one operator from the user,
perform the operation and then print the result. (Consider the operators +,-,*, /, % and
use Switch Statement)
Description:
Take two integer operands and one operator from user and perform some arithmetic operations
by using the following operators like +,-,*, /, %
Ex: 2+3=5
Algorithm:
Step 1: Start
Flowchart:
58
start
op?
‘-’
‘+’ ‘*‘ ‘/’ ‘%’
displa display a- display display display a display
y a+b b value a*b value a/b value %b value “Invalid
value operator”
start
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int op1,op2;
char op;
clrscr();
printf("\nOperations Performed are: + - * / %");
printf("\nEnter 2 Integers & an Operator:");
scanf("%d %d %c",&op1,&op2,&op);
switch(op)
{
case '+': printf("ADDITION -- Sum is %d",op1+op2);
break;
case '-': printf("SUBTRACTION -- Difference is %d",op1-op2);
break;
case '*': printf("MULTIPLICATION -- Product is %d",op1*op2);
break;
case '/': printf("DIVISION -- Quotient is %d",op1/op2);
break;
case '%': printf("MODULUS -- Remainder is %d",op1%op2);
break;
default: printf("Invalid operation");
break;
}
getch();
}
59
Output:
VIVA QUESTIONS:
Description:
60
A prime number is the one which has only the factors 1 and itself. We check for the
total number of factors for the given number. If the given number has only two factors, it’s a
prime number. Else, it’s not a prime number.
Algorithm:
Step 1: Start
Step 2: initialize c=0
Step 3: Read input ‘n’ from user
Step 4: initialize i=1
Step 5: check whether n%i==0 if true increment c
Step 6: increment i
Step 7: repeat steps 4 and 5 until n>i
Step 8:check c=2 if true print number is prime
Step 9: else print number not prime
Step 10: stop
Flowchart:
START
61 c=
i<=n
=2
READ INPUT ? Number is prime
Number is not prime ? ‘n’
Increment
FROM USERcount
Increment STOP
Initialize i=1i
c
F
F If(n
%i=0
)
Program
#include<stdio.h>
void main()
{
62
int c=0,n,i;
printf("enter a number");
scanf("%d",&n);
i=1;
do
{
if(n%i==0)
c++;
}while(i<=n);
if(c==2)
printf("given number %d is prime",n);
else
printf("given number %d is not prime",n);
getch();
}
Output
1. enter a number21
given number 21 is not prime
2. enter a number251
given number 251 is prime
Viva Questions:
1) What is a composite number?
2) How does a for loop work?
3) State the skeleton for simple if-else statement?
4) What is meant by access specifier?
63
6 c) Write a C program to display first N natural numbers.
Description:
A natural number is a number that occurs commonly and obviously in nature. As such,
it is a whole, non-negative number. The set of natural numbers, denoted N, can be defined in
either of two ways: N = {0, 1, 2, 3,}
Algorithm
1. Start.
2. Read the value of n.
3. Initialize the variable i=1.
4. Repeat.
4.1. Display i value.
4.2. i is incremented by 1 in each case
Until the condition is failed i.e. i<=n.
5. stop.
Flowchart
start
i=1
F
i<=
n
T
Display i value
i+=1
Stop
64
Program
#include<stdio.h>
int main()
{
int i,n;
clrscr();
printf("\n Enter range of natural numbers ");
scanf("%d",&n);
i=1;
while(i<=n)
{
printf("%d\t", i);
i++;
}
return 0;
}
Output
1. Enter range of natural numbers 10
1 2 3 4 5 6 7 8 9 10
2. Enter range of natural numbers 5
1 2 3 4 5
Viva Questions:
1) What is a natural number?
2) Any program execution in C language starts from which function?
3) How does the printf and scanf functions work?
65
6 d) Write a C program to calculate electricity bill for the consumed units – assume
suitable constraints.
Algorithm
Step 1: Start
Step 2: Read the no. of units(U)
Step 3: if the units(U) are less than or equal to 200 then
calculate bill =U*0.50 and goto step 7
Step 4: Otherwise check the units(U) are less than or equal to 400 then
Calculate bill =100+(U-200)*0.60 and goto step 7
Step 5: Otherwise check the units(U) are less than or equal to 600 then
Calculate bill =220+(U-400)*0.80 and goto step 7
Step 6: Otherwise
Calculate bill =380+(U-600)*1.00 and goto step 7
Step 7: Display bill
Step 8: Stop
Flowchart:
start
Read no of units
66
Units< F
T =200
T Units
bill =U*0.50 <=400
bill =100+(U-200)*0.60 T F
Units
<=600
Display bill
stop
Program:
main()
{
float u,amt;
printf("Enter no of units\n");
scanf("%f",&u);
if(u<=200)
amt=u*0.5;
else if(u<=400)
amt=100+(u-200)*.6;
else if(u<=600)
amt=220+(u-400)*.8;
else
amt=380+(u-600)*1.00;
printf("Amount for %.0f units is %.2f",u,amt);
getch();
}
Output:
67
Viva questions:
6 e) Write a c program to find the sum of individual digits of a positive integer and find
reverse of the given number.
Description: Sum of the individual digits means adding all the digits of a number
Ex: 123, the sum of digits is 1+2+3=6
Algorithm:
Step 1: start
Step 2: initialize the sum=0
Step 3: read number n
Step 4: if n!=0 go to Step 6 else go to step 7
Step 5: store n%10 value in rem
Add rem value to sum
Calculate rev=rev*10+rem
Assign n/10 value to n
Go to Step 4
Step 6: print sum
Step 7: print rev
Step 8: stop
Flowchart:
start
sum=0
read number n
68
F
n!=0
T
rem=n%10
Sum=sum+rem
rev=rev*10+rem
n=n/10;
Print sum
Print rev
stop
Program:
main()
{
int n,rem,rev=0,sum=0;
printf("\n Enter number");
scanf("%d",&n);
while(n!=0)
69
{
rem=n%10;
sum=sum+rem;
rev=rev*10+rem;
n=n/10;
}
printf("\n Sum=%d",sum);
printf("\n Rev=%d",rev);
}
Output:
1)
Enter number1234
Sum=10
Rev=4321
2)
Enter number567
Sum=18
Rev=765
VIVA QUESTIONS:
7 a) Write a C program to find both the largest and smallest number in a list of integers
Description:
This program contains n number of elements, in these elements we can find and diplay
the largest and smallest numbers.
Algorithm:
Step 1: start
Step 2: read n
Step 3: initialize i=0
70
Step 4: if i<n do as follows. If not goto step 5
Read a[i]
Increment i
Goto step 4
Step 5: min=a[0], max=a[0]
Step 6: initialize i=0
Step 7: if i<n do as follows. If not goto step 8
If a[i]<min
Assign min=a[i]
Increment i goto Step 7
Step 8: print min,max
Step 9: stop
71
Flowchart:
Start
Read n
i= 0
false i<n i++
true
Read a[i]
min = a[0]
max = a[0]
i=0 i++
false
i< n
true
false true
if a[i]<
min
min=a[i]
a[i]>max
true
max=a[i]
Print min,
max
stop
72
Program:
main()
{
int a[20],i,n,max,min;
clrscr();
printf("Enter size\n");
scanf("%d",&n);
printf("\n Enter %d elements",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
max=min=a[0];
for(i=1;i<n;i++)
{
if(a[i]>max)
max=a[i];
if(a[i]<min)
min=a[i];
}
printf("\n Max=%d",max);
printf("\n Min=%d",min);
}
Output:
1) Enter size 5
Enter 5 elements5
23
12
7
1
Max=23
Min=1
2) Enter size 9
Enter 9 elements12
356
145
897
210
23
54
65
89
Max=897
Min=12
VIVA QUESTIONS:
73
1) What is an array?
2) How many types of arrays are there?
3) What is the use of getch() function?
4) What are the advantages of implementing an array?
74
7 b) Write a c program to Search whether the given element is in the array(Linear search)
Algorithm
1. Start.
2. Read number of elements in an array (n)
3. Read n array elements
4. Read search key
5. Initialize i=0
6. If i<n do as follows if not goto step 7
6.1. check if array element equal to key then goto step 6.2 otherwise goto 6.3
6.2. Display search key is available in the array ,goto step 8
6.3. Increment i
7. if i=n display key is not found
8. Stop
Flowchart
75
start
Read number of
elements in an array (n)
Initialize i=0
i<n
?
?
T F
Read array elements
a[i]
i++
i<n
i=0
i+
+
F T F
a[i]=
=k
T
key is available
F i==
n?
? T
key is not found
Stop
Program:
main()
76
{
int a[20],i,n,key;
clrscr();
printf("Enter no of elements\n");
scanf("%d",&n);
printf("Enter %d elements",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("Enter key");
scanf("%d",&key);
for(i=0;i<n;i++)
{
if(a[i]==key)
{
printf("element is found at %d th location",i);
break;
}
}
if(i==n)
printf("key not found");
Output:
1) Enter no of elements 5
Enter 5 elements5
4
3
2
1
Enter key2
element is found at 3 th location
2) Enter no of elements 8
Enter 8 elements14 2 54 896 47 25 14 7
Enter key100
key not found
Viva Questions:
1) How an array is efficient in storing and organizing of data?
2) If the total elements of an array are n, then the maximum possible value of index is?
Why?
3) How the search operation does takes place in an array?
7 c i) Write a c program to perform the addition of two matrices
77
general, matrices can contain complex numbers but we won't see those
here. Here is an example of a matrix with three rows and three columns:
Algorithm:
Step 1: start
Step 2: read the size of matrices A,B – m,n
Step 3: read the elements of matrix A
Step 4: read the elements of matrix B
Step 5: perform the addition operation place the result in C matrix
Step 6: print the elements of matrix C
Step 7: Stop
78
Flowchart:
start
If r1!=r2 T
and c1!
=c2
F
Display invalid
Read matrices A and B order of
matrices
F i=0 i++
i<r1
j=0 j<c1 F
j++
c[i][j]=a[i][j]+b[i][j];
stop
79
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10][10],b[10][10],c[10][10];
int r1,c1,r2,c2,i,j,k;
clrscr();
printf("Enter Number of rows & columns for Matrix1:");
scanf("%d %d",&r1,&c1);
printf("Enter Number of rows & columns for Matrix2:");
scanf("%d %d",&r2,&c2);
if(r1==r2 && c1==c2)
{
printf("Enter elements for Mat1:");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
scanf("%d",&a[i][j]);
}
printf("Enter elements for Mat2:");
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
scanf("%d",&b[i][j]);
}
for(i=0;i<r1;i++)
{
printf("\n");
for(j=0;j<c1;j++)
{
c[i][j]=a[i][j]+b[i][j];
printf("%d\t",c[i][j]);
}
}
}
else
printf("Matrix addition is not possible");
getch();
Output:
80
1)
Enter Number of rows & columns for Matrix1:2
2
Enter Number of rows & columns for Matrix2:2
2
Enter elements for Mat1:2
2
2
2
Enter elements for Mat2:2
2
2
2
4 4
4 4
2)
Enter Number of rows & columns for Matrix1:2
3
Enter Number of rows & columns for Matrix2:3
2
Matrix addition is not possible
81
Description:A matrix is a collection of numbers arranged into a fixed
number of rows and columns. Usually the numbers are real numbers. In
general, matrices can contain complex numbers but we won't see those
here. Here is an example of a matrix with three rows and three columns:
Algorithm:
Step 1: start
Step 2: read the size of matrices A,B – m,n
Step 3: read the elements of matrix A
Step 4: read the elements of matrix B
Step 5: perform the subtraction operation place the result in C matrix
Step 6: print the elements of matrix C
Step 7: Stop
82
Flowchart:
start
If r1!=r2 T
and c1!
=c2
F
Display invalid
Read matrices A and B order of
matrices
F i=0 i++
i<r1
j=0 j<c1 F
j++
c[i][j]=a[i][j]-b[i][j];
stop
83
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10][10],b[10][10],c[10][10];
int r1,c1,r2,c2,i,j,k;
clrscr();
printf("Enter Number of rows & columns for Matrix1:");
scanf("%d %d",&r1,&c1);
printf("Enter Number of rows & columns for Matrix2:");
scanf("%d %d",&r2,&c2);
if(r1==r2 && c1==c2)
{
printf("Enter elements for Mat1:");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
scanf("%d",&a[i][j]);
}
printf("Enter elements for Mat2:");
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
scanf("%d",&b[i][j]);
}
for(i=0;i<r1;i++)
{
printf("\n");
for(j=0;j<c1;j++)
{
c[i][j]=a[i][j]-b[i][j];
printf("%d\t",c[i][j]);
}
}
}
else
printf("Matrix subtraction is not possible");
getch();
84
Output:
1)
Enter Number of rows & columns for Matrix1:2
2
Enter Number of rows & columns for Matrix2:2
2
Enter elements for Mat1:2
2
2
2
Enter elements for Mat2:2
2
2
2
0 0
0 0
2)
Enter Number of rows & columns for Matrix1:2
3
Enter Number of rows & columns for Matrix2:3
2
Matrix subtraction is not possible
85
Description:A matrix is a collection of numbers arranged into a fixed
number of rows and columns. Usually the numbers are real numbers. In
general, matrices can contain complex numbers but we won't see those
here. Here is an example of a matrix with three rows and three columns:
Algorithm:
Step 1: start
Step 2: read the size of matrices A,B
Step 3: check compatibility of matrices for multiplication i.e, number of columns
in the first matrix should be equal to number of rows in the second matrix.
Step 4: read the elements of matrix A
Step 5: read the elements of matrix B
Step 6: perform the multiplication operation by storing the resulting values into
matrix C.
Step 7: print the resultant matrix C.
Step 8: Stop
86
Flowchart :
start
If c1! T
=r2 F
Read matrices A and B
Display invalid
i=0 i++ order of
i<r1 matrices
F
j=0 j<c2
j++
c[i][j]=0
F
k=0 k<c1
k++
T
c[i][j]=c[i][j]+(a[i][k]*b[k]
[j])
stop
87
T F
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10][10],b[10][10],c[10][10];
int r1,c1,r2,c2,i,j,k;
clrscr();
printf("Enter Number of rows & columns for Matrix1:");
scanf("%d %d",&r1,&c1);
printf("Enter Number of rows & columns for Matrix2:");
scanf("%d %d",&r2,&c2);
if(c1==r2)
{
printf("Enter elements for Mat1:");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
scanf("%d",&a[i][j]);
}
printf("Enter elements for Mat2:");
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
scanf("%d",&b[i][j]);
}
printf("result");
for(i=0;i<r1;i++)
{
printf("\n");
for(j=0;j<c2;j++)
{
c[i][j]=0;
for(k=0;k<c1;k++)
c[i][j]+=a[i][k]*b[k][j];
printf("%d\t",c[i][j]);
}
}
}
else
printf("\n Matrix multiplication is not possible");
getch();
Output:
88
1)
Enter Number of rows & columns for Matrix1:2
3
Enter Number of rows & columns for Matrix2:3
2
Enter elements for Mat1:2
2
2
2
2
2
Enter elements for Mat2:2
2
2
2
2
22
result
12 12
12 12
2)
Enter Number of rows & columns for Matrix1:2
3
Enter Number of rows & columns for Matrix2:2
2
VIVA QUESTIONS:
1) What is a matrix? How are they useful in representing data?
2) What is condition for performing matrix addition?
3) We have two matrices A of order 3*3, B of order 2*2. Can we perform multiplication
operation? Justify.
Description:
89
A string is a sequence of zero or more characters followed by a NULL '\0' character
(end of the string).All the string handling functions are prototyped in: string.h or stdio.h
standard header file. String constants have double quote marks around them.We use the
functions strlen, strcpy for obtaining the length of the string and copying string values
respectively.
Algorithm:
Step 1: start
Step 2: read string
Step 3: read the number of characters to be deleted and from which position we
have to delete
Step 4: copy string from position +number of characters to end
Step 5:
stop
Flow chart: Start
Read string(a)
Read position, no of
characters
delchar( a, n, pos)
Stop
i=pos,j=pos+n i++,j++
if ((a+b-1)<=
strlen(x))
a[j]!=’\0’
a[i]=a[j];
a[i]=’\0’
Return to main
main program
90
Program:
#include <stdio.h>
#include <conio.h>
#include <string.h>
void delchar(char x[],int a,int b);
void main()
{
char string[10];
int n,pos,p;
clrscr();
puts("Enter the string");
gets(string);
printf("Enter the position from where to delete");
scanf("%d",&pos);
printf("Enter the number of characters to be deleted");
scanf("%d",&n);
delchar(string,n,pos);
getch();
}
void delchar(char x[],int n,int pos)
{
int i,j;
for(i=pos,j=pos+n;x[j]!='\0';i++,j++)
x[i]=x[j];
x[i]='\0';
printf("\n the string is deleted,now the string is:");
puts(x);
}
Output:
VIVA QUESTIONS:
1) What is meant by apalindrome ?
2) What is the use of gets() function ?
3) What is the use of puts() function ?
4) What is the syntax for performing String Copy operation?
5) What will happen if the amount of memory is not sufficient while implementing
strcpy() function?
6) Can we use strrev() function for Palindrome verification? Justify.
91
7)
Description:
Apply some of the predefined functions on given strings. These are included in string.h header
file.
Algorithm
Step 1 : start
Step 2: read s1,s2,s3
Step 3: compute l1= strlen(s1)
Step 4 : print l1
Step 5 : compute s=strcpy(s3,s1)
Step 6 : print s
Step7: compute e= strcmp(s1,s2)
Step 7 : if e==0 go to step 8 otherwise go to step 9
Step 8 : display “strings are equal”
Step 9 : display “Strings are not equal “
Step 10 : display “reverse of 1st string is “, strrev(s1)
Step 11 : display “after concatenation of two strings s1 and s2 is “ strcat(s1,s2)
Step 12 : stop
92
Flowchart:
start
Read strings
s1,s2,s3
l1=strlen(s1)
Display l1
s=strcpy(s3,s1)
Display s
e=strcmp(s1,s2)
r=strrev(s1) c=strcat(s1,s2)
false
If
e==0
true
stop
93
Program
#include<string.h>
#include<stdlib.h>
void main()
{
char s1[25],s2[25],s3[25];
int l1,l2,e;
clrscr();
printf("\n Enter three strings ");
gets(s1);
gets(s2);
gets(s3);
l1 = strlen(s1);
printf("\n length of s1 is %d ",l1);
printf("\n After copying 1st string into 3rd string is %s",strcpy(s3,s1));
e=strcmp(s1,s2);
if(e==0)
printf("\n The two strings s1 and s2 are equal ");
else
printf("\n The two Strings s1 and s2 are not equal ");
printf("\n Reverse of first string is %s ",strrev(s1));
printf("\n After adding first two strings %s",strcat(s1,s2));
getch();
}
Output:
1)
Enter three strings sagf
gec
gudlavalleru
length of s1 is 4
After copying 1st string into 3rd string is sagf
The two Strings s1 and s2 are not equal
Reverse of first string is fgas
After adding first two strings fgasgec
2)
Enter three strings gec
gec
gudlavalleru
length of s1 is 3
After copying 1st string into 3rd string is gec
The two strings s1 and s2 are equal
Reverse of first string is ceg
After adding first two strings ceggec
94
VIVA QUESATIONS:
1) What is a string?
2) Which command is used to combine two strings?
3) Which command is used to copy the strings?
4) Which header file/s is used to implement string functions?
5) What is the difference between a character and a string?
6) What is a sub-string?
7) What do the functions gets(),puts() do?
8 a) Write a C program to calculate mean, standard deviation and variance for a given set
95
of values using functions
Description:
This C Program calculates the mean, variance & standard deviation. The formula which is used
in this program are
mean = average of the numbers.
variance = (summation ( ( Xi – average of numbers) * ( Xi – average of numbers)) ) Where i =
1 to N here N is the total no of elements.
Standard deviation = Square root of the variance.
Algorithm
1. Start.
2. Read number of elements in an array (n)
3. Read n elements in the array
4. Call the sub program mean(a,n)
5. Stop
1. Start
2. Initialize sum=0,t=0
3. if i<n then goto step 3.1 otherwise goto step 4
3.1 compute sum=sum+a[i]
4. compute m=sum/n and display m value
5. Call the sub program var(a,n,m)
6. End of subprogram
1. Start
2. if i<n then goto step 2.1 otherwise goto step 3
1. Start
2. compute s=sqrt(v)
3. display s value
4. end of sub program.
96
Flowchart
start
Read number of
elements in an array (n)
mean(a,n)
stop
Sum=0,t=0
F
i=0 i<n
i+
+
T
sum=sum+a[i]
m=sum/n
Display m value
var(a, n, m)
97
sub program var
F
i=0
i<n
i++
v=v+pow((a[i]-m),2)
Display v value
sd( v)
Sub program sd
void sd(int v)
Sd=sqrt(v)
Display s value
Program:
#include<math.h>
void mean(int a[],int);
void sd(int);
98
void var(int a[],int,int);
main()
{
int a[20],i,n,max,min;
printf("Enter size\n");
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
mean(a,n);
}
void mean(int a[],int n)
{
int i,sum=0,mean;
for(i=0;i<n;i++)
sum+=a[i];
mean=sum/n;
printf("mean result is %d",mean);
var(a,n,mean);
}
void var(int a[],int n,int m)
{
int i,varres=0;
for(i=0;i<n;i++)
varres+=pow((a[i]-m),2);
printf("var resulkt is %d",varres);
sd(varres);
}
void sd(int v)
{
float sdres;
sdres=sqrt(v);
printf("sd=%f",sdres);
}
Output:
1)
Enter size
5
Enter 5 elements10
20
30
40
50
mean result is 30
var resulkt is 1000
sd=31.622776
2)
99
Enter size
7
Enter 7 elements1 3 5 2 7 6 8
mean result is 4
var resulkt is 44
sd=6.633250
VIVA QUESTIONS:
1) What is a Mean?
2) What is a Standard deviation?
3) What is a Variance?
Description:
This programs sorts the given set of integers in ascending order. It takes the help of a
temporary variable for storing intermediate values.
Algorithm:
100
Step1: Start
Step2: Read n
Step3: initialize i=0
Step4: if i<n go to step5, otherwise go to step6
Step5: Read a[i], go to step4
Step6: initialize i=0
Step7: if i<n go to step8, otherwise go to step13
Step8: initialize j=0
Step9: if j<n go to step10, otherwise go to step12
Step10: if a[j]>a[j+1], otherwise go to step 11
i) temp=a[j];
ii) a[j]=a[j+1];
iii) a[j+1]=temp; go to step11
Step11: increment j, go to step9
Step12: increment i, go to step7
Step13: initialize i=0
Step14: if i<n go to step15, otherwise go to step16
Step15: Print a[i], go to step14
Step16: Stop
101
Flowchart:
Start
Read n
i=0 i++
false
i<n
true
Read a[i]
i=1 i++
i<n
false i<n
true
false
j=0 j<n-i
j++
j++
true
If false
a[i]>a[j
]+1]
true
temp=a[i]
a[i]=a[j]
a[j]=temp
i=0 i++
false i<n
true
Print a[i]
Stop
102
Program:
#include<stdio.h>
#include<conio.h>
void main() {
int arr[30], num, i;
bubble_sort(arr, num);
getch();
}
printf("\nUnsorted Data:");
for (k = 0; k < num; k++) {
printf("%5d", iarr[k]);
}
Output:
103
1)
Enter no of elements :5
9
4
7
Unsorted Data: 10 18 9 4 7
After pass 1 : 10 9 4 7 18
After pass 2 : 9 4 7 10 18
After pass 3 : 4 7 9 10 18
After pass 4 : 4 7 9 10 18
2)
Enter no of elements :8
Viva Questions:
8 c i a) Write a c Program that use recursive function to find the factorial of a given
integer.
104
Description:
Factorial of a number is nothing but the multiplication of numbers from a given number
to 1
Algorithm:
main program
Step 1: start
Step 2: read n
Step 3: call sub program
Step4: f=fact(n)
Step 5: print f value
Step 6: stop
Sub program:
Flowchart:
105
Start
Read n
Call subprogram
f = fact(n)
print f
Stop
Sub program
fact(int n)
false
n==0
true
Return 1 Return
n*fact(n-1)
Return to main
program
Program:
#include<stdio.h>
106
#include<conio.h>
int fact(int n)
{
int f;
if((n==0)||(n==1))
return 1;
else
f=n*fact(n-1);
return(f);
}
void main()
{
int n;
clrscr();
printf("enter the number :");
scanf("%d",&n);
printf("factorial of number %d is %d",n,fact(n));
getch();
}
Output:
1)
enter the number :5
factorial of number 5 is 120
2)
enter the number :9
factorial of number 9 is 362880
8 c i b) Write a c Program that use non recursive function to find the factorial of a given
integer.
Description:
107
Factorial of a number is nothing but the multiplication of numbers from a given number
to 1
Step 1: start
Step 2: read n
Step 3: call the sub program fact(n)
Step 4: print the f value
Step 5: stop
Sub program:
Flowchart:
108
start
Read n
Call subprogram
Fact(n)
Print F value
Stop
Subprogram Flowchart
Fact (int n)
Initialize F = 1
i= 1 i++
i<=n
false true
F=F*i
Return to main
program Return F
Program:
#include<stdio.h>
109
#include<conio.h>
long int f=1;
long int fact(int n)
{
int i;
if((n==0)||(n==1))
return 1;
else
{
for(i=n;i>=1;i--)
f*=i;
}
return(f);
}
void main()
{
int n;
clrscr();
printf("enter the number :");
scanf("%d",&n);
printf("factorial of number %d is %ld",n,fact(n));
getch();
}
Output:
1)
enter the number :11
factorial of number 11 is 39916800
2)
enter the number :7
factorial of number 7 is 5040
VIVA QUESTIONS:
8 c ii a) Write a c Program that use recursive function to find the GCD of two given
integers by using the recursive function
Description:
110
GCD means Greatest Common Divisor. i.e., the highest number which divides the
given number
Ex: GCD(12,24) is 12.Formulafor GCD is given by
GCD= product of numbers/ LCM of numbers
Algorithm:
1) For recursion:
Main program
Step 1: start
Step 2: read a,b
Step 3: call the sub program gcdrecursive(a,b) for print the value
Step 4: stop
Sub program:
Flowchart(for recursion):
111
Start
Read a,b
Stop
gcdrecursive( )
false true
If
n>m
true
F Return
gcdrecursive(n,m)
If
n==0
Return to main
program
Program:
#include<stdio.h>
112
int main()
{
int n1,n2,gcd,lcm;
clrscr();
printf("\nEnter two numbers: ");
scanf("%d %d",&n1,&n2);
gcd=findgcd(n1,n2);
printf("\nGCD of %d and %d is: %d",n1,n2,gcd);
return 0;
}
Output:
1. Enter two numbers: 250 150
VIVA QUESTIONS:
1) What is a function?
2) What is the GCD of 0, 10?Why?
3) What is the storage class used in this program?
113
8 c ii b) Write a c Program that use non recursive function to find the GCD of two given
integers by using the recursive function
Description:
GCD means Greatest Common Divisor. i.e the highest number which divides the given
number
Ex: GCD(12,24) is 12
Formula: GCD= product of numbers/ LCM of numbers
Algorithm:
Main program
Step 1: start
Step 2: read a,b
Step 3: call sub program g=GCD(a,b)
Step 4: print the g value
Step 5: stop
Sub program:
114
Flowchart:
start
Read a, b
Call subprogram
gcdnonrec(a,b)
Output g
stop
Subprogram Flowchart
gcdnonrec(m,n)
r=m%n
true false
r!=0
m=n, Return n
n=r,
r=m%n
Program:
115
#include<stdio.h>
int main(){
int n1,n2,gcd,lcm;
printf("\nEnter two numbers: ");
scanf("%d %d",&n1,&n2);
gcd=findgcd(n1,n2);
printf("\nGCD of %d and %d is: %d",n1,n2,gcd);
lcm=n1*n2/gcd;
printf("\nLCM of %d and %d is: %d",n1,n2,lcm);
return 0;
}
return n;
Output:
VIVA QUESTIONS:
116
8 c iii a) Write a c Program that use recursive function to generate fibonacci series.
Description
Algorithm:
main program
Step 1: start
Step 2: read range (n)
Step 3: : Initialize i=0
Step 4: repeat step 4.1, 4.2 until i<=n is true else goto step 5
Step 4.1: call the sub program fib(n) and then print the value
Step 4.2: i++
Step 5: stop
Sub program:
117
Flowchart:
Start
Read n
Stop
Sub program
fib(int
n)
false
n==1? n==2 ?
true
return 0 return 1 return fib(n-1)+fib(n-2)
Return to main
program
Program:
118
#include<stdio.h>
int Fibonacci(int);
main()
{
int n, i, c;
clrscr();
printf("Enter no of terms in fibonacci series");
scanf("%d",&n);
printf("Fibonacci series\n");
return 0;
}
int Fibonacci(int n)
{
if ( n == 0 || n == 1 )
return n;
else
return Fibonacci(n-1) + Fibonacci(n-2);
}
Output:
1)Enter no of terms in fibonacci series10
Fibonacci series
0 1 1 2 3 5 8 13 21 34
2)
Enter no of terms in fibonacci series20
Fibonacci series
0 1 1 2 3 5 8 13 21 34
55 89 144 233 377 610 987 1597 2584 4181
VIVA QUESTIONS:
8 c iii b) Write a c Program that use non recursive function to generate Fibonacci series.
Description
119
A Fibonacci series is defined as follows
The current term is calculated by adding the preceding two terms in the sequence
Step 1: start
Step 2: read range (n)
Step 3: : Initialize i=0
Step 4: repeat step 4.1, 4.2 until i<=n is true else goto step 5
Step 4.1: call the sub program fib(n) and then print the value
Step 4.2: i++
Step 5: stop
Algorithm subprogram :
Step 1: start
Step 2: initialize the a=0, b=1
Step 3: read n
Step 4: if n== 1 print a go to step 7. else goto step 5
Step 5: if n== 2 print a, b go to step 7 else print a,b
Step 6: initialize i=3
i) if i<= n do as follows. If not goto step 7
c=a+b
a=b
b=c
increment i value
goto step 6(i)
Step 7: return c
Step 8:stop
120
Flowchart:
Start
Read n
Stop
Sub program
fib(int
n)
false
n==1 n==2 ?
? Initialize a=0,b=1
true
return 0 return 1 I=0 i<n i++
c=a+b;
a=b;
b=c;
return to main
program
return c
121
Program:
#include<stdio.h>
int Fibonacci(int);
main()
{
int n, i,c;
clrscr();
scanf("%d",&n);
printf("Fibonacci series\n");
return 0;
}
int Fibonacci(int n)
{
int i,a=0,b=1,c;
if ( n == 0 || n==1)
return n;
else
{
for(i=2;i<=n;i++)
{
c=a+b;
a=b;
b=c;
}
}
return c;
}
Output:
1)
Fibonacci series
122
0 1 1 2 3 5 8 13 21 34
2)
Fibonacci series
0 1 1 2 3 5 8 13 21 34
VIVA QUESTIONS:
123
9 a) Write a c program to implement a structure to read and display the Name, date of Birth
and salary of ten employees.
Description:
Structure is a user defined data type available in C programming, which allows you to
combine data items of different kinds. Structures help to organize complex data in a
meaningful way.
Algorithm
1. Start.
2. Declare structure members with tag name emp
3. Read number of employees n
4. Read n employees information.(employee name ,date of birth, salary)
5. Display n employees information.( employee name ,date of birth, salary)
6. Stop
124
Flowchart
start
Read number of
employees (n)
i=0 i<n
i+
+
F T
Display n employees name,
date of birth , salary of
emp[i]
Stop
125
Program:
struct emp
{
char name[10];
int sal;
struct
{
int date,year;
char month[10];
}dob;
};
void main()
{
int i;
struct emp e[10];
for(i=0;i<10;i++)
{
printf("enter name sal,date,month,year of emp[%d]",i+1);
scanf("%s%d%d%s%d",e[i].name,&e[i].sal,&e[i].dob.date,e[i].dob.month,&e[i].dob.year);
}
for(i=0;i<10;i++)
{
printf("employee %d details\n",i+1);
printf("name:%s\nsal:%d\ndob:%d %s
%d\n",e[i].name,e[i].sal,e[i].dob.date,e[i].dob.month,e[i].dob.year);
}
getch();
}
Output:
126
23000
23
4
2010
enter name sal,date,month,year of emp[5]bhaskar
22000
12
3
1990
enter name sal,date,month,year of emp[6]satish
23000
23
4
1999
enter name sal,date,month,year of emp[7]gopi
20000
12
4
2000
enter name sal,date,month,year of emp[8]vinni
30000
12
4
2000
enter name sal,date,month,year of emp[9]mani
28000
23
5 2000
enter name sal,date,month,year of emp[10]harsha
30000
12
3
1998
Employee1 details
name: hari
sal: 20000
dob: 12 12 2014
employee 2 details
name: gopi
sal: 21000
dob: 12 4 2012
employee 3 details
name:
sal:
dob:
employee 4 details
name:
sal:
dob:
employee 5 details
127
name:bhaskar
sal:22000
dob:12 3 1990
employee 6 details
name:satish
sal:23000
dob:23 4 1999
employee 7 details
name:gopi
sal:20000
dob:12 4 2000
employee 8 details
name:vinni
sal:30000
dob:12 4 2000
employee 9 details
name:mani
sal:28000
dob:23 5 2000
employee 10 details
name:harsha
sal:30000
dob:12 3 1998
VIVA QUESTIONS:
1) What is a Structure?
2) Difference between Structure and Union?
3) How do you access Structure Members?
128
9 b) Write a c program to display the Name, Marks in five subjects and total marks of
given number of students. (Using array of structures).
Algorithm
1. Start.
2. Declare structure members with tag name
3. Read number of students n
4. Read n students information.(student name, marks in 5 subjects)
5. Display n students information.(student name, marks in 5 subjects)
6. Calculate total marks for each student
7. Display total marks for each student
8. Stop
129
Flowchart
start
Read number of
students (n)
i=0 i<n
i+
+
F T F
Display student name
j=0
j<n
j+
+
T
Display student marks in
5 subjects
Stop
Program
130
struct stu
{
char name[10];
int m1[5];
int tot;
}s[20];
main()
{
int n,i,j;
clrscr();
printf("Enter no of students");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\nEnter student %d name and five subjects marks details",i+1);
scanf("%s",s[i].name);
for(j=0;j<5;j++)
scanf("%d",&s[i].m1[j]);
}
for(i=0;i<n;i++)
{
printf("\nStudent Name%s\n",s[i].name);
printf("\n Marks in 5 subjects");
for(j=0;j<5;j++)
{
printf("%d\t",s[i].m1[j]);
s[i].tot+=s[i].m1[j];
}
printf("\nTotal=%d\n",s[i].tot);
}
getch();
}
Output
Marks in 5 subjects 45 67 89 34 67
Total=302
131
Student Name gopi
Marks in 5 subjects 56 89 67 98 45
Total=355
Marks in 5 subjects 45 67 89 67 97
Total=365
Enter no of students 1
Marks in 5 subjects 89 67 78 67 90
Total=391
Viva Questions:
1) What is the difference between arrays of structures and arrays within structures?
2) Explain about the “dot operator”?
3) Is nesting of structures possible? Justify.
9c) Write a C program to perform the following operations using Structure and
functions:
i) Reading a complex number
ii) Writing a complex number
iii) Addition of two complex numbers
132
iv) Multiplication of two complex numbers
Description:
In this program the complex number means it contains the two parts . first one is real part and
second one is imaginary part(2+3i).by taking these two complex numbers we can perform the
addition and multiplication operation.
133
Flow chart:
Start
Call subprogram
write(c1) c3.r=c1.r+c2.r;
c3.i=c1.i+c2.i ;
Display second complex number is
Call subprogram
write(c3)
Call subprogram write(c2)
return to main
write(c4)
Call subprogram mul(c1,c2)
return to main
Stop
Program:
134
struct comp
{
int r,i;
};
void write(struct comp);
void add(struct comp,struct comp);
void mul(struct comp,struct comp);
main()
{
struct comp c1,c2,c3;
clrscr();
printf("Enter first complex number");
scanf("%d %d",&c1.r,&c1.i);
printf("Enter second complex number");
scanf("%d %d",&c2.r,&c2.i);
printf("\nFirst complex number is");
write(c1);
printf("\n Second complex number is");
write(c2);
add(c1,c2);
mul(c1,c2);
getch();
}
void write(struct comp c1)
{
printf("\n%d+%di",c1.r,c1.i);
}
void add(struct comp c1,struct comp c2)
{
struct comp c3;
c3.r=c1.r+c2.r;
c3.i=c1.i+c2.i;
printf("\nAddition result is");
write(c3);
}
void mul(struct comp c1,struct comp c2)
{
struct comp c3;
c3.r=c1.r*c2.r-c1.i*c2.i;
c3.i=c1.r*c2.i+c1.i*c2.r;
printf("\nMultiplication result is");
write(c3);
}
Output:
1)
135
Enter first complex number2
3
Enter second complex number3
4
First complex number is
2+3i
Second complex number is
3+4i
Addition result is
5+7i
Multiplication result is
-6+17i
2)
Enter first complex number2
-2
Enter second complex number-8
-9
First complex number is
2+-2i
Second complex number is
-8+-9i
Addition result is
-6+-11i
Multiplication result is
-34+-2i
VIVA QUESTIONS:
1) Define structure?
2) What is use of <math.h> header file?
3) What is a matrix?
136
10 a) Write a C program to exchange (Swap) values of two integers using call by
reference.
Description
This program interchanges values of two variables using functions and sending addresses.
Algorithm:
Step 1 : Start
Step 2 : Read num1,num2.
Step 3 : Display before swapping num1,num2.
Step 4 : Calling swap function.
Step 5 : Display after swapping.
Step 6 : Stop
start
Swap(&num1,&
num2)
Flowchart:
After Swaping Print
num1,num2137
Stop
Subprogram:
temp=*a
*a=*b,
*b=temp
main()
Program
#include<stdio.h >
#include<conio.h>
void swap(int *a,int *b)
138
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}
void main()
{
int num1,num2;
clrscr();
printf("Enter 2 Numbers to Swap:");
scanf("%d%d",&num1,&num2);
printf("\nBefore Swapping: Two Numbers are:Num1=%d\tNum2=%d",num1,num2);
swap(&num1,&num2);
printf("\nAfter Swapping:\nTwo Numbers are:Num1=%d\tNum2=%d",num1,num2);
getch();
}
Output:
Enter 2 Numbers to Swap:10 20
Before Swapping:
Two Numbers are:Num1=10 Num2=20
After Swapping:
Two Numbers are:Num1=20 Num2=10
Enter 2 Numbers to Swap:55 66
Before Swapping:
Two Numbers are:Num1=55 Num2=66
After Swapping:
Two Numbers are:Num1=66 Num2=55
Viva Questions:
139
10 b i) Write a C program to illustrate the usage of dynamic memory management
function.(malloc)
Description:
Dynamic memory allocation allows a program to obtain more memory space, while
running or to release space when no space is required. C language supports allocation of
memory dynamically by using four library functions under "stdlib.h" for dynamic memory
allocation.
Algorithm
Step 1 : start
Step 2 : read n
Step 3 : allocate memory for n values of given type using malloc
Step 4 : assign 0 to i ,sum to 0
Step 5 : if(i<n) go to step 6 else go to step 8
Step 6 : read p+i value
Step 7 : compute i = i+1 goto step 5
Step 8 : assign 0 to i
Step 9: if(i<n) go to step 10 else go to step 13
Step 10 : display *(p+i), (p+i)
Step 11: compute sum=sum+*(p+i)
step 12: increment i go to step 9
Step 13: display sum
Step 14: free the memory
step 15 : Stop
140
Flowchart:
STAR
T
Read n
p=(int *) malloc(n*sizeof(int));
i=0 i++
false
i<n
true
Read (p+i)
i=0 i++
false
i<n
true
Print *(p+i), (p+i)
sum+=*(p+i)
Display sum
free(p)
Stop
141
free(a)
Stop
Program:
#include<stdio.h>
main()
{
int *p,n,i,sum=0;
printf("\n Enter size");
scanf("%d",&n);
p=((int *)calloc(n,sizeof(int)));
if(p==NULL)
{
printf(" No space");
exit(0);
}
printf("\n Enter %d elements",n);
for(i=0;i<n;i++)
scanf("%d",p+i);
printf("\n Element \t Address\n");
for(i=0;i<n;i++)
{
printf("\n %d\t %u",*(p+i),p+i);
sum+=*(p+i);
}
printf("%d",sum);
free(p);
}
142
Output:
1)
Enter size5
Enter 5 elements5
4
3
2
1
Element Address
5 3458
4 3460
3 3462
2 3464
1 3466
15
2)
Enter size8
Enter 8 elements12 3 5 1 7 9 23 54
Element Address
12 3458
3 3460
5 3462
1 3464
7 3466
9 3468
23 3470
54 3472
114
143
10 b ii) Write a C program to illustrate the usage of dynamic memory management
function. (realloc)
Algorithm
Step 1 : start
Step 2 : read n
Step 3 : allocate memory for n values of given type using malloc
Step 4 : assign 0 to i
Step 5 : if(i<n) go to step 6 else go to step 7
Step 6 : display p+i value goto step 5
Step 7: read new size n2
Step 8 : assign 0 to i
Step 9 : if(i<n2) go to step 10 else go to step 11
Step 10 : display p+i value
Step 11: free the memory
Step 12: Stop
Flowchart:
144
STAR
T
Read n
p=(int *) malloc(n*sizeof(int));
i=0 i++
false
i<n
true
display (p+i)
i=0 i++
false
i<n2
true
display (p+i)
free(p)
Stop
Program
#include<stdio.h>
145
free(a)
Stop
main()
{
int *p,n,n2,i;
printf("\n Enter size");
scanf("%d",&n);
p=(int *)malloc(n*sizeof(int));
if(p==NULL)
{
printf(" No space");
exit(0);
}
printf("\n previous addresses are");
for(i=0;i<n;i++)
printf("%u\t ",p+i);
printf("\n Enter new size");
scanf("%d",&n2);
p=(int *)realloc(p,n2);
printf("\n new addresses are\n");
for(i=0;i<n2;i++)
printf("%u\t",p+i);
free(p);
}
Output:
1)
Enter size5
previous addresses are3478 3480 3482 3484 3486
Enter new size10
new addresses are
3494 3496 3498 3500 3502 3504 3506 3508 3510 3512
2)
Enter size10
previous addresses are3478 3480 3482 3484 3486 3488 3490
3492 3494 3496
Enter new size6
new addresses are
3502 3504 3506 3508 3510 3512
Viva Questions:
146
Description:
In this program we have to use the file functions to perform the copy operation from
one file to another file.
Algorithm:
Step 1: Start
Step 2: read source file fname1, destination file fname2
Step 3: open source file in read mode
Step 4: open destination file in write mode
Step 5: if NULL pointer, then print unable to open files, go to step 8 otherwise go
to step6
Step 6: read a character from source file and write to destination file until EOF
Step 7: Close source file and destination file and print copied successfully
Step 8: Stop
Flowchart:
147
Start
Read destination
file fname2
fs=fopen(fname1,"r");
ft=fopen(fname2,"w");
if
false
fs==NULL ||
ft==NULL
false
if ch!=EOF
true
Print
Unable to open true
ch=fgetc(fs);
exit fputc(ch,ft);
fcloseall()
Stop
Program:
148
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fs,*ft;
char ch,fname1[20],fname2[20];
printf("\n enter sourse file name");
gets(fname1);
printf("\n enter dest file name");
gets(fname2);
fs=fopen(fname1,"r");
ft=fopen(fname2,"w");
if(fs==NULL||ft==NULL)
{
printf("unable to open");
exit(0);
}
do
{
ch=fgetc(fs);
fputc(ch,ft);
}while(ch!=EOF);
fcloseall();
printf("\nFile copy operation performed successfully");
}
OUTPUT:
enter sourse file name1.c
VIVA QUESTIONS:
149
10d) Write a C program to count the number of characters, words and lines in a file.
Description:
In this program, we have to count the number of lines, words and characters in a given program
or given text by using the string function. We check for conditions new line, empty space for
updating the above values.
Algorithm:
Step 1: Start
Step 2:initialize noc=0,now=0,nol=0.
Step 3: open file fname in read mode
Step 4: if fp is NULL, then print unable to open files, go to step 10 otherwise go
to step5
Step 5: read a character from file to c
Step 6: if c !=EOF then goto step 6.1otherwise go to step 7
6.1 increment noc by 1
6.2 if ch=’ ‘ or c=’\t’ then increment now by 1
6.3 if ch=\n the increment nol and now by 1
Step 7: increment nol and now by 1
Step 8:print the noc ,now and nol
Step 9:Close the file.
Step 10: Stop
start
Flowchart :
Initialize nol,now,noc to
0
fp=fopen(fname1,"r")
150
fp==NULL?
F
T
Unable to open the file
file
ch=fgetc(p)
ch!=EOF ?
noc++
ch ==’ ‘
|| \t’
T F
now++
F ch==’\n’ ?
T
nol++
now++
Display nol+1
Display now+1
Display noc
fclose(fp)
Program:
#include<stdio.h> stop
#include<conio.h>
void main()
{
int noc=0,now=0,nol=0;
151
FILE *fw,*fr;
char fname[20],ch;
clrscr();
printf("\n enter the source file name");
gets(fname);
fr=fopen(fname,"r");
if(fr==NULL)
{
printf("\n error \n");
exit(0);
}
do
{
ch=fgetc(fr);
noc++;
if(ch==' ')
now=1+now;
if(ch=='\n')
{
nol++;
now++;
}
}while(ch!=EOF);
fclose(fr);
printf("\n total no of character=%d",noc);
printf("\n total no of words=%d",now+1);
printf("\n total no of lines=%d",nol+1);
getch();
}
Output:
1)
enter the source file namea.c
total no of character=13
total no of words=1
total no of lines=1
2)
enter the source file namerealloc.c
total no of character=431
total no of words=50
total no of lines=25
VIVA QUESTIONS:
152