Sei sulla pagina 1di 40

GECR

PCD LAB

GOVERNMENT ENGINEERING COLLEGE


RAMANAGARA

Department of
Computer Science & Engineering

1stYEAR

PROGRAMMING IN C & DATA STRUCTURE


LABORATORY 15CPL16/26

--Prepared By

Chandan A S
Part Time Lecturer

GECR
1

GECR

PCD LAB

CONTENTS
DemonstrationofPersonalComputeranditsAccessories318

PART A

PART B

19 - 39

Solve the Quadratic equation (ax2+bx+c=0).

Find the reverse of an integer and check whether it is 21 - 22


PALINDROME or NOT.

19 - 20

Find the square root of a given number N without using 22 - 23


library function.

Read a year as an input and find whether it is leap year or 23 - 24


not

Evaluating
polynomial
f(x)=a4x4+a3x3+a2x2+a1x+a0,using Horners method.

To compute Sin(x) using Taylor series approximation and 25 - 26


Compare the result with the built- in Library

Reads N integer numbers and arrange them in ascending order 26 - 28


using Bubble Sort technique.

Reads two matrices


product A and B.

10

A(mxn)

and

B(pxq)

and

equation 24 - 25

Compute

the 28 - 30

De To search a Name in a list of names using Binary Search.

30 - 31

Sting copy operation .STRCOPY(str1,str2)without using


library function.

31 - 32

Read a sentence and prints frequency of each of the vowels


and total count of consonants.

C function to RightShift(x ,n) and print

Design and develop a C function isprime(num) function to


generate prime numbers between the given range.

32

33
33 - 34

11

Write a recursive C function to find the factorial of a 34 - 35


number.

12

Copy the content of files studentname.txt and usn.txt 35 - 37


into output file output.txt.

13

Write a C program to maintain a record of n student 37 - 38


details. Print the marks of the student given student name
as input.

14

Write a C program using pointers to compute the sum, mean 38 - 39


and standard deviation of all elements stored in an array
of n real numbers.

VIVA QUESTIONS

40

GECR

PCD LAB

PART-A
DemonstrationofPersonalComputeranditsAccessories
LaboratorySession1
Writeup on Functional block diagram of Computer, CPU, Buses, Mother Board,
Chipsets,OperatingSystem&typesofOS,BasicsofNetworking&Topologyand
NIC.
DescriptionaboutFunctionalblockdiagramofComputer:
Acomputerisanelectronicdevice,whichmainlyperformsthefourfunctions
as reading, processing, displaying and storing on data. These functions of a
computer system can be carried out by using the three main units namely input
unit,systemunitandoutputunit.
Theblockdiagramofacomputersystemisasfollows:

Fig1:BlockDiagramofaComputer

Notations:
DataandResultsflow

Controlinstructionstootherunitsfromcontrolunit
Instructionsfrommemoryunittocontrolunit

SystemorCentralProcessingUnit(CPU): iscommonlyknownasprocessorthat
executes the instructions of a computer program. It has Control Unit (CU) and
3

GECR

PCD LAB

Arithmetic & Logical Unit (ALU). These two units perform the basic arithmetic,
logical,andinput/outputoperations.
a)Inputunit: isusedtoenterdataandinformationintoacomputer.Thedevices
likekeyboard,mouseandscannerarecommonlyusedinputdevices.
Akeyboardisusedtoenteralphanumericcharactersandsymbols.
Themouseisusedtopickorselectacommandfromthemonitorscreen.
Ascannerisusedtoscananimageorreadabarcodeandsoon.
b)ArithmeticandLogicUnit(ALU):isadigitalcircuitthatperformarithmetic
(Add, Sub, Multiplication, Division) and logical (AND, OR, NOT) operations. It
helpsinfastcomputationofscientificcalculationsonfloatingpointnumber.

c) Control unit (CU): is the circuitry that controls the flow of information
throughtheprocessorandcoordinatestheactivitiesoftheotherunitswithinthe
processor.
FunctionsofControlunit
Accessingdata&instructionsfrommemoryunit
Interpretinginstructions
controllinginputandoutputunits
OverallsupervisionofaComputersystem
d)MemoryUnit(MU): istheunitwherealltheinputdataandresultsarestored
either temporarily or permanently. The CPU memory is also called as memory
register.Thememoryofacomputerhastwotypes:
a.MainMemory/PrimaryMemoryunits
i.RandomAccessMemory(RAM)
ii.ReadOnlyMemory(ROM)

b.SecondaryMemory/AuxiliaryMemory
e)OutputUnit: Itisusedtodisplayorprintresultsfromacomputer.Monitor,
printerandplottersarecommonlyusedoutputdevices.
f)Bus:Abusisacollectionofwiresthatcarriesdata/Instructions.Itconnects
physical components such as cables, printed circuits, CPU, Memory, Peripherals
etc.,forsharingofInformationandcommunicationwithoneanother.Thepurpose
ofbusesisto reducethenumber of"pathways"neededforcommunicationbetween
thecomponents,bycarryingoutallcommunicationsoverasingledatachannel.
TypesofBuses:
System Buses: The system buses are used to transfer the data and
instructionsbetweenMainmemory(RandomAccessMemory)andCPU.Theseare
classifiedintofollowingthreetypes.
DataBus

AddressBus

ControlBus

Itisusedtotransfer
thedatabetween
Processor,Memoryand
I/Odevices.

Itisusedtotransfer
theaddressesofdata
andinstructions
storedinmemory.

Itisusedtotransfer
thecontrolsignals
betweenCPU,Memoryand
I/Odevices.

GECR

PCD LAB
Bidirectionalin
nature

Unidirectionalin
nature

Unidirectionalor
Bidirectionalinnature

Fig2:TypesofBuses

I/OBuses: ThebuseswhichareusedtoconnectallI/OdeviceswithCPUand
MemoryarecalledI/Obuses.Theseareclassifiedintofollowingthreetypes.
PCIBus
PCIstandsfor
Peripheral
Component
Interconnect
Themotherboard
willbehaving3
or4PCI
connectors,so
thatwecaninsert
variouschips.
Fastestand
presentlymore
powerfulbus

ISABus
ISAstandsfor
IndustryStandard
Architecture

USBBus
USBstandsfor
UniversalSerial
Bus

Thisissimpleand
slowestbusused
inIBMPCs

Ithelpstoconnect
variousI/Odevices
likekeyboard,
mouse,pendrives,
printer,etc.

Oldest,simplest
andslowestbus

Newestandwidely
usedbus

MainBoardorMotherBoard:MotherBoardisasetofIntegratedChips(ICs)which
are designed to work together. It controls the flow of data/instructions within
our computer. It is the main board on which other hardware components are
connectedtoenablethecomputersystemtoworkasanintegratedunit.Itconsists
ofsockets,slots,powerconnectorsandbus.
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. The
chipsmaybecontrollersformemory,cache,harddrive,keyboardandperipherals.
OperatingSystemanditstypes:AnOperatingSystem(OS)isa
5

GECR

PCD LAB

systemsoftwarethatcontrolsandsupervisesthe
hardwarecomponentsofacomputersystemandit
provides the services to computer users. Also
calledasResourceManagerthatmanagesthe
resources such as CPU, Memory, I/O devices,
Job/Task/Process etc., a computer cannot run
withoutit.ThemajorfunctionsofOSincludes:
CPU Management, Memory Management, File
Management, Device Management, Process/Task/Job Management and Security
Management.
TheprimarygoalofanOSistomakethecomputersystemconvenientandefficient
touse.AnOSensuresthatthesystemresources(suchasCPU,memory,I/Odevices,
etc)areutilizedefficiently.Forexample,theremaybemanyprogramsresidingin
the main memory. Therefore, the system needs to determine which programs are
activeandwhichneedtowaitforsomeI/Ooperation.
SomeoftheexamplesofOperatingSystems:
WindowsXPisanO.S.isusedforPersonalComputers(PCs)
UnixandXENIXaretheOSsusedformultiusercomputers.
Windows7,Windows8,MacintoshOS,Fedora,andAndroid,etc.

Types of Operating Systems:The operating systems are classified into 7 types


basedontheircapabilityandusage.
TYPESOFOPERATINGSYSTEM

BATCH
SINGLE
SINGLEUSERMULTIUSER
MULTIREALVIRTUAL
PROCESSINGUSERMULTIMULTIPROCESSINGTIMEMACHINE
TASKINGSINGLETASKINGTASKING
TASKING
Fig3:TypesofOS

BatchProcessingTaskingOS: Thedataiscollectedintoagroupcalledbatch
andprovidesonlyonebatch(oneafteranother)ofjobsasinputtothecomputer
system at a time. The jobs in a batch are processed on first come first serve
basis. In this type, the process takes place at specified time intervals i.e.
weeklyormonthlywithoutuserinteraction.E.g.Punchcardswereusingtostore
the data in batch processing and in payroll preparation in a business batch
processingwashelpful.
Single user and single tasking OS: The OS that allows only one program to
execute at a time is called single user single tasking operating system. Using
this operating system user can do only one task at a time. E.g. DOS (Disk
OperatingSystem).
SingleuserandmultitaskingOS: TheOSthatallowsasingleusetoperform
morethanonetaskatatimeiscalledsingleusermultitaskingoperatingsystem.
6

GECR

PCD LAB

WhileworkingwiththeMsWordusercanperformotherworklikeprintadocument,
listenmusic.E.g.WindowsXP,WindowsVista,Windows7,etc.

MultiuserandmultitaskingOS:TheO.S.thatallowstwoormoreuserstousea
maincomputersystemtodomorethanonetaskiscalledmultiuserandmultitasking
operatingsystem.E.g.Unixisamultiuserandmultitaskingoperatingsystem.
Multiprocessing OS : The OS that allows multiple programs to be executed by
multipleCPUs(Processors)iscalledmultiprocessingoperatingsystem.Superand
mainframecomputershavemorethanoneCPUandmultiprocessingoperatingsystem.
Real Time Operating System (RTOS): The OS that is used for real time
applications and to carry out certain calculations within the specified time
constraint. This OS is used in applications such as mobile phones, supporting
systems in hospitals, nuclear power plants, oil refining, chemical processing,
environmental applications and airtraffic control systems, disaster management
etc.,
VirtualmachineOS: Allowsseveralusersofacomputersystemtooperateasif
eachhastheonlyterminalattachedtothecomputer.
BasicsofNetworking&TopologyandNetworkInterfaceCard(NIC):
IntroductiontoComputerNetwork:
A computer network is a collection of computers and devices interconnected to
facilitate sharing of resources among interconnected devices. Advantages of
Computer Networks include File Sharing, Resource Sharing, Increased Storage
Capacity,LoadSharingandFacilitatecommunications.
Computers in a network can be connected by using telephone lines, cables,
satellite links, etc., Wireless network will use radio signals to exchange the
information.

Basiccomponentsofacomputernetwork: Thebasiccomponentsofanetworkareas
follows.
1.Protocol:Setofrulesusedduringthedatatransmission.
2. Transmission Medium: The media used to connect computer to each other like
telephone lines, twisted pair wire, coaxial cable, fiber optics, satellite
signalsandradiosignals,etc.

GECR

PCD LAB

3.Processors: Modem,Multiplexers,bridges,routers,gateways,hubetc.arethe
processorsusedinthenetworkfortheflowofdata.
4. Channels: Analog/Digital, Synchronous/Asynchronous, Switched/Non switched,
Simplex/duplex,etc.
5. Topology: Physical network layout used for networking. For example, bus
topology,startopology,ringtopology,andmeshtopology
6.Software: UserinterfacesoftwarelikeInternetExplorer,NetscapeNavigator,
FTP (File Transfer Protocol), Telnet (Telecommunication Network), PPP (Point to
PointProtocol),andSMTP(SimpleMailTransferProtocol)etc.
TypesofNetworks:Thecomputernetworksaremainlyclassifiedinto3types
LAN
LocalAreaNetwork
Agroupofcomputers
thatareconnectedin
asmallareasuchas
building,home,office
etci.e.withina
smallcampus
Distancecoveredby
thisnetworkisless
than1KM
Usedwithinasingle
buildinglikehomeor
office
Computersare
connectedthroughthe
twistedpaircables
andcoaxialcables.
Transmittingdatais
cheaper
Transmissiondatais
generallyerrorfree

MAN

WAN

MetropolitanArea
Network
Anetworkwhichcovers
largearealikeacity

WideAreaNetwork

Distancecoveredby
thisnetworkis5to50
KM.
Usedbyprivate
organizationlikecable
televisioninourcity.
Anetworkdevicecalled
routerisusedto
connecttheLANs
together
Transmittingdatais
costlier
Transmissiondatais
generallyerrorprone

Distancecoveredby
thisnetworkis100to
1000KM
Usedalloverthe
world.i.e.good
exampleisinternet
Itusesfibreoptics,
cablesandeven
satellitesignalsasa
transmissionmedia.
Transmittingdatais
morecostlier
Transmissiondatais
generallyerrorfree

Anetworkwhichcovers
alargearealikea
state,countryor
acrossacontinent.

Network Topologies: Topology refers to the schematic


descriptionofthearrangementofanetwork.Itisthe
actual geometric layout of computers and other devices
connectedtothenetwork.
8

GECR

PCD LAB

TypesofNetworkTopologies:Thesearemainlyclassifiedinto4types.
1.BusTopology:
Inthisnetworkstructure,asinglecablerunsinabuildingorcampus.Allthe
nodes (terminals / computers)are connected to this single cable. It is suitable
forLocalAreaNetwork.
Advantages:
Failureofonenodewillnotaffectthewholenetwork.
Wellsuitedforquicksetup
Easytoinstallandexpand

Highrateofdatatransmissionascomparetostarandringtopology

Disadvantages:
Acablebreakcandisabletheentirenetwork
Troubleshoutingisverydifficult
Onlyasinglemessagecantravelatatime

2.RingTopology:
Inthisnetworkstructure,allthecomputersareconnectedtoeachother
intheformofaring.i.e.firstnodeisconnectedtosecond,secondto
thirdandsoon.Finallylastnodeisconnectedtofirstone.
Advantages:
Allthenodeshaveequalchancetotransferthedata
Theseareeasilyextensible
Itcanspanlongerdistancethanothertypeofnetworks
Disadvantages:
Difficulttoinstall
Expensive
Difficulttotroubleshoot
Addingorremovingcomputercandisturbtheentirenetwork

3.StarTopology:
In this network structure, all the computers are connected with a centralized
system called server. The central computer is also called a hub. To transmit
information from one node to another node, it should be transmitted through a
centralhub.Thecentralhubmanagesandcontrolsallthefunctionsofnetwork.
Advantages:
Easytoinstallandexpand.
Additionordeletionofanodeiseasier.
Failure of one node will not affect the entire
network.
Wellsuitedforquicksetup

Easiertodebugnetworkproblemsthroughahub
9

GECR

PCD LAB
Disadvantages:

Failureofacentralsystemi.e.hubwillaffectthewholenetwork
Costofhubisexpensive.
4.MeshTopology
In this network structure, all the computers and network devices are
interconnectedwithoneanotherlikeamesh.Everynodehasaconnectiontoevery
othernodeinthenetwork.Thistopologyisnotcommonlyusedfor
mostcomputernetworksbecauseofitsinstallationdifficultyandexpensive.
Advantages:
Failure of a single node will not affect the
entirenetwork
Data transfer rate is very fast because all the
nodesareconnectedtoeachother.
Disadvantages:
Installationandreconfigurationisverydifficult
Costlier

Hybrid Topology: Each of the topologies has their own


advantagesanddisadvantages.Sointherealworld,apure
start or pure ring or bus is rarely used. Rather a
combinationoftwoormoretopologiesisused.
Hence,hybridnetworktopologyusesacombinationofanytwoormore
topologiesinsuchawaythattheresultingnetworkdoesnotexhibitoneofthe
standardtopologies(e.g.,bus,star,ring,etc.).Twoverycommonlyusedhybrid
networktopologiesincludethestarringnetworkandstarbusnetwork.

Network Interface Cards (NICs): This is the important


hardware component, which connects the machine to the
computernetwork.Thiswillbefixedintooneofthefree
slot on the mother board. It has one port for the
connectionofanetworkcable.Thesecardstypicallyuse
an Ethernet connection and are available in 10, 100, and 1000 BaseT
configurations.A100BaseTcardcantransferdataat100Mbps.Thecardscomein
ISAandPCIversionsandaremadebycompanieslike3ComandLinkSys.
LaboratorySession2
WriteuponRAM,SDRAM,FLASHmemory,Harddisks,Opticalmedia,CDROM/R/RW,
DVDs, Flash drives, Keyboard, Mouse, Printers and Plotters.
Introductiontoflowchart,algorithmandpseudocode.
Random Access Memory (RAM): RAM is basically main memory of the
computer.
10

GECR

PCD LAB

RAMisasemiconductormemorymadeupofsmallmemorychipsthatforma
memorymodule.ThesemodulesareinstalledintheRAMslotsonthemotherboard
of computer. Every time you open a program, it gets loaded from the hard drive
into
the RAM. This is because reading data from the RAM is much faster than reading
datafromtheharddrive.

Synchronous Dynamic Random Access Memory (SDRAM): It is an improvement to


standard DRAM because it retrieves data alternately between two sets of memory.
Thiseliminatesthedelaycausedwhenonebankofmemoryaddressesisshutdown
whileanotherispreparedforreading.Itiscalled"Synchronous"DRAMbecausethe
memoryissynchronizedwiththeclockspeedthatthecomputer'sCPUbusspeedis
optimizedfor.Thefasterthebusspeed,thefastertheSDRAMcanbe.SDRAMspeed
ismeasuredinMegahertz.
FLASHmemory: FlashmemoryisatypeofElectricallyErasableProgrammableRead
OnlyMemory(EEPROM).Thenamecomesfromhowthememoryisdesignedasection
ofmemorycellscanbeerasedinasingleactionorina"flash.".Flashmemory
cards used for digital cameras, cellular phones, networking hardware, and PC
cards.
Harddisks: Harddiskisprimeunitofstorageofthecomputer.Hugeamountof
data can be stored and accessed in few milliseconds. The hard disk consists of
more number of disks arranged in the cylindrical order, one above another on a
spindle.
Theread/writeheadsareattachedtosingleaccessmechanismsothatthey
cannot move independently. All read/write heads are moved together to
position that heads on the required track. The hard disks available to
dayrangesfrom200GBto2TBandsoon.Thepresentdayharddiskranges
from3600rpmtomorethan10000rpmandsoon.
Advantages: Highstoragecapacity,highdataaccessingrateandpermanentstorage
medium.
Disadvantages:Itisnotportable.
Opticalmedia: Anopticalstoragemediaiskindofstorage,whichiscoatedwith
thinmetalonwhichbitsarestored.Thedatacanbestoredintoopticalstorage
mediaorreadformtheopticalstoragemedia.
Thedeviceswhichperformreadorwriteoperationonopticalstoragemediaare
calledopticalstoragemedia.
The laser technology is used to read the data or write the data on optical
storagedevices.
Examples:CDROM,DVDetc.

CompactDiscReadOnlyMemory(CDROM): Itisatypeofopticaldiscthatuses
laser technology to read and write data on the disc. The information stored on
CDROM becomes permanent and cannot be altered. This means that the stored
informationcanonlybereadforprocessing.
ACDROMusestheroundshapedopticaldisktostoredata,applications,gamesand
audiofiles.Itcanstoreupto700MBofdata.Ithasbecomeintegralpartof
11

GECR

PCD LAB
every organization due to its features like reliability, reasonable,
storagecapacityandeasytouseofcarry.
CDDrive will be with motor to rotate the disks to perform read and
writeoperations.ACDdrivewillconsistsofthecomponentslikeDisc
drive, disk drive motor, laser pick up assembly tracking drive and
trackingmotorandsoon.

CompactDiskRecordable(CDR): TheCDRallowsyoutocreateyourownCD.CDR
driveshavetheabilitytocreateCDsbuttheycan write dataon thediskonly
once.CDRtechnologyalsocalledasWriteOnceReadmuch(WORM)technology.Laser
technologyisusedtowritethedataonthecompactdisk.CDRdrivescomeinIDE,
SCSIandUSBmodels.
CompactDiscRewritable(CDRW): CDRWisanerasableopticaldiskwhichisused
towritedatamultipletimesonadisk,CDRWdisksaregoodfordatabackup,data
archiving or data distribution on CDs. The disk normally holds 700MB of data.
TechnologytowritedatamultipletimesonaCDwasknownasthePhasechangeDual
(PD)technology.ThereflectivepropertiesofaCDRWaredifferentthanregular
CDROMdisks.
DigitalVideoDiskorDigitalVersatileDisc(DVDROM):ADVDisasmalloptical
diskhavinghighdensitymediumandcapableofstoringafulllengthmovieona
singledisk.Thehighdensityisachievedbyusingbothsidesofthedisk,special
datacompressiontechnology,andextremelysmalltrackstostorethedata.
Advantages:StoragecapacityismorecomparedtoCDs.
Flash Drives (Pen drives): USB flash drives are removable, rewritable, and
physically much smaller drives weighing even less than 30 g. A flash drive
consistsofasmallprintedcircuitboardcarryingthecircuitelementsandaUSB
connector, insulated electrically and protected inside a plastic, metal, or
rubberizedcasewhichcanbecarriedinapocketoronakeychain.
Advantages:
Datastoredonflashdrivesisimpervioustoscratchesanddust
MechanicallyveryrobustEasilyportable
Havehigherdatacapacitythananyotherremovablemedia.
Comparedtoharddrives,flashdrivesuselittlepower
Flashdrivesaresmallandlightweightdevices
Flash drives can be used without installing device
drivers.

Disadvantages:
Can sustain only a limited number of write and erase cycles before the
drivefails.
Mostflashdrivesdonothaveawriteprotectmechanism
Flash drives are very small devices that can easily be misplaced, left
behind,orotherwiselost.
Thecostperunitofstorageinaflashdriveishigherthanthatofhard
disks

12

GECR

PCD LAB

Keyboard: Akeyboardistheprimaryinputdeviceusedinallcomputers.Keyboard
has a group of switches resembling the keys on an ordinary typewriter machine.
Normallykeyboardhasaround101keys.Thekeyboardincludeskeythatallowsusto
typeletters,numbersandvariousspecialsymbolssuchas*,/,[,%etc.
Mouse: ThemouseisthekeyinputdevicetobeusedinaGraphicalUserInterface
(GUI).Theuserscanusemousetohandlethecursorpointereasilyonthescreen
toperformvariousfunctionslikeopeningaprogramorfile.
With mouse, the users no longer need to memorize commands, which was earlier a
necessitywhenworkingwithtextbasedcommandlineenvironmentsuchasMSDOS.
Advantages:
Easytouse;Cheap;Canbeusedtoquicklyplacethecursoranywhereon
thescreen
Helpstoquicklyandeasilydrawfigures

Point and click capabilities makes it unnecessary to remember certain


commands

Disadvantages:
Needsextradeskspacetobeplacedandmovedeasily

Theballinthemechanicalmouseneedstobecleanedveryoftenforsmooth
movements

Printers:Theprinterisanoutputdevice,whichisusedtogethardcopyofthe
textdisplayedonthescreen.Theprinterisanexternaloptionaldevicethatis
connected to the computer system using cables. The printer driver software is
requiredtomaketheprinterworking.Theperformanceofaprinterismeasuredin
termsofDotsPerInch(DPI)andPagesPerMinute(PPM)producedbytheprinter.
TypesofPrinters:
1) Impact Printers: Impact printers are those printers in which a physical
contactisestablishedbetweentheprinthead,ribbon(cartridge)andpaper.E.g.
DotMatrixPrinters
2) NonImpact Printers: No physical contact is established between the print
head,ribbon(cartridge)andpaper.E.g.InkjetPrintersandLaserPrinter
Dotmatrix,InkjetandLaserprinters
Sl.No

DotMatrixPrinter

InkjetPrinter

LaserPrinter

ImpactPrinter

NonimpactPrinter

Nonimpactprinter

Itusesmetalpinsin
itsheadtocreate
textandgraphicsin
theformofdots.

Itsprintheaddoesnot
havemetalpins;instead
ithasseveraltiny
nozzlesthatsprayink
ontothepaper.Each
nozzleisthinnerthan
hair.

Thelaserprinter
usesabeamof
laserfor
printing.

13

GECR

PCD LAB

Theprocessof
printinginvolves
strikingapin
againstaribbonto
produceitsoutput.

Theinkcartridgesare
attachedtotheprinter
headthatmoves
horizontallyfromleftto
right.

Theprinterusesa
cylindricaldrum,
atonerandthe
laserbeam.

Printingspeedis
slowerthanlaser
printer,

Printingspeedisslower
thanlaserdotmatrix.

Printingspeedis
higherthanboth.

Characterby
characterprinting

Linebylineprinting

Itisapage
printer

Lowqualityprinting

Highqualityprinting

Highquality
printing

Lessexpensive

Highexpensive

Highexpensive

Generatesmuchnoise
whileprinting

Generateslessnoisewhile
printing

Nonoise

Speedismeasuredin
DPI(DotsPerInch)

SpeedismeasuredinCPI
(CharactersPerInch)

Speedismeasured
inPPM(PagesPer
Minute)

10

Monochrome(Black&
White)Printers

Colourprinter

Monochromeand
colourprinter

11

Plotters: A plotter is similar to printer that produces hardcopy


output with highquality colour graphics. Plotters are generally more
expensivethanprinters,rangingfromabout$1000to$75000.
ProblemSolvingTechniques:
Theprocessofworkingthroughdetailsofaproblemtoreachasolution.Thereare
threeapproachestoproblemsolving:
Algorithm
Flowchart
PseudoCode
Algorithm: Thealgorithmisa stepbystepprocedure tobefollowedinsolvinga
problem.Itprovidesaschemetosolveaparticularproblemin finitenumberof
unambiguoussteps.Ithelpsinimplementingthesolutionofaproblemusinganyof
theprogramminglanguages.
14

GECR

PCD LAB

Inordertoqualifyasanalgorithm,asequenceofinstructionsmustpossessthe
followingcharacteristics:
Definiteness: Instructionsmustbe precise and unambiguous i.e.eachandevery
instructionshouldbeclearandshouldhaveonlyonemeaning.

Finiteness: Not even a single instruction must be repeated infinitely. i.e.,


eachinstructionshouldbeperformedinfinitetime.
Termination: Afterthealgorithmgetsexecuted,theusershouldgetthedesired
result
Keyfeaturesofanalgorithm:
Anyalgorithmhasafinitenumberofstepsandsomestepsmayinvolvedecision
making, repetition. Broadly speaking, an algorithm exhibits three key features
thatcanbegivenas:
Sequence: Sequence means that each step of the algorithm is executed in the
specifiedorder.
Decision: Decisionstatementsareusedwhentheoutcomeoftheprocessdepends
onsomecondition.
Repetition: Repetitionwhichinvolvesexecutingoneormorestepsforanumber
of times can be implemented using constructs like the while, dowhile and for
loops.Theseloopsexecutedoneormorestepsuntilsomeconditionistrue.
Example:TocomputetheAreaofRectangle
ALGM: AREA_of_RECTANGLE [This algorithm takes length and breadth, the sides of
the rectangle as input and computes the area of rectangle using the formula
area=length*breadth.Finallyitprintstheareaofrectangle]
STEPS:
Step1:[Initialize]
Start
Step2:[InputthesidesofRectangle]
Readlength,breadth
Step3:[Computetheareaofrectangle]
Area length*breadth
Step4:[DisplaytheArea]
PrintArea
Step5:[Finished]
Stop
Flowcharts:Aflowchartisagraphicalorsymbolicrepresentationofanalgorithm.
Theyarebasicallyusedtodesignanddevelopcomplexprogramstohelptheusers
tovisualizethelogicoftheprogramsothattheycangainabetterunderstanding
oftheprogramandfindflaws,bottlenecks,andotherlessobviousfeatureswithin
it.Basically, a flowchart depictsthe flowof a program.Thefollowingtable
shows the symbols used in flowchart along with its descriptions.

15

GECR

PCD LAB
Symbol

Name

Description

oval

Representstheterminalpoint

Rectangle

Representstheprocessstepsdefinedin
algorithm

Parallelogram

IndicatethereadingOperationusedfor
input/outputordataorinformationfrom/to
anydevice

Diamond

Indicatesthedecisions(questions)and
consequentlythebranchpointsorthepaths
tobefollowedbasedontheresultofthe
question

Arrows

Showstheflowchartdirectionandconnects
thevariousflowchartsymbols

Smallcircle

Showsthecontinuationfromonepointinthe
processflowtoanother

Hexagon

RepresentsLoopingstructures

Predefined
Process

IndicatesSubroutines

AdvantagesofFlowcharts:
Aflowchartisadiagrammaticrepresentationthatillustratesthesequence
ofstepsthatmustbeperformedtosolveaproblem.Theyareusuallydrawnin
the early stages of formulating computer solutions to facilitate
communicationbetweenprogrammersandbusinesspeople.
Flowcharts help programmers to understand the logic of complicated and
lengthyproblems.
Theyhelptoanalyzetheprobleminamoreeffectivemanner
Flowchartcanbeusedtodebugprogramsthathaveerror(s).
E.g.:TocomputetheAreaofRectangle

LimitationsofusingFlowcharts:
Drawingflowchartsisalaboriousandatimeconsumingactivity.
Flowchart of a complex program becomes, complex and clumsy. At times, a
littlebitofalterationinthesolutionmayrequirecompleteredrawingof
theflowchart

16

GECR

PCD LAB

Essentialsofwhatisdonemaygetlostinthetechnicaldetailsofhowitis
done.

Therearenowelldefinedstandardsthatlimitsthedetailsthatmustbe
incorporatedinaflowchart
Start

Read length & breadth

Area = length * breadth

Print Area

Stop

Pseudocode: It is a form of structured English that describes algorithms. It


facilitatesthedesignerstofocusonthelogicofthealgorithmwithoutgetting
bogged down by the details of language syntax. Pseudocode is a compact and
informal highlevel description of an algorithm that uses the structural
conventionsofaprogramminglanguage.Itismeantforhumanreadingratherthan
machinereading,soitomitsthedetailsthatarenotessentialforhumans.Such
17

GECR

PCD LAB

details include keywords, variable declarations, systemspecific code and


subroutines.Therearenostandardsdefinedforwritinga pseudocode becauseit
is not an executable program. Flowcharts can be considered as a graphical
alternativetopseudocode,butaremorespaciousonpaper.
E.g.:TocomputetheareaofRectangle
Begin
Inputlength,breadth
Area=length*breadth
PrintArea
End

18

GECR

PCD LAB

PART B
Problem Solving in C - Implementation of the following problems with
WINDOWS / LINUX platform using appropriate C compiler.
1.Design and develop a flowchart or an algorithm that takes three coefficients
(a, b, and c) of a Quadratic equation (ax2+bx+c=0) as input and compute all
possible roots. Implement a C program for the developed flowchart/algorithm and
execute the same to output the possible roots for a given set of coefficients
with appropriate messages.
Algorithm
Step1.[inputthevaluesofa,b,c]
reada,b,c
Step2.[checkifaorbarezero]
if(a=0orb=0)

outputinvalidinput
gotostep7
Step3.[calculatethediscriminant]
d=b*b4ac
Step4.[findtwodistinctroots]
if(d>0)
r1=(b+sqrt(d))/2a
r2=(bsqrt(d))/2a
Outputr1andr2withsuitablemessage
gotostep7
Step5.[findtwoequalroots]if(d=0)
r1=r2=b/2a
Outputr1andr2withsuitablemessage
gotostep7
Step6.[findtwocomplexroots]
r1=b/2a
r2=sqrt(d)/2a
Outputr1andr2withsuitablemessage
Step7:Stop

Program
#include<stdio.h>
#include<conio.h>
#include<math.h>
voidmain()
{
floata,b,c;
floatd,x1,x2,r;
clrscr();
printf("Enterthethreecoefficients:\n");
scanf("%f%f%f",&a,&b,&c);
if(a*b*c==0)
printf("\nInvalidInput");
else

19

GECR

PCD LAB
{

d=b*b4*a*c;
r=sqrt(fabs(d));
if(d>0)
{
x1=(b+r)/(2.0*a);
x2=(br)/(2.0*a);
printf("\nTherootsarerealanddistinct\n");
printf("\nTherootsare\n1)x1=%f\t\t\n2)x2=%f",x1,x2);
}
elseif(d==0)
{
x1=x2=b/(2.0*a);
printf("\nTherootsarerealandequal\n");
printf("\nTherootsare:\n1)x1=x2=%f",x1);
}
else
{
x1=b/(2.0*a);
x2=r/(2.0*a);
printf("\nTherootsarerealandimaginary\n");
printf("\nTherootsare:\n1)%f+i%f\t\t\n2)%fi%f",x1,x2,x1,x2);
}
}
getch();
}

Output

Enterthethreecoefficient:
144
Therootsarerealandequal
Therootsare:
X1=X2=2.0000

Enterthethreecoefficient:
156
Therootsarerealanddistinct
Therootsare:
X1=3.0000
X2=2.0000

Enterthethreecoefficient:
234
TherootsarerealandimaginaryTherootsare:
1)0.750000+i1.198958
2)0.750000i1.198958
Enterthethreecoefficient:
105InvalidInput

----------------------------------------------------------------------------------------------------------------------------------

20

GECR

PCD LAB

2. Design and develop an algorithm to find the reverse of an integer number NUM
and check whether it is PALINDROME or NOT. Implement a C program for the
developed algorithm that takes an integer number as input and output the
reverse of the same with suitable messages. Ex: Num: 2014, Reverse: 4102, Not a
Palindrome
Algorithm
Step1.[inputthenumber]
Readnumber
Step2.[makeacopyofthenumber]
m=number
Step3.[initializethevalueofreverse]
reverse=0
Step4.[reversethegivennumber]
while(m!=0)
remain=m%10
m=m/10
reverse=reverse*10+remain;
endwhile
Step5.[checkifthegivennumberispalindrome]
if(number=reverse)
outputgivennumberispalindrome
else
outputgivennumberisnotpalindrome
endif
Step6.[finished]
Stop
Program
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
voidmain()
{
intn,rev=0,rem,m;
clrscr();
printf("Enteranumber:");
scanf("%d",&n);
m=n;
if(n<=999||n>9999)
{
printf("Nota4digitnumber\n");
exit(0);
}
while(n!=0)
{
rem=n%10;
n=n/10;
rev=rev*10+rem;
}
printf("Reverseofanumberis%d\n",rev);
if(m==rev)
printf("Thegivennumber%disPalindrome\n",m);
else
printf("Thegivennumber%disnotPalindrome\n",m);

21

GECR

PCD LAB
getch();
}

Output
Enteranumber:1221
Reverseofanumberis1221
Thegivennumber1221isPalindrome
Enteranumber:121
Nota4digitnumber
Enteranumber:1234
Reverseofanumberis4321ss
Thegivennumber1234isnotPalindrome

---------------------------------------------------------------------------------------------------------------------------------3a. Design and develop a flowchart to find the square root of a given number N.
Implement a C program for the same and execute for all possible inputs with
appropriate messages.
Note: Dont use library function sqrt(n).
Flowchart

Start

Read a number (N)


asqrt=N/2
Temp=0

False

IS
asqrt!=temp

True
temp=asqrt;
asqrt=(N/asqrt+asqrt)/2;

Print Area

22

Stop

GECR

PCD LAB
Program
#include<stdio.h>
#include<conio.h>
voidmain()
{
floatN,temp,asqrt;
clrscr();
printf("EnterthevalueofN\n");
scanf("%f",&N);
asqrt=N/2;
temp=0;
while(asqrt!=temp)
{
temp=asqrt;
asqrt=(N/asqrt+asqrt)/2;
}
printf("Thesquarerootof%fis%f\n",N,asqrt);
getch();
}

Output
EnterthevalueofN
25
Thesquarerootof25.000000is5.000000
EnterthevalueofN
12.3
Thesquarerootof12.300000is3.507136

---------------------------------------------------------------------------------------------------------------------------------3b. Design and develop a C program to read a year as an input and find whether
it is leap year or not. Also consider end of the centuries.
Flowchart

Is
year%400==0)||
(year%100!
=0&&year%4==0

True

False

NOT Leap Year

Leap Year

Leap Year

NOT Leap Year

23

GECR

PCD LAB
Program
#include<stdio.h>
#include<conio.h>
voidmain()
{
intyear;
clrscr();
printf("Enterayear:");
scanf("%d",&year);
if((year%400==0)||(year%100!=0&&year%4==0))
printf("%disaleapyear\n",year);
else
printf("%disnotaleapyear\n",year);
getch();
}
Output
Enterayear:2015
2015isnotaleapyear
Enterayear:2016
2016isaleapyear

---------------------------------------------------------------------------------------------------------------------------------4. Design and develop an algorithm for evaluating the polynomial


f(x)=a4x4+a3x3+a2x2+a1x+a0, for a given value of x and its coefficients using
Horners method. Implement a C program for the developed algorithm and execute
for different sets of values of coefficients and x.
Algorithm
Step1.[inputn]
Readn
Step2.[Inputncoefficients,startingfromnthcoefficientto0thcoefficient]
fori=ndownto0instep1
reada[i]
endfor
Step3.[inputthevalueofx]
readx
Step4.[initialize]
sum=0
Step5.[evaluatethepolynomialusinghornersmethod]
fori=ndownto0instep1
sum=(sum+a[i])*x
endfor
sum=sum+a[0]
Step6.[outputthevalueofthegivenpolynomialexpression]
outputresult
Step7.[finished]
Stop
Program
#include<stdio.h>
#include<conio.h>
voidmain()
24

GECR

PCD LAB
{
intn,i;
floatx,a[10],sum=0;
clrscr();
printf("EntertheThedegreeofpolynomial:");
scanf("%d",&n);
printf("Enterthe%dcoefficient\n",n+1);
for(i=n;i>=0;i)
scanf("%f",&a[i]);
printf("Enterthevalueofx:");
scanf("%f",&x);
for(i=n;i>0;i)
sum=(sum+a[i])*x;
sum=sum+a[0];
printf("Sumofthepolynomial=%f",sum);
getch();
}

Output
EntertheThedegreeofpolynomial:2
Enterthe3coefficient
246
Enterthevalueofx:2
Sumofthepolynomial=22.000000

---------------------------------------------------------------------------------------------------------------------------------5. Write C Program to compute Sin(x) using Taylor series approximation given by
Sin(x) = x - (x3/3!) + (x5/5!) - (x7/7!) + .
Compare the result with the built- in Library function and print both the
results.
Program
#include<stdio.h>
#include<conio.h>
#include<math.h>
intfact(intn)
{
inti,prod;
prod=1;
for(i=1;i<=n;i++)
prod=prod*i;
returnprod;
}
floattsin(floatx,intn)
{
inti;
floatsum;
sum=0;
for(i=1;i<=n;i+=2)
{
if((i1)%4==0)

25

GECR

PCD LAB
sum=sum+pow(x,i)/fact(i);
else
sum=sumpow(x,i)/fact(i);
}
returnsum;
}
voidmain()
{
intn;
floatx,rad,res;
clrscr();
printf("Enterthevalueofxandn\n");
scanf("%f%d",&x,&n);
rad=(x*3.142)/180;
res=tsin(rad,n);
printf("sin(%f)=%f\n",x,res);
printf("Usinglibraryfunction,sin(%f)=%f\n",x,sin(rad));
getch();
}

Output

Enterthedegreeandnumberofterms
90
3
sin(90)=0.925018
Usinglibraryfunctionsin(90)=1.000000
Enterthedegreeandnumberofterms
30
2
sin(30)=0.523333
Usinglibraryfunctionsin(30)=0.499770

---------------------------------------------------------------------------------------------------------------------------------6. Develop, implement and execute a C program that reads N integer numbers and
arrange them in ascending order using Bubble Sort technique.
Algorithm
Step1:
Step2:
Step3:
Step4:

[Initialize]Start
[Inputnumberofelements]
readn
[Inputunsortedelementsinarray]
readelementsinarraya[]
printelementsofarraya[]

Step5: [Iteratearray a[]intwoloops.Outerloopgivesnumberofpasses.


Innerloopdoesswaptask.Ineachpass,compareeachpairofadjacentitems.If
formerelementisgreaterthanlatterone,swapthem.]
[Iteratearraya[]with

26

GECR

PCD LAB

Step6:

foreachvalueiinarraya[i]tondo
foreachvaluejinarraya[j]ton1do
[Compareeachpairofadjacentelements]
if(a[j]>a[j+1])then
[Swaptheseelementsusingtempvariable]
tempa[j]
a[j]a[j+1]
a[j+1]temp
endif
endfor
endfor
Printarraywithsortedelements

Step7:

[Finished]End.

Program
#include<stdio.h>
#include<conio.h>
voidmain()
{
inta[50],n,i,j,temp=0;
clrscr();
printf("Enterthenumbersofelements:");
scanf("%d",&n);
printf("Enterthe%delements:\n",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("Thegivenarrayis:\n");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
for(i=1;i<n;i++)
{
for(j=0;j<ni;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
printf("\nThesortedarrayusingBubblesortis:\n");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
getch();
}

27

GECR

PCD LAB
Output
Enterthenumbersofelements:5
Enterthe5elements:
54321
Thegivenarrayis:
5
4
3
2
1

ThesortedarrayusingBubblesortis:
1
2
3
4
5

---------------------------------------------------------------------------------------------------------------------------------7. Develop, implement and execute a C program that reads two matrices A(mxn )
and B(pxq) and Compute the product A and B. Read matrix A in row major order
and matrix B in column major order. Print both the input matrices and resultant
matrix with suitable headings and in matrix format. Program must check the
compatibility of orders of the matrices for multiplication. Report appropriate
message in case of incompatibility.
Program
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
voidreadmatrix(inta[10][10],intm,intn)
{
inti,j;
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
}
voidwritematrix(inta[10][10],intm,intn)
{
inti,j;
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
printf("%d\t",a[i][j]);
printf("\n");
}
}
voidmulmatrix(inta[10][10],intb[10][10],intc[10][10],intm,intn,intp,intq)
{
inti,j,k,sum;
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
sum=0;
for(k=0;k<n;k++)
{
sum=sum+a[i][k]*b[k][j];
}
c[i][j]=sum;

28

GECR

PCD LAB
}
}
}
voidmain()
{
intm,n,p,q,a[10][10],b[10][10],c[10][10];
clrscr();
printf("EntertheorderofmatrixA\n");
scanf("%d%d",&m,&n);
printf("EntertheorderofmatrixB\n");
scanf("%d%d",&p,&q);
if(n!=p)
{
printf("MatrixAandBarenotmulticable\n");
exit(0);
}
printf("EntertheelementsofmatrixA\n");
readmatrix(a,m,n);
printf("EntertheelementsofmatrixB\n");
readmatrix(b,p,q);
mulmatrix(a,b,c,m,n,p,q);
printf("MatrixAis\n");
writematrix(a,m,n);
printf("MatrixBis\n");
writematrix(b,p,q);
printf("Theresultantmatrixis\n");
writematrix(c,m,q);
getch();
}

Output
EntertheorderofmatrixA
22
EntertheorderofmatrixB
22
EntertheelementsofmatrixA
12
34
EntertheelementsofmatrixB
23
45
MatrixAis
1
2

3
4

MatrixBis
2
3

4
5

Theresultantmatrixis
10
13

22
29

29

GECR

PCD LAB
EntertheorderofmatrixA
23
EntertheorderofmatrixB
23
MatrixAandBarenotmulticable

---------------------------------------------------------------------------------------------------------------------------------8. Develop,implement and execute a C program to search a Name in a list of names using Binary
Search.
Program
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<conio.h>
voidmain()
{
inti,n,low,high,mid;
chara[50][50],key[20];
clrscr();
printf("Enterthenumberofnames:");
scanf("%d",&n);
printf("Enterthenamesinascendingorder\n");
for(i=0;i<n;i++)
scanf("%s",a[i]);
printf("Enterthenametobesearched\n");
scanf("%s",key);
low=0;
high=n1;
while(low<=high)
{
mid=(low+high)/2;
if(strcmp(key,a[mid])==0)
{
printf("keyfoundattheposition%d\n",mid+1);
exit(0);
}
elseif(strcmp(key,a[mid])>0)
{
high=high;
low=mid+1;
}
else
{
low=low;
high=mid1;
}
}
printf("Namenotfound\n");
getch();
}

30

GECR

PCD LAB
Output
Enterthenumberofnames:5
Enterthenamesinascendingorder
Abhi
Brinda
Chethan
Dheeraj
Enrique
Enterthenametobesearched
Enrique
keyfoundattheposition5
Enterthenumberofnames:5
Enterthenamesinascendingorder
Abhi
Brinda
Chethan
Dheeraj
Enrique
Enterthenametobesearched
Raj
Namenotfound

---------------------------------------------------------------------------------------------------------------------------------9a.Write and execute a C program that implements string copy operation


STRCOPY(str1,str2) that copies a string str1 to another string str2 without
using library function.
Program
#include<stdio.h>
#include<string.h>
#include<conio.h>
voidSTRCPOY(charstr1[100],charstr2[100])
{
inti;
for(i=0;i<strlen(str1);i++)
if(str1[i]!='\0')
str2[i]=str1[i];
str2[i]='\0';
}
voidmain()
{
charstr1[100],str2[100];
clrscr();
printf("Enterthesourcestring\n");
scanf("%s",str1);
STRCPOY(str1,str2);
printf("AfterCopying,Destinationstring=%s\n",str2);
getch();
}

31

GECR

PCD LAB
Output
Enterthesourcestring
Programming
AfterCopying,Destinationstring=Programming

---------------------------------------------------------------------------------------------------------------------------------9b. Reads a sentence and prints frequency of each of the vowels and total
count of consonants.
Program
#include<stdio.h>
#include<string.h>
#include<ctype.h>
#include<conio.h>
voidmain()
{
charstr[100],ch;
intj,ac=0,ec=0,ic=0,oc=0,uc=0,cc=0;
clrscr();
printf("Enterthesentence\n");
gets(str);
for(j=0;j<strlen(str);j++)
{
if(isalpha(str[j]))
{
switch(ch=tolower(str[j]))
{
case'a':ac++;break;
case'e':ec++;break;
case'i':ic++;break;
case'o':oc++;break;
case'u':uc++;break;
default:cc++;

}
}
}
printf("\nFrequencyofvowela=%d",ac);
printf("\nFrequencyofvowele=%d",ec);
printf("\nFrequencyofvoweli=%d",ic);
printf("\nFrequencyofvowelo=%d",oc);
printf("\nFrequencyofvowelu=%d",uc);
printf("\nNumberofConsonants=%d\n",cc);
getch();
}
Output
Enterthesentence
Indiaismycountry
Frequencyofvowela=1
Frequencyofvowele=0
Frequencyofvoweli=3
Frequencyofvowelo=1
Frequencyofvowelu=1
NumberofConsonants=10

32

GECR

PCD LAB

10a. Design and develop a C function RightShift(x ,n) that takes two integers
x and n as input and returns value of the integer x rotated to the right by n
positions. Assume the integers are unsigned. Write a C program that invokes
this function with different values for x and n and tabulate the results with
suitable headings.
Program
#include<stdio.h>
#include<conio.h>
unsignedintrightshift(unsignedintx,intn);
voidmain()
{
unsignedintx;
unsignedintres;
intn;
clrscr();
printf("\nEnteranunsignedinteger<=65535\n");
scanf("%u",&x);
printf("\nRotate%uhowmanytimes:\n",x);
scanf("%d",&n);
res=rightshift(x,n);
printf("\nRightShift(%u,%d)=%u\n",x,n,res);
getch();
}
unsignedintrightshift(unsignedintx,intn)
{
inti;
for(i=1;i<=n;i++)
{

if(x%2==0)
x=x>>1;

else

{
x=x>>1;
x=x+32768;

}
}
returnx;
}

Output

Enteranunsignedinteger<=65535
10
Rotate10howmanytimes:
1
RightShift(10,1)=5

---------------------------------------------------------------------------------------------------------------------------------10 b. Design and develop a C function isprime(num) that accepts an integer


argument and returns 1 if the argument is prime, a 0 otherwise. Write a C
program that invokes this function to generate prime numbers between the given
range.
33

GECR

PCD LAB
Program
#include<stdio.h>
#include<conio.h>
intisprime(intm);
voidmain()
{
inti,n1,n2;
clrscr();
printf("EnteraRange\n");
scanf("%d%d",&n1,&n2);
printf("TheprimeNumbersbetween%dand%dare\n",n1,n2);
for(i=n1;i<=n2;i++)
if(isprime(i))
printf("%d\t",i);
getch();
}
intisprime(intm)
{
inti;
for(i=2;i<=m/2;i++)
if(m%i==0)
return0;
return1;
}

Output
EnteraRange
530
TheprimeNumbersbetween5and30are
5
7
11
13
17
19
23
29

---------------------------------------------------------------------------------------------------------------------------------11. Draw the flowchart and write a recursive C function to find the factorial
of a number, n!, defined by fact(n)=1, if n=0. Otherwise fact(n)=n*fact(n-1).
Using this function, write a C program to compute the binomial coefficient
(nCr). Tabulate the results for different values of n and r with suitable
messages.
Flowchart

fact(a)

Start

Read the value of n and r

ncr=fact(n)/((fact(nr))*(fact(r)))

True

IS
a==1
?

False

Print ncr
return 1

Stop
34

return a*fact(a1)

GECR

PCD LAB
Program
#include<stdio.h>
#include<conio.h>
longintfact(inta);
voidmain()
{
longintn,r,ncr;
clrscr();
printf("Enterthevaluesofnandr\n");
scanf("%ld%ld",&n,&r);
ncr=fact(n)/((fact(nr))*(fact(r)));
printf("ncr=%ld\n",ncr);
getch();
}
longintfact(inta)
{
if(a==0)
return1;
else
returna*fact(a1);
}

Output
Enterthevaluesofnandr
52
ncr=10

---------------------------------------------------------------------------------------------------------------------------------12. Given two university information files studentname.txt and usn.txt that
contains students Name and USN respectively. Write a C program to create a new
file called output.txt and copy the content of files studentname.txt and
usn.txt into output file in the sequence shown below. Display the contents of
output file output.txt on to the screen.
Program
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
voidmain()
{
FILE*fp1,*fp2,*fp3;
charch1,ch2;
clrscr();
fp1=fopen("studentname.txt","r");
if(fp1==NULL)
{
printf("studentname.txtnotfound\n");
exit(0);
}
fp2=fopen("usn.txt","r");
if(fp2==NULL)
{
printf("usn.txtnotfound\n");

35

GECR

PCD LAB
exit(0);
}
fp3=fopen("output.txt","w");
do
{
while((ch1=fgetc(fp1))!='\n')
{
if(ch1==EOF)
break;
else
fputc(ch1,fp3);
}
fputc('\t',fp3);
while((ch2=fgetc(fp2))!='\n')
{
if(ch2==EOF)
break;
else
fputc(ch2,fp3);
}
fputc('\n',fp3);
}while(ch1!=EOF||ch2!=EOF);
fclose(fp3);
fp3=fopen("output.txt","r");
printf("\n");
printf("NameUSN\n");
printf("\n");
while((ch1=fgetc(fp3))!=EOF)
printf("%c",ch1);
fclose(fp1);
fclose(fp2);
fclose(fp3);
getch();
}
studentname.txt

Arun
Kumar
Raj
Shashi
Tarun

usn.txt
1GG15CS001
1GG15CS011
1GG13CS027
1GG13CS031
1GG13CS032
36

GECR

PCD LAB
Output

NameUSN

Arun
1GG15CS001
Kumar 1GG15CS011
Raj
1GG13CS027
Shashi
1GG13CS031
Tarun 1GG13CS032

---------------------------------------------------------------------------------------------------------------------------------13. Write a C program to maintain a record of n student details using an


array of structures with four fields (Roll number, Name, Marks, and Grade).
Each field is of an appropriate data type. Print the marks of the student given
student name as input.
Program
#include<stdio.h>
#include<string.h>
#include<conio.h>
structstudent
{
introllno,marks;
charname[20],grade[1];
};
voidmain()
{
inti,n,found=0;
structstudents[10];
charsname[20];
clrscr();
printf("Enterthenumberofstudents:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\nEnterstudent%ddetails\n",i+1);
printf("Entertherollnumber:");
scanf("%d",&s[i].rollno);
printf("Enterthestudentname:");
scanf("%s",s[i].name);
printf("Enterthemarks:");
scanf("%d",&s[i].marks);
printf("Enterthegrade:");
scanf("%s",s[i].grade);
}
printf("\nStudentdetailsare\n");
printf("\nRollno\tName\t\t\tMarks\t\tGrade\n");
for(i=0;i<n;i++)
printf("%d\t%s\t\t\t%d\t\t%s\n",s[i].rollno,s[i].name,s[i].marks,
s[i].grade);
printf("\nEnterthestudentnametoprintthemarks:\n");
scanf("%s",sname);
for(i=0;i<n;i++)

37

GECR

PCD LAB
{
if(strcmp(s[i].name,sname)==0)
{
printf("\nMarksofthestudentis:%d\n",s[i].marks);
found=1;
}
}
if(found==0)
printf("studentnamenotfound\n");
getch();
}

Output
Enterthenumberofstudents:2
Enterstudent1details
Entertherollnumber:1
Enterthestudentname:Mohith
Enterthemarks:85
Enterthegrade:A
Enterstudent2details
Entertherollnumber:2
Enterthestudentname:Rahul
Enterthemarks:75
Enterthegrade:B
Studentdetailsare
Rollno
Name
1
Mohith
2
Rahul

Marks
85
75

Grade
A
B

Enterthestudentnametoprintthemarks:
Rahul
Marksofthestudentis:75

---------------------------------------------------------------------------------------------------------------------------------14. Write a C program using pointers to compute the sum, mean and standard
deviation of all elements stored in an array of n real numbers.
Program
#include<stdio.h>
#include<conio.h>
#include<math.h>
voidmain()
{
floata[10],*ptr,mean,std,sum=0,sumstd=0;
intn,i;
clrscr();

38

GECR

PCD LAB
printf("Enterthenoofelements\n");
scanf("%d",&n);
printf("Enterthearrayelements\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;
ptr=a;
for(i=0;i<n;i++)
{
sumstd=sumstd+pow((*ptrmean),2);
ptr++;
}
std=sqrt(sumstd/n);
printf("sum=%f\n",sum);
printf("Mean=%f\n",mean);
printf("standarddeviation=%f\n",std);
getch();
}

Output
Enterthenoofelements
5
Enterthearrayelements
12345
sum=15.000000
Mean=3.000000
standarddeviation=1.414214

----------------------------------------------------------------------------------------------------------------------------------

39

GECR

PCD LAB

VIVA QUESTIONS
1)Whatisanalgorithm?
2)Whatishighlevellanguage?
3)Whatiscompiler?
4)Whataretokens?
5)Whatareidentifiers?
6)Whatarekeywords?HowmanykeywordsistheirinCprogramminglanguage?
7)Whatisavariable?
8)Whataretherulestobefollowedwhiledeclaringavariable?
9)Whatisaconstant?
10)Whatisadatatype?Whatarethedifferentdataypes?
11)Whatareescapesequencecharacters?
12)Listthesizeandrangeofbasicdatatypes.
13)Whatisthedifferencebetweenacharacterandstring?
14)Whatisimplicittypeconversionandexplicittypeconversion(typecasting)?
15)Whatisprecedenceofanoperatormeans?
16)Whatisthedifferencebetweenprintf()andputs()functions.
17)Whatisfunction?Whataretheadvantagesoffunctions?
18)Whatarethedifferenttypesoffunctions?
19)Whatisalibraryfunction?
20)Whatiscallingfunctionandcalledfunction?
21)Whatisthemeaningofactualparameterandformalparameter?
22)Whatisthepurposeofswitchstatement?Explainwithsyntax.
23)Whatisloop?Listthedifferencesbetweenpretestandposttestloop.
24)Whatisthemeaningofeventcontrolledloopandcountercontrolledloop?
25)Whataretheadvantagesofloops?
26)Whatiscontrolstatement?Whatarethevarioustypesofcontrolstatements
availableinClanguage?
27)Explainforloopwithsyntax.
28)Whatisthedifferencebetweenwhileanddowhileloop?
29)Whatareunconditionalcontrolstatements?
30)Whatistheuseofbreakstatement?
31)Whatisanarray?Whatisthedifferencebetweenanordinaryvariableandan
arrayvariable?
32)Whatarethedifferencesbetweenrecursionanditeration?
33)Whatisapointer?
34)WhatisaNULLpointer?
35)WhatisaStructure?Whatarethedifferencesbetweenstructuresandarrays?
36)Whatismemoryleak?Whyitshouldbeavoided.
37) Which header file should be included to use functions like malloc() and
calloc()?
38)Liststring.hLibraryfunctionsinC.
39)Whatisthepurposeofmain()function?
40)WhatisthedifferencebetweenstaticanddynamicmemoryallocationinC?

---------------------------------------------------------------------------------------------------------------------------------THE END
40

Potrebbero piacerti anche