C PDF
C PDF
Ravi Kumar
II nd Semester
Course3:
UNIT-II
Control statements: Decision making statements: if, if else, else if ladder, switch
statements.Loopcontrolstatements:whileloop,forloopanddo-whileloop.Jump Control
statements: break, continue and goto.
UNIT-III
UNIT-IV
UNIT-V
DynamicMemoryManagement:Introduction,Functions-malloc,calloc,realloc,free
Structures:Basicsofstructure,structuremembers,accessingstructuremembers,nested
Designed by J.Ravi Kumar
structures,arrayofstructures,structureandfunctions,structuresandpointers. Unions-
Union definition; difference between Structures and Unions.
UNIT-I
Computer:isanelectronicdevicethatoperates(works)underthecontrolofprograms
stored in its own memory unit.
Acomputerisanelectronicmachinethatprocessesrawdatatogiveinformationas
output.
An electronic device that accepts data as input, and transforms it under
theinfluenceofasetofspecialinstructionscalledPrograms,toproducethedesiredoutp
ut (referred to as Information).
Explanations;
A computer is described as an electronic device because; it is made up
ofelectroniccomponentsanduseselectricenergy(suchaselectricity)tooperate.
A computer has an internal memory, which stores data & instructions temporarily
awaiting processing ,and even holds the intermediate result(information)beforeitis
communicated to the recipients through the Output devices.
Designed by J.Ravi Kumar
It works on the data using the instructions issued, means that, the
computercannotdoanyusefuljobonitsown.Itcanonlyworkasperthesetofinstructionsi
ssued.
Acomputerwillacceptdatainoneformandproduceitinanotherform.Thedatais
normally held within the computer as it is being processed.
Program:
A computer Program is a set of related instructions written in the language of
thecomputer&isusedtomakethecomputerperformaspecifictask(or,todirectthecomp
uter on what to do).
Asetofrelatedinstructionswhichspecifyhow thedataistobeprocessed.A set of
instructions used to guide a computer through a process.
Data:Isacollectionofrawfacts,figuresorinstructionsthatdonothavemuchmeaning to
the user.
Datamaybeinformofnumbers,alphabets/lettersorsymbols,andcanbeprocessed to
produce information.
TYPESOF DATA.
Therearetwotypes/formsof data:
a). Digital(discrete)data:
Digital data is discrete in nature. It must be represented in form of
numbers,alphabetsorsymbolsforittobeprocessedby
acomputer.Digitaldataisobtainedby counting. E.g. 1, 2, 3 …
b). Analogue(continuous)data:
Analoguedataiscontinuousinnature.Itmust berepresentedinphysicalnatureinorder
to be processed by the computer.Analogue data is obtained bymeasurement. E.g.
Pressure, Temperature, Humidity, Lengths or currents, etc.
DataProcessing:
Itistheprocessofcollectingallitemsofdatatogether&convertingthemintoinformation.
Information:isthedatawhichhasbeenrefined,summarized&manipulatedinthe way
you want it, or into a more meaningful form for decision-making.Theinformation
must be accurate, timely, complete and relevant.
Characteristics/Featuresofa Computer.
1. Speed : Computers have the ability to process so many millions (1,000,000) of
instructions per second. Computer operations are performed in micro and nano
seconds.
2. Diligence : A human cannot work for several hours without resting, yet a
computer never tires. A computer can conduct millions of calculations per
second with complete precision without stopping
Designed by J.Ravi Kumar
3. Reliability :A computer is reliable. The output results never differ unless the
input varies. the output is totally depend on the input. when an input is the
same the output will also be the same.
Programmingistheprocessofgivingmachinesasetofinstructionsthatdescribe how a
program should be carried out. Programmers will spend their whole careers
learning a variety of programming languages and tools so they can effectively
build computer programs.
Programmers will start by using a code editor or IDE to write what is called
sourcecode.Thisisacollectionofcodewritteninaprogramminglanguagethat other
programmers can read.
Thesecomputerprogramsallowustointeractivewithdifferentsoftwaredevices and
services like phones, websites, and the computers themselves.
• Input Unit
Designed by J.Ravi Kumar
• Output Unit
Input Unit
TheInputUnitconsistsofinputdevicessuchasamouse,keyboard,scanner,joystick,etc.
Thesedevicesareusedtoinputinformationorinstructionintothecomputersystem.Like
otherelectronicmachines,acomputertakesinputsasrawdata(binarydata)andperforms
necessary processing giving out processed data. Therefore, the input unit is the medium
of communication that takes data from us to the computer in an organized manner for
processing.
• The input unit converts the inputted data or instructions into binary form for further
processing.
• Input Unit transmits the data to the main memory of the computer.
CPU or Central Processing Unit is known as the brain of the computer system. It is an
electronic hardware device that processes all the operations (e.g., arithmetic and logical
operations) of the computer. In other words, all the major calculations, operations or
comparisons are performed inside the CPU. It is also responsible for handling the
operations of several other units.
Designed by J.Ravi Kumar
Intheabovediagram,theControlUnit(CU)andArithmetic&LogicUnit(ALU)arejointly called
the Central Processing Unit (CPU).
Let'sdiscussallthepartsdisplayedintheabovediagramonebyone:
ControlUnit
The control unit acts like the supervisor which determines the sequence in which
computerprogramsandinstructionsareexecuted.Itretrievesinstructionsfrommemory,
decodes the instructions, interprets the instructions and understands the sequence of
tasksto beperformedaccordingly.Itfurther transmitstheinstructionstothe otherparts of
the computer system to execute them. In short, the control unit determines the
sequence of operations to execute the given instructions.
Arithmetic&LogicUnit
The data inputted through input devices is stored in the primary storage unit. The
Arithmetic Logic Unit (ALU) performs arithmetic and logical operations.
Thearithmeticunitcontrolssimpleoperationssuchasaddition,subtraction,division,and
multiplication.
MemoryUnit
Therearetwotypesofmemoryunits:
PrimaryMemory
The primary memory cannot store avast amount of data. The datastoredin the primary
memory is temporary. The data will be lost if they are disconnected from the power
supply.Theprimarymemoryusuallystorestheinputdataandimmediatecalculation
Designed by J.Ravi Kumar
SecondaryMemory
The use of primary memory is not possible to store data permanently for future access.
Therefore, there are some other options to store the data permanently for future use,
whichisknownassecondarymemoryorauxiliarystorageorpermanentstorage.The data
stored in the secondary memory is safe even when there is a power failure or no power
supply. Hard Disk is usually considered a secondary memory.
3. FunctionalComponentsofaComputer
Computer: A computer is a combination of hardware and software resources which
integrate together and provides various functionalities to the user. Hardware are the
physical components of a computer like the processor, memory devices, monitor,
keyboardetc.whilesoftwareisthesetofprogramsorinstructionsthatarerequiredby the
hardware resources to function properly.
DetailsofFunctionalComponentsofaDigitalComputer
Input Unit :The input unit consists of input devices that are attached to the
computer. These devices take input and convert it into binary language that the
computerunderstands.Someofthecommoninputdevicesarekeyboard,mouse, joystick,
scanner etc.
• Central Processing Unit (CPU) : Once the information is entered into the computer
by the input device, the processor processes it. The CPU is called the brain of the
computerbecauseitisthecontrolcenterofthecomputer.Itfirstfetchesinstructions
frommemoryandtheninterpretsthemso astoknowwhatistobedone.Ifrequired, data is
fetched from memory or input device. Thereafter CPU executes or performs the
required computation and then either stores the output or displays on the output
device.
• Arithmetic and Logic Unit (ALU) : The ALU, as its name suggests performs
mathematicalcalculationsandtakeslogicaldecisions.Arithmeticcalculationsinclude
Designed by J.Ravi Kumar
4. ConceptsofHardwareandsoftware
Computer Hardware and Software, both are essential parts of a Computer System. In
short,Hardware andSoftwaremakeaSystemcompatiblewiththeuser.Inthisarticle,we are
going to discuss the basic differences between Computer Hardware and Computer
Software.
ComputerHardware
Hardware refers to the physical components of a computer. Computer Hardware is any
part of the computer that we can touch these parts. These are the primary electronic
devices used to build up the computer. Examples of hardware in a computer are the
Processor, Memory Devices, Monitor, Printer, Keyboard, Mouse, and Central Processing
Unit.
TypesofComputerHardware
• InputDevices
• OutputDevices
• Storage Devices
• InternalComponent
1. InputDevices:
InputDevicesarethosedevicesthroughwhichauserentersdataandinformation
intotheComputerorsimply,UserinteractswiththeComputer. Examples ofInput
Devices are Keyboard, Mouse, Scanner, etc.
2. OutputDevices:
OutputDevicesaredevicesthatareusedtoshowtheresultofthetaskperformed by the
user. Examples of Output Devices are Monitors, Printers, Speakers, etc.
Designed by J.Ravi Kumar
3. Storage Devices:
StorageDevicesaredevicesthatareusedforstoringdataandtheyarealsoknown
asSecondaryStorageData.ExamplesofStorageDevicesareCDs,DVDs,HardDisk, etc
4. InternalComponent:
Internal Components consists of important hardware devices present in the
System. Examples of Internal Components are the CPU, Motherboard, etc.
ComputerSoftware
TypesofComputerSoftware
• SystemSoftware
• ApplicationSoftware
1. SystemSoftware:
SystemSoftwareisacomponentofComputerSoftwarethatdirectlyoperateswith
Computer Hardware which has the work to control the Computer’s Internal
FunctioningandalsotakesresponsibilityforcontrollingHardwareDevicessuchas
Printers,StorageDevices,etc.TypesofSystemSoftwareincludeOperatingsystems,
Language processors, and Device Drivers.
2. ApplicationSoftware:
Application Software are the software that works the basic operations of the
computer. It performs a specific task for users. Application Software basically
includesWordProcessors,Spreadsheets,etc.TypesofApplicationsoftwareinclude
General Purpose Software, Customized Software, etc.
5. Typesofsoftwares
Software is a collection of instructions, data, or computer programs that are used to
run machines and carry out particular activities.
WhatisaSoftware?
In a computer system, the software is basically a set of instructions or commands that
tell a computer what to do. In other words, the software is a computer program that
provides a set of instructions to execute a user’s commands and tell the computer what
to do. For example like MS-Word,MS-Excel,PowerPoint, etc.
TypesofSoftware
It is a collection of data that is given to the computer to complete a particular task. The
chart below describes the types of software:
Designed by J.Ravi Kumar
Above is the diagram of types of software. Now we will briefly describe each type
andits subtypes:
1. SystemSoftware
• OperatingSystem
• LanguageProcessor
• DeviceDriver
2. ApplicationSoftware
• GeneralPurposeSoftware
• CustomizeSoftware
• UtilitySoftware
1.SystemSoftware
System softwareis software that directly operates the computer hardwareand
provides the basic functionality to the users as well as to the other software to
operate smoothly. Or in other words, system software basically controls acomputer’s
internal functioning and also controls hardware devices such as monitors, printers,
and storage devices, etc. It is like an interface between hardware and user
applications, it helps them to communicate with each other because hardware
understands machine language(i.e. 1 or 0) whereas user applications are work in
human-readable languages like English, Hindi, German, etc. so system software
converts the human-readable language into machine language and vice versa.
TypesofSystemSoftware
Ithastwosubtypeswhichare:
a) OperatingSystem:
It is the main program of a computer system. When the computer system ON it is
the first software that loads into the computer’s memory. Basically, it manages all
the resources such as computer memory,CPU,printer, hard disk, etc., and
Designed by J.Ravi Kumar
provides an interface to the user, which helps the user to interact with the
computer system. It also provides various services to other computer software.
Examples of operating systems are Linux, Apple macOS, Microsoft Windows, etc.
b) LanguageProcessor:
As we know that system software converts the human-readable language into a
machine language and vice versa. So, the conversion is done by the language
processor. It converts programs written in high-level programming
languageslike Java,C, C++,Python, etc(known as source code), into sets of
instructions that are easily readable by machines(known as object code or
machine code).
c) DeviceDriver:
A device driveris a program or software that controls a device and helps that
device to perform its functions. Every device like a printer, mouse, modem, etc.
needs a driver to connect with the computer system eternally. So, when you
connect a new device with your computer system, first you need to install the
driver of that device so that your operating system knows how to control or
manage that device.
2) ApplicationSoftware
Software that performs special functions or provides functions that are much more
than the basic operation of the computer is known as application software. Or in
other words, application software is designed to perform a specific task for end-
users. It is a product or a program that is designed only to fulfill end-users’
requirements. It includes word processors, spreadsheets, database management,
inventory, payroll programs, etc.
TypesofApplicationSoftware
Therearedifferenttypesofapplicationsoftwareandthoseare:
a) GeneralPurposeSoftware:
This type of application software is used for a variety of tasks and it is not
limited to performing a specific task only. For example, MS-Word, MS-Excel,
PowerPoint, etc.
b) CustomizedSoftware:
This type of application software is used or designed to perform specific tasks
or functions or designed for specific organizations. For example,
railwayreservation system, airline reservation system, invoice
management system, etc.
c) UtilitySoftware:
This type of application software is used to support the computer infrastructure.
Itisdesigned toanalyze,configure,optimizeandmaintainsthesystem,and take care
of its requirements as well. For example, antivirus,disk fragmenter,
Designed by J.Ravi Kumar
memory tester, disk repair, disk cleaners, registry cleaners, disk space
analyzer, etc.
6. Compilerandinterpreter
The Compiler and Interpreter, both have similar works to perform. Interpreters and
Compilers convert the Source Code (HLL) to Machine Code (understandable by
Computer). In general, computer programs exist in High-Level Language that a human
being can easily understand. But computers cannot understand the same high-level
language, so for computers, we have to convert them into machine language and make
themreadableforcomputers.Inthisarticle,wearegoingtoseethedifferencesbetween them.
Compiler
The Compileris a translator which takes input i.e., High-Level Language, and produces an
output of low-level language i.e. machine or assembly language. The work of a Compiler
is to transform the codes written in the programming language into machine code
(format of 0s and 1s) so that computers can understand.
• A compiler is more intelligent than an assemblerit checks all kinds of limits, ranges,
errors, etc.
• But its program runtimeis more and occupies alarger part of memory. It has aslow
speed because a compiler goes through the entire program and then translates the
entire program into machine codes.
RoleofaCompiler
For Converting the code written in a high-level language into machine-level languageso
that computers can easily understand, we use a compiler. Converts basically convert
high-level language to intermediate assembly language by a compiler and then
assembled into machine code by an assembler.
Designed by J.Ravi Kumar
AdvantagesofCompiler
• CompiledcoderunsfasterincomparisontoInterpretedcode.
• CompilershelpinimprovingthesecurityofApplications.
• AsCompilersgiveDebuggingtools,whichhelpinfixingerrorseasily.
DisadvantagesofCompiler
• Thecompilercancatchonlysyntaxerrorsandsomesemanticerrors.
• Compilationcantakemoretimeinthecaseofbulkycode.
Interpreter
An Interpreteris a program that translates a programming language into a
comprehensible language. The interpreter converts high-level language to an
intermediate language. It contains pre-compiled code, source code, etc.
• Ittranslatesonlyonestatementoftheprogramatatime.
• Interpreters,moreoftenthannotaresmallerthancompilers.
RoleofanInterpreter
The simple role of an interpreter is to translate the material into a target language. An
Interpreterworks line by line on a code. It also converts high-level language to
machinelanguage.
Interpreter
AdvantagesofInterpreter
• ProgramswritteninanInterpretedlanguageareeasiertodebug.
• Interpretersallowthemanagementofmemoryautomatically,whichreducesmemory
error risks.
• InterpretedLanguageismoreflexiblethanaCompiledlanguage.
Designed by J.Ravi Kumar
DisadvantagesofInterpreter
• TheinterpretercanrunonlythecorrespondingInterpretedprogram.
• InterpretedcoderunsslowerincomparisontoCompiledcode.
7) Concepts of Machine level, Assembly level and high-level
programming(concept of programming languages)
Each programming language contains a unique set of keywords and syntax, which are
used to create a set of instructions. Thousands of programming languages have been
developed till now, but each language has its specific purpose. These languages vary in
the level of abstraction they provide from the hardware. Some programming languages
providelessornoabstractionwhilesomeprovidehigherabstraction.Basedonthelevels of
abstraction, they can be classified into two categories:
o Low-levellanguage
o High-levellanguage
Theimagewhichisgivenbelowdescribestheabstractionlevelfromhardware.Aswecan
observe from the below image that the machine language provides no abstraction,
assembly language provides less abstraction whereas high-level language provides a
higher level of abstraction.
Designed by J.Ravi Kumar
Low-levellanguage
Thelow-levellanguageisaprogramminglanguagethatprovidesnoabstractionfromthe
hardware, and it is represented in 0 or 1 forms, which are the machine instructions. The
languages that come under this category are the Machine level language and Assembly
language.
Machine-levellanguage
Themachine-levellanguageisalanguagethatconsistsofasetofinstructionsthatarein the
binary form 0 or 1. As we know that computers can understand only machine
instructions, which are in binary digits, i.e., 0 and 1, so the instructions given to the
computercanbeonlyinbinarycodes.Creatingaprograminamachine-levellanguageis
averydifficulttaskasitisnoteasyfortheprogrammerstowritethe programinmachine
instructions. It is error-prone as it is not easy to understand, and its maintenance is also
very high. A machine-level language is not portable as each computer has its machine
instructions, so if we write a program in one computer will no longer be valid in another
computer.
Thedifferentprocessorarchitecturesusedifferentmachinecodes,forexample,aPowerPC
processor contains RISC architecture, which requires different code than intel x86
processor, which has a CISC architecture.
Assembly Language
The assembly language contains some human-readable commands such as mov, add,
sub, etc. The problems which we were facing in machine-level language are reduced to
some extent by using an extended form of machine-level language known as assembly
language. Since assembly language instructions are written in English words like mov,
add, sub, so it is easier to write and understand.
The assembly language code is not portable because the data is stored in computer
registers, and the computer has to know the different sets of registers.
computer.Thehigh-levellanguagesareconsideredashigh-levelbecausetheyarecloser to
human languages than machine-level languages.
When writing a program in a high-level language, then the whole attention needs to be
paid to the logic of the problem.
Acompilerisrequiredtotranslateahigh-levellanguageintoalow-level language.
8) FlowchartsandAlgorithms.
a) Flow charts
The Flowchart is the most widely used graphical representation of an algorithm and
procedural design workflows. It uses various symbols to show the operations and
decisions to be followed in a program. It flows in sequential order.
Flowchartsymbols:
ThevarioussymbolsusedinFlowchartDesignsaregivenbelow.
o Terminal Symbol: In the flowchart, it is represented with the help of a circle for
denoting the start and stop symbol. The symbol given below is used to represent
theterminalsymbol.
o Flow lines: It represents the exact sequence in which instructions are executed.
Arrowsareusedtorepresenttheflowlinesinaflowchart.Thesymbolgivenbelow is used
for representing the flow lines:
AdvantagesofFlowchartinC:
Followingarethevariousadvantagesofflowchart:
DisadvantagesofFlowchartinC:
Followingarethevariousdisadvantagesofflowchart:
o Time-consuming:Designingaflowchartisaverytime-consumingprocess.
o Complex:Itisn'teasytodrawaflowchartforlargeandcomplex programs.
o Thereisnostandard intheflowchart;thereisnostandardtodeterminethe quantity of
detail.
o Difficulttomodify: Itisverydifficulttomodifytheexistingflowchart.
Examplesofflowchart:
Designed by J.Ravi Kumar
b) Algorithms.
Algorithmisastep–by–stepprocedurewhichishelpfulinsolvingaCODE’. An
alagorithamhasa finitenumber ofstepsand somesteps mayinvolve decision-
making and repetition. Boardly speaking, an alagoritham exhibits three key
features, namely, sequence, decision, and repetition
Keyfeaturesofalgorithm
a)sequence
b)decision
c)repitation
a) Sequence:
sequencemenasthateachstepofthealagorithamisinthespecifiedorder.
Q:analagorithamtoaddtwo
numbers
Step:1: inputthefirsty
number as A
Step:2 inputthefirstynumberasB
Step:3 set C=A+ B
Step:4 printC
Step:5 end
b) Decision:
Decisionstatementsareusedwhenthe outcomeoftheprocessdependsonsome condition.
Q:analagorithamtotest theequalityoftwo numbers
Step:1inputthefirstynumberasA
Step:3if A = B
Then
print“equal”
else
PrintNotEqual“
Designed by J.Ravi Kumar
Step:4 end
Repetition : repetition, which involves executing one or more steps for a number
oftimes,canbeimplementedusingconstructssuchasthewhile,do-while,forloop. These
loops execute one or more steps until some condition is true.
Q:analagorithamtoprintthefirst 10natural numbers.
Step:1 [initilization]setI=0,N=10.
Step:3 print “ I”
Step:4 end
Featuresofthe algorithm
Itdefinesseveralimportantfeaturesofthealgorithm, including:
o Inputs:Algorithmsmustreceiveinputsthatcanberepresentedasvaluesordata.
o Output:Thealgorithmshouldproducesomeoutput.Itcanbeaconsequenceofa
problem or a solution designed to solve it.
o Clarity:Algorithmsmustbepreciselydefined,usingunambiguousinstructionsthat a
computer or other system can follow unambiguously.
o Finiteness:Thealgorithmrequiresalimitedsteps.Itmeansthatitshouldbeexited after
executing a certain number of commands.
o Validity:Thealgorithmmustbevalid.Inotherwords,itshouldbeabletoproduce a
solution to the problem that the algorithm is designed to solve in a reasonable
amount of time.
o Effectiveness: An algorithm must be effective, meaning that it must be able to
produce a solution to the problem it is designed to solve in a reasonable amount
of time.
o Generality: An algorithm must be general, meaning that it can be applied to a
wide range of problems rather than being specific to a single problem.
AdvantagesofAlgorithms:
• Itiseasytounderstand.
• Analgorithmisastep-wiserepresentationofasolutiontoagivenproblem.
Designed by J.Ravi Kumar
• In an Algorithm the problem is broken down into smaller pieces or steps hence, it
is easier for the programmer to convert it into an actual program.
DisadvantagesofAlgorithms:
• Writinganalgorithmtakesalongtimesoitistime-consuming.
• Understandingcomplexlogicthroughalgorithmscanbeverydifficult.
• BranchingandLoopingstatementsaredifficulttoshowinAlgorithms(imp).
FundamentalsofC
9. HistoryofC
• Cisoneofthehigh-levelprogramminglanguagesdevelopedbyDennisRitchie.
• C was originally developed for UNIX operating system to beat the issues of
previous languages such as B, BCPL, etc.
• The UNIX operating system development started in the year 1969, and its code
was rewritten in C in the year 1972.
• In 1985, Windows 1.0 was released. Even though Windows source code isn’t
publiclyavailableonthemarket,it’sbeenstatedthatitskernelismostlywrittenin C.
• In1991,Linuxkerneldevelopmentstarted,andit’sadditionallywritteninC.
• AfterayearitwasreleasedundertheGNUlicenseandwasusedaspartofthe
GNUOperatingSystem.
• The GNU operating system was started using C and Lisp programming
languages. So, many of its components are written in C.
• In1977,Oracledatabasedevelopmentstarted,andin1983itscodewasrewritten
fromassemblytoC.Itbecameoneinalltheforemostwidespreaddatabaseswithin the
world.
• Now a days C is exclusively used for building OS, application packages and
customized software. Because of its power and efficiency, it has gained more
popularity.
• C is increasingly used by system programmers, application developers and
researchers for a spread of programming tasks.
Itwasdevelopedtoovercometheproblemsof previouslanguagessuchasB,BCPL,etc.
Let'sseetheprogramminglanguagesthatweredevelopedbeforeC language.
10. FeaturesofC
Designed by J.Ravi Kumar
Cisthewidelyusedlanguage.Itprovidesmanyfeaturesthataregivenbelow.
1. Simple
2. MachineIndependentorPortable
3. Mid-levelprogramminglanguage
4. structuredprogramminglanguage
5. RichLibrary
6. MemoryManagement
7. FastSpeed
8. Pointers
9. Recursion
10. Extensible
1) Simple
2) MachineIndependentor Portable
3) Mid-levelprogramminglanguage
4) Structuredprogramminglanguage
C is a structured programming language in the sense thatwe can break the program
into parts using functions. So, it is easy to understand and modify. Functions also
provide code reusability.
5) RichLibrary
Cprovidesalotofinbuiltfunctionsthatmakethedevelopmentfast.
Designed by J.Ravi Kumar
6) MemoryManagement
It supports the feature of dynamic memory allocation. In C language, we can free the
allocated memory at any time by calling the free() function.
7) Speed
The compilation and execution time of C language is fast since there are lesser inbuilt
functions and hence the lesser overhead.
8) Pointer
Cprovidesthefeatureofpointers.Wecandirectlyinteractwiththememorybyusingthe
pointers. We can use pointers for memory, structures, functions, array, etc.
9) Recursion
InC,wecancallthefunctionwithinthefunction.Itprovidescodereusabilityforevery
function. Recursion enables us to use the approach of backtracking.
10) Extensible
Clanguageisextensiblebecauseitcaneasilyadoptnewfeatures.
CTokens
TokensinCisthemostimportantelementtobeusedincreatingaprograminC.Wecan define
the token as the smallest individual element in C. For `example, we cannot create
asentencewithoutusingwords;similarly,wecannotcreateaprograminCwithoutusing tokens
in C. Therefore, we can say that tokens in C is the building block or the basic component
for creating a program in C language.
ClassificationoftokensinC
TokensinClanguagecanbedividedintothefollowingcategories:
Designed by J.Ravi Kumar
o KeywordsinC
o IdentifiersinC
o StringsinC
o OperatorsinC
o ConstantinC
o SpecialCharactersinC
Let'sunderstandeachtokenonebyone.
11) KeywordsinC
do if static while
12) IdentifiersinC
IdentifiersinCareusedfornamingvariables,functions,arrays,structures,etc.Identifiers in C
are the user-defined words. It can be composed of uppercase letters, lowercase letters,
underscore, or digits, but the startinglettershouldbe either an underscore or an
alphabet. Identifiers cannot be used as keywords. Rules for constructing identifiers in C
are given below:
13) StringsinC
Strings in Care always represented as an array of characters having null character '\0' at
the end of the string. This null character denotes the end of the string. Strings in C are
enclosedwithindoublequotes,whilecharactersareenclosedwithinsinglecharacters.The size
of a string is a number of characters that the string contains.
Designed by J.Ravi Kumar
Now,wedescribethestringsindifferent ways:
chara[10]={'j','a','v','a','t','p','o','i','n','t','\0'};//Stringisrepresentedintheformofcharacters.
14) OperatorsinC
OperatorsinCisaspecialsymbolusedtoperformthefunctions.Thedataitemsonwhich the
operators are applied are known as operands. Operators are applied between the
operands. Depending on the number of operands, operators are classified as follows:
Unary Operator
A unary operator is an operator applied to the single operand. For example: increment
operator (++), decrement operator (--), sizeof, (type)*.
BinaryOperator
The binary operator is an operator applied between two operands. The following is the
list of the binary operators:
• ArithmeticOperators
• RelationalOperators
• LogicalOperators
• BitwiseOperators
• AssignmentOperators
• MiscOperators
Wewill,inthischapter,lookintothewayeachoperatorworks.
ArithmeticOperators
ThefollowingtableshowsallthearithmeticoperatorssupportedbytheClanguage. Assume
variable A holds 10 and variable B holds 20 then −
Example:
Designed by J.Ravi Kumar
+ Addstwooperands. A + B= 30
– Subtractssecondoperandfromthefirst. A − B=-10
/ Dividesnumeratorbyde-numerator. B/A = 2
ModulusOperatorandremainderofafteran integer
% B%A = 0
division.
Incrementoperatorincreasestheintegervalueby one.
++ A++=11
Decrementoperatordecreasestheintegervalue by
-- A-- =9
one.
RelationalOperators
ThefollowingtableshowsalltherelationaloperatorssupportedbyC.Assume variable
A holds 10 and variable B holds 20 then −
ShowExamples
Checksifthevalueofleftoperandisgreaterthanthe value
(A>B)isnot
> of right operand. If yes, then the condition becomes
true.
true.
Checksifthevalueofleftoperandislessthanthe value of
< right operand. If yes, then the condition becomes (A< B) istrue.
true.
Checksifthevalueofleftoperandisgreaterthanor equal
(A>=B)isnot
>= to the value of right operand. If yes, then the
true.
condition becomes true.
Checksifthevalueofleftoperandislessthanor
<= equaltothevalueofrightoperand.Ifyes,thenthe (A<= B) istrue.
condition becomes true.
LogicalOperators
FollowingtableshowsallthelogicaloperatorssupportedbyClanguage.Assume variable A
holds 1 and variable B holds 0, then −
ShowExamples
CalledLogicalNOTOperator. Itisusedtoreversethe
!(A&&B)
! logicalstateofitsoperand.Ifaconditionistrue,then
is true.
Logical NOT operator will make it false.
Designed by J.Ravi Kumar
BitwiseOperators
Bitwiseoperatorworksonbitsandperformbit-by-bitoperation.Thetruthtablesfor&,
|,and^isasfollows−
p q p &q p |q p ^q
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
AssumeA=60andB =13inbinaryformat,theywillbeasfollows−
A=00111100
B=00001101
A&B=0000 1100
A^B=0011 0001
ThefollowingtableliststhebitwiseoperatorssupportedbyC.Assumevariable'A'holds 60 and
variable 'B' holds 13, then −
Example:
(A|B)=61,i.e.,
| BinaryOROperatorcopiesabitifitexistsineither operand.
0011 1101
BinaryOne'sComplementOperatorisunaryandhastheeffect of (~A)=~(60),
~
'flipping' bits. i.e,.-0111101
AssignmentOperators
ThefollowingtableliststheassignmentoperatorssupportedbytheClanguage− Show
Examples
C = A + B will
Simpleassignmentoperator.Assignsvaluesfromrightside operands
= assignthevalue
to left side operand
of A + B to C
C += A is
AddANDassignmentoperator.Itaddstherightoperandtothe left
+= equivalenttoC
operand and assign the result to the left operand.
= C+ A
Designed by J.Ravi Kumar
DivideANDassignmentoperator.Itdividestheleftoperand with C /= A is
/= the right operand and assigns the result to the left operand. equivalenttoC
= C/A
C %= A is
ModulusANDassignmentoperator.Ittakesmodulususingtwo
%= equivalenttoC
operands and assigns the result to the left operand.
= C%A
C<<=2issame as
<<= LeftshiftANDassignmentoperator.
C = C << 2
C>>=2issame as
>>= RightshiftANDassignmentoperator.
C = C >> 2
C&=2issame as
&= BitwiseANDassignmentoperator.
C=C&2
C^=2issame as
^= BitwiseexclusiveORandassignmentoperator.
C=C^2
C|=2issameas C
|= BitwiseinclusiveORandassignmentoperator.
=C|2
MiscOperators↦sizeof&ternary
ShowExamples
sizeof(a),whereaisinteger,will
sizeof() Returnsthesizeof avariable.
return 4.
&a;returnstheactualaddressof the
& Returnstheaddressofavariable.
variable.
IfConditionistrue?thenvalueX:
?: ConditionalExpression.
otherwise value Y
15) ConstantsinC
Aconstantisavalueassignedtothevariable whichwillremainthesamethroughoutthe
program, i.e., the constant value cannot be changed.
TypesofconstantsinC
Constant Example
Hexadecimalconstant 0x1a,0x4b,0x6b,etc.
Characterconstant 'a','b','c',etc.
Designed by J.Ravi Kumar
Stringconstant "java","c++",".net",etc.
DefiningConstants
TherearetwosimplewaysinCtodefineconstants−
• Using#definepreprocessor.
• Usingconstkeyword.
The#definePreprocessor
Givenbelowistheformtouse#definepreprocessortodefineaconstant−
#defineidentifiervalue
Example
#include
<stdio.h>#defineLENG
TH10
#define WIDTH5
#defineNEWLINE'\n'in
t main() {
intarea;
area=LENGTH*WIDTH;
printf("valueofarea:%d",area); printf("%c",
NEWLINE);
return0;
}Output:
valueofarea:50
TheconstKeyword
Example
#include<stdio.h>i
nt main() {
constintLENGTH=10;
Designed by J.Ravi Kumar
const intWIDTH =
5;constcharNEWLINE='\n';
int area;
area=LENGTH*WIDTH;
printf("valueofarea:%d",area); printf("%c",
NEWLINE);
return0;
}
Output:
valueofarea:50
16) Specialcharactersin C
o Square brackets [ ]: The opening and closing brackets represent the single and
multidimensional subscripts.
o Simple brackets ( ): It is used in function declaration and function calling. For
example, printf() is a pre-defined function.
o Curlybraces{}:Itisusedintheopeningandclosingofthecode.Itisusedinthe opening
and closing of the loops.
o Comma(,): Itisusedforseparatingformorethanonestatementandforexample,
separating function parameters in a function call, separating the variable when
printing the value of more than one variable using a single printf statement.
o Hash/pre-processor(#):Itisusedforpre-processordirective.Itbasicallydenotes that
we are using the header file.
o Asterisk(*):Thissymbolisusedtorepresentpointersandalsousedasanoperator for
multiplication.
o Tilde(~):Itisusedasadestructortofree memory.
o Period(.):Itisusedtoaccessamemberof astructureoraunion.
17.Datatypesinc
Designed by J.Ravi Kumar
A data type specifies the type of data that a variable can store such as integer, floating,
character, etc.
TherearethefollowingdatatypesinClanguage.
Types DataTypes
DerivedDataType array,pointer,structure,union
EnumerationDataType enum
VoidDataType void
BasicData Types
The basic data types are integer-based and floating-point based. C language
supportsboth signed and unsigned literals.
Thememorysizeofthebasicdatatypesmaychangeaccordingto32or64-bitoperating system.
Let'sseethebasicdatatypes.Itssizeisgivenaccordingto32-bitarchitecture.
Designed by J.Ravi Kumar
float 4byte
double 8byte
longdouble 10 byte
Int:
Integersare entire numbers without any fractional or decimal parts, and the int datatype
is used to represent them.
It is frequently applied to variables that include values, such ascounts, indices, or other
numericalnumbers.The intdatatype mayrepresentboth positiveandnegative numbers
because it is signed by default.
Anint takes up4 bytesof memory on most devices, allowing it to store values between
around -2 billion and +2 billion.
Char:
Float:
To represent integers, use the floating data type. Floating numbers can be used to
represent fractional units or numbers with decimal places.
Thefloat typeis usually used for variables that require very good precision but may not
beveryprecise.Itcanstorevalueswithanaccuracyofabout6decimalplaces andarange of
about 3.4 x 1038 in 4 bytes of memory.
Double:
Use two data types to represent two floating integers. When additional precision is
needed, such as in scientific calculations or financial applications, it provides greater
accuracy compared to float.
Designed by J.Ravi Kumar
Double type, which uses8 bytesof memory and has an accuracy of about 15 decimal
places, yields larger values. C treats floating point numbers as doubles by default if no
explicit type is supplied.
18)VariableandRulesforconstructingvariablenames
Itisawaytorepresentmemorylocationthroughsymbolsothatitcanbeeasilyidentified.
Syntax:
typevariable_list;
Example:
int a;
floatb;
char c;
Here,a,b,carevariables.Theint,float,chararethedatatypes.
Wecanalsoprovidevalueswhiledeclaringthevariablesasgivenbelow:
inta=10,b=20;
float f=20.8;
char c='A';
Rulesfordefiningvariables
o Avariablecanhavealphabets,digits,andunderscore.
o Avariablenamecanstartwiththealphabet,andunderscoreonly.Itcan'tstartwith a digit.
o Nowhitespaceisallowedwithinthevariable name.
Designed by J.Ravi Kumar
o Avariablenamemustnotbeanyreservedwordorkeyword,e.g.int,float,etc.
Validvariablenames:
int a;
int_ab;
inta30;
Invalidvariablenames:
int 2;int
a b;
intlong;
TypesofVariablesinC
Therearemanytypesof variablesinc:
1. localvariable
2. globalvariable
3. staticvariable
4. automaticvariable
5. externalvariable
1) LocalVariable
Avariablethatisdeclaredinsidethefunctionorblockiscalledalocalvariable. It must
voidfunction1()
{
intx=10;//localvariable
}
Youmusthavetoinitializethelocalvariablebeforeitisused.
2) Global Variable
Designed by J.Ravi Kumar
A variable that is declared outside the function or block is called a global variable. Any
function can change the value of the global variable. It is available to all the functions.
Itmustbedeclaredatthestartofthe block.
intvalue=20;//globalvariable
void function1()
{
intx=10;//local variable
}
3) StaticVariable
Avariablethatisdeclaredwiththestatickeywordiscalledstaticvariable.Itretainsitsvalue
between multiple function calls.
voidfunction1()
{
intx=10;//local variable
staticinty=10;//staticvariable
x=x+1;
y=y+1;
printf("%d,%d",x,y);
}
Ifyoucallthisfunctionmanytimes,thelocalvariablewillprintthesamevalueforeach
functioncall,e.g,11,11,11andsoon.Butthe staticvariablewillprinttheincremented value
in each function call, e.g. 11, 12, 13 and so on.
4.AutomaticVariable
AllvariablesinCthataredeclaredinsidetheblock,areautomaticvariablesbydefault.We can
explicitly declare an automatic variable using auto keyword.
voidmain()
{
intx=10;//localvariable(also automatic)
autointy=20;//automaticvariable
Designed by J.Ravi Kumar
4) ExternalVariable
WecanshareavariableinmultipleCsourcefilesbyusinganexternalvariable.Todeclare an
external variable, you need to use extern keyword.
externintx=10;//externalvariable(alsoglobal) #include
"myfile.h"
#include<stdio.h>
voidprintValue()
{ printf("Globalvariable:%d",global_variable);
}
19. StructureofCprogram
The structure of a C program means the specific structure to start the programming in
the C language. Without a proper structure, it becomes difficult to analyze the problem
and the solution. It also gives us a reference to write more complex programs.
SectionsofaC program
ThesectionsofaCprogramarelistedbelow:
1. Documentationsection
2. Preprocessorsection
3. Definitionsection
4. Global declaration
5. Mainfunction
6. Userdefinedfunctions
1. Documentationsection
//nameofaprogramOr/*Overviewof thecode.*/
Designed by J.Ravi Kumar
2. Preprocessorsection
The preprocessor section contains all the header files used in a program. It informs the
system to link the header files to the system libraries. It is given by:
#include<stdio.h>
#include<conio.h>
3. Definesection
Thedefinesectioncomprisesofdifferentconstantsdeclaredusingthedefinekeyword.It is
given by:
#definea=2
4. Globaldeclaration
Theglobalsectioncomprisesofalltheglobaldeclarationsintheprogram.Itisgivenby:
Thesizeoftheaboveglobalvariablesislisted asfollows:
char=1byte,float=4bytes,int=4 bytes
Wecanalsodeclareuserdefinedfunctionsintheglobalvariablesection.
5. Mainfunction
main() is the first function to be executed by the computer. It is necessary for a code to
includethemain().ItislikeanyotherfunctionavailableintheClibrary.Parenthesis()are used for
passing parameters (if any) to a function.
return;Orreturnexpression; For
example,
return0;
Example:
/*Sumoftwonumbers*/
#include<stdio.h>
intmain(){
inta,b, sum;
printf("Entertwonumberstobeadded");
scanf("%d %d", &a, &b);
sum=a+b;
printf("%d+%d=%d", a,b, sum);
return0; }
Output:Entertwonumberstobeadded3,53+5=8
intmain() main()isthefirstfunctiontobeexecutedineveryprogram. We
have used int with the main() in order to return an integer
value.
Designed by J.Ravi Kumar
{… Thecurlybracesmarkthebeginningandendofafunction. It is
} mandatory in all the functions.
return0 Aprogramcanalsorunwithoutareturn0function.Itsimply
states that a program is free from error and can be
successfully exited.
20. Input/outputstatementsinC-FormattedandUnformattedI/O
Thisarticlefocusesondiscussingthefollowingtopicsindetail-
• FormattedI/OFunctions.
• Unformatted I/O Functions.
Formatted I/O Functions
Formatted I/O functionsare used to take various inputs from the user and display
multiple outputs to the user. These types of I/O functions can help to display the
output to the user in different formats using the format specifiers. These I/O supports
all data typeslike int, float, char, and many more.
Listofsomeformatspecifiers-
ThefollowingformattedI/Ofunctionswillbediscussedinthissection-
1. printf()
2. scanf()
3. sprintf()
4. sscanf()
1)printf():
Designed by J.Ravi Kumar
printf() functionis used in a C program to display any value like float, integer,
character, string, etc on the console screen. It is a pre-defined function that is already
declared in the stdio.h(header file).
Syntax:
printf(“FormatSpecifier”,var1,var2,….,varn);
Example:
printf(“%d”,a,b,……c);
2) scanf():
scanf() functionis used in the C program for reading or taking any value from the
keyboard by the user, these values can be of any data type like integer, float, character,
string, and many more. This function is declared in stdio.h(header file), that’s why it is
also a pre-defined function. In scanf() function we use &(address-of operator) which is
used to store the variable value on the memory location of that variable.
Syntax:
scanf(“FormatSpecifier”,&var1,&var2,….,&varn);
Example:
scanf(“%d”,&a,&b,……&c);
3.sprintf():
sprintfstands for “string print”. This function is similar to printf() function but this
function prints the string into a character array instead of printing it on the console
screen.
Syntax:
sprintf(array_name,“formatspecifier”,variable_name);
Example:
sprintf(array,“%d”,a);
4)sscanf():
sscanfstands for “string scanf”. This function is similar to scanf() function but this
function reads data from the string or character array instead of the console screen.
Syntax:
sscanf(array_name,“formatspecifier”,&variable_name);
Example:
sscanf(array,“%d”,&a);
UnformattedInput/Outputfunctions
Unformatted I/O functions are used only for character data type or character
array/string and cannot be used for any other datatype. These functions are used to
read single input from the user at the console and it allows to display the value at the
console.
ThefollowingunformattedI/Ofunctionswillbediscussedinthissection-
1. getch()
Designed by J.Ravi Kumar
2. getche()
3. getchar()
4. putchar()
5. gets()
6. puts()
7. putch()
1) getch():
getch()function reads a single character from the keyboard by the user but doesn’t
display that character on the console screen andimmediately returned withoutpressing
enter key. This function is declared in conio.h(header file). getch() is also used for hold
the screen.
Syntax:
getch();
or
variable-name=getch();
Example:
getch(ch);
or
ch=getch();
2) getche():
getche()function reads a single character from the keyboard by the user and displays it
on the console screen and immediately returns without pressing the enter key. This
function is declared in conio.h(header file).
Syntax:
getche();
or
variable_name=getche();
Example:
getche(g);
or
g= getche();
3) getchar():
The getchar()function is used to read only a first single character from the keyboard
whether multiple characters is typed by the user and this function reads one character
at one time until and unless the enter key is pressed. This function is declared in
stdio.h(header file)
Syntax:
Variable-name=getchar();
Example:
ch=getchar();
Designed by J.Ravi Kumar
4) putchar():
The putchar()function is used to display a single character at a time by passing that
character directly to it or by passing a variable that has already stored a character. This
function is declared in stdio.h(header file)
Syntax:
putchar(variable_name);
Example:
putchar(ch);
5) gets():
gets() function reads a group of characters or strings from the keyboard by the user
and these characters get stored in a character array. This function allows us to write
space-separated texts or strings. This function is declared in stdio.h(header file).
Syntax:
char str[length of string in number];
gets(str);
Example:
charstr[10];
gets(str);
6)puts():
In C programming puts()function is used to display a group of characters or strings
which is already stored in a character array. This function is declared in stdio.h(header
file).
Syntax:
puts(identifier_name);
Example:
puts(a);
7)putch():
putch() function is used to display a single character which is given by the user and
that character prints at the current cursor location. This function is declared in
conio.h(header file)
Syntax:
putch(variable_name);
Example:
putch(variable_name);
UNIT-II
Control statements: Decision making statements: if, if else, else if ladder, switch
statements.Loopcontrolstatements:whileloop,forloopanddo-whileloop.Jump Control
statements: break, continue and goto.
Designed by J.Ravi Kumar
1.Controlstatements(or)Decisionmakingstatements
Conditional statements help you to make a decision based on certain conditions. These
conditions are specified by a set of conditional statements having boolean expressions
which are evaluated to a boolean value of true or false.
Controlstatements(or)Decisionmakingstatementsareclassifiedinto3types
1)Branching(or)conditional statements
2)Iterative(or) looping statements
3)jumping statements
1)Branching(or)conditionalstatements
Thesestatementsagainclassifiedinto
a) Ifstatement
b) If-Elsestatement
c) NestedIfstatement
d) If-ElseIf ladder
e) Switchstatement
a)Ifstatement
Whether check the condition if the condition is satisfiedstatement part will get excuted.
Otherwise it will be terminated.
Syntax:
if(expression){
//codeto beexecuted
}
Designed by J.Ravi Kumar
ifStatementExample
#include<stdio.h>#in
clude<conio.h>void
main(){
intnum=0;
printf("enterthenumber");
scanf("%d",&num);
if(n%2==0){
printf("%dnumberineven",num);
getch();
b)If-elsestatement
Whetherchecktheconditioniftheconditionissatisfiedstatementpart-1willgetexcuted.
Otherwise statement part-2 will get excuted.
Syntax
if(expression){
//Statementspart-1
else{
//Statementspart-2
}
Designed by J.Ravi Kumar
if..elseStatementExample
#include<stdio.h>#include<conio
.h>
voidmain(){
int num=0;
printf("enterthenumber");
scanf("%d",&num);
if(n%2==0){
printf("%dnumberineven",num);} else{
printf("%dnumberinodd",num);}
getch();
Designed by J.Ravi Kumar
c)NestedIfstatement
Oneif blockintoaanotherifblockiscallednestedif-elsestatement.
Syntax
if(expression){
if(expression1){
statement-block1;
Example
#include<stdio.h>
#include<conio.h>
void main( )
inta,b,c;
clrscr();
printf("PleaseEnter3number");
scanf("%d%d%d",&a,&b,&c);
if(a>b)
if(a>c)
Designed by J.Ravi Kumar
printf("aisgreatest");
getch();
d) If..elseIfladder
The if-else-if statement is used to execute one code from multiple conditions. It is also
called a multipath decision statement. It is a chain of if..else statements in which each if
statementisassociatedwithanelseifstatementandthelastwouldbeanelsestatement.
Syntax
if(condition1){
//statements
}elseif(condition2)
//statements
elseif(condition3)
//statements
else
Designed by J.Ravi Kumar
//statements
If..elseIfladderExample
#include<stdio.h>#include<conio
.h>
voidmain()
int a;
printf("enteranumber");
scanf("%d",&a);
if(a%5==0&&a%8==0)
Designed by J.Ravi Kumar
printf("divisiblebyboth5and8");
elseif(a%8==0)
printf("divisibleby8");
elseif(a%5==0)
printf("divisibleby5");
else
printf("divisiblebynone");
getch();
e) SwitchStatement
switch statement acts as a substitute for a long if-else-if ladder that is used to test a list
ofcases.Aswitchstatementcontainsoneormorecaselabelsthataretested againstthe switch
expression. When the expression match to a case then the associated statements with
that case would be executed.
Syntax
Designed by J.Ravi Kumar
Switch(expression)
case value1:
//Statements
break;
casevalue2:
//Statements
break;
casevalue3:
//Statements
case value n:
//Statements
break;
Default:
//Statements
}
Designed by J.Ravi Kumar
switchstatementExample
#include<stdio.h>#include<conio
.h>
voidmain()
chargrade='B';
if(grade=='A')
Designed by J.Ravi Kumar
printf("Excellent!");
elseif(grade=='B')
printf("Welldone");
elseif(grade=='D')
printf("Youpassed");
elseif(grade=='F')
printf("Bettertryagain");
else
printf("YouFailed!");
getch();
Designed by J.Ravi Kumar
2)Iterative(or)loopingstatementsinc
Iterationisafundamentalconceptinprogrammingthatinvolvesrepeatingaspecificset
ofinstructionsmultipletimesuntilacertainconditionismet.InCprogramminglanguage, there
are three types of iteration statements:
i) forloop
ii)do-whileloop
i) ForLoop
Theforloopisusedtoexecuteasetofstatementsrepeatedlyforafixednumberoftimes.
Itconsistsofthreeparts:initialization,condition,andincrement/decrement.Thesyntaxof sthe
for loop is as follows:
Syntax:
for(initialization;condition;increment/decrement){
//codetobe executed
}
Theinitializationstatementisexecutedonlyonceatthebeginningoftheloop,anditis
usedtoinitializetheloopvariable.Theconditionstatementisevaluatedatthebeginning
ofeachiteration,andifitis true,thecodeinsidetheloopisexecuted.
Theincrement/decrementstatement is executed at the end of each iteration, and it is
used to update the loop variable.
#include<stdio.h>i
nt main() {
inti;
for (i=1;i<=10;i++){
Designed by J.Ravi Kumar
printf("%d\n",i);
}
return0;
}
Output:
1
2
3
4
5
6
7
8
9
10
Thewhileloopisusedtoexecuteasetofstatementsrepeatedlyaslongasacertain condition is
true. The syntax of the while loop is as follows:
Syntax:
while(condition){
//codetobe executed
}
Theconditionis evaluated at the beginning of each iteration, and if it is true, the code
inside the loop is executed. The loop continues until the condition becomes false.
#include<stdio.h>i
nt main() {
inti=1;
Designed by J.Ravi Kumar
while(i<=10){
printf("%d\n",i);
i++;
}
return0;
}
Output:
1
2
3
4
5
6
7
8
9
10
iii) Do-WhileLoop
do{
//codetobe executed
}while(condition);
The code inside the loop is executedfirst, and then the condition is checked. If the
condition is true, the loop continues, otherwise, it terminates.
Hereisanexampleof ado-whileloopthatprintsthenumbersfrom1to10:
Exampple:
Designed by J.Ravi Kumar
#include<stdio.h>i
nt main() {
inti=1;
do {
printf("%d\n",i);
i++;
}while(i<=10); return
0;
}
Output:
1
2
3
4
5
6
7
8
9
10
3) jumpingstatementsinc
In the C programming language, a jump statement is used to alter the normal flow of
executionofaprogram.Itallowstheprogramtotransfercontroltoadifferentpartofthe code,
such as a different function or a different block of code within the same function. There
are three types of jump statements in C:
i) goto
ii)break
iii)continue.
i) Gotostatement:
code difficult to read and understand. However, there are some events where they may
be useful, such as when implementing error handling.
Syntax:
gotolabel;
.
.
.
label:statement;
Thegotostatementtransferscontroltothelabeledstatement,whichisdefinedelsewhere in
the function.
Example:
#include<stdio.h>i
nt main() {
inti=1;
loop:
printf("%d",i);
i++;
if(i<=10){
goto loop;
}
return0;
}
Output:
12345678910
Explanation:
In this example, the program uses agoto statement to jump back to the loop label until
the condition is met.
ii) Breakstatement:
Designed by J.Ravi Kumar
Syntax:
while(condition){
if(condition){
break;
}
}
Example:
#include<stdio.h>i
nt main() {
inti;
for(i=1;i<=10;i++){ if (i
== 5) {
break;
}
printf("%d",i);
}
return0;
}
Output:
1234
In this example, the program uses the breakstatement to exit the loop early when iis
equal to 5.
iii) Continuestatement:
Thecontinue statementis utilized to skip the remaining code in a loop for the current
iteration and move on to the next iteration. It is commonly used in loops to skip over
certain elements.
Syntax:
Designed by J.Ravi Kumar
for(inti=0; i<n;i++) {
if(condition){
continue;
}
//Codetoexecuteif conditionisfalse
}
Example:
#include<stdio.h>i
nt main() {
inti;
for(i=1;i<=10;i++){ if (i
% 2 == 0) {
continue;
}
printf("%d",i);
}
return0;
}
Output:
13579
Explanation:
In this example, the program uses thecontinuestatement to skip over even numbers in
the loop and only print odd numbers.
UNIT-III
DeriveddatatypesinC
Designed by J.Ravi Kumar
1. OneDimensionalarrays-Declaration,InitializationandMemory
representation
Anarraywhichishavingtheonesubscriptiscalledonedimensionalarray
Wecandeclareanarrayintheclanguageinthefollowingway.
datatypearrayname[array_size];
intmarks[5];
Here,intisthedatatype,marksarethearrayname,and5isthearray_size. Initialization of
marks[0]=80;//initializationofarray
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;
Designed by J.Ravi Kumar
Example
#include<stdio.h>
intmain(){
inti=0;
int marks[5];//declaration of array
marks[0]=80;//initializationofarray
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;
for(i=0;i<5;i++){
printf("%d\n",marks[i]);
}
return0;
}
Output
80
60
70
85
75
Memoryrepresentationofonedimensionalarray
Each box represents the amount the memory needed to hold one array of elements.
Thepointersinitholdthememoryaddressoftheotherdata.They arerepresentedbya black
disk with an arrow to the referring data.
Letuswritecodeandrepresentthememoryof it.
inta [5];
.....
a[0]=1;
for (inti=1;i<5;i++)
a[i]=a[i-1]*2;
Thetwo-dimensionalarraycanbedefinedasanarrayofarrays.The2Darrayisorganized
asmatriceswhichcanberepresentedasthecollectionofrowsandcolumns.However,2D
arraysarecreatedtoimplementarelationaldatabaselookalikedatastructure.Itprovides
easeofholdingthebulkofdataatoncewhichcanbepassedtoanynumberoffunctions herever
required.
Anarraywhichishavingtwosubscriptsarecalledtwodimensionalarray Declaration of
Thesyntaxtodeclarethe2Darrayisgivenbelow. Data
following example.
inttwodimen[4][3];
Here,int is data type and twodimen is array name 4 is the number of rows, and 3 is the
number of columns.
Initializationof2DArrayinC
In the 1D array, we don't need to specify the size of the array if the declaration and
initialization are being done simultaneously. However, this will not work with 2D arrays.
We will have to define at least the second dimension of the array. The two-dimensional
array can be declared and defined in the following way.
intarr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
Two-dimensionalarrayexampleinC
#include<stdio.h>
intmain(){
inti=0,j=0;
intarr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};//declarationandinitializationof2darray
for(i=0;i<4;i++){
Designed by J.Ravi Kumar
for(j=0;j<3;j++){
printf("%d%d",arr[i][j]);
}
}
return0;
}
Output
arr[0][0]=1
arr[0][1]=2
arr[0][2]=3
arr[1][0]=2
arr[1][1]=3
arr[1][2]=4
arr[2][0]=3
arr[2][1]=4
arr[2][2]=5
arr[3][0]=4
arr[3][1]=5
arr[3][2]=6
Memoryrepresentationof2Darray
CalculatingtheMemoryAddressofanElement:
Toaccessaspecificelementina2-dimensionalarray,youneedtocalculateitsmemory address.
The formula to calculate the memory address of an element at row i and column j in a
2-dimensional array with rows and columns is:
Here,base_addressrepresentsthestartingmemoryaddressofthearray,element_sizeis the
size (in bytes) of each element, and i and j are the indices of the row and column,
respectively.
Designed by J.Ravi Kumar
ExampleofMemoryMapof a2-DimensionalIntegerArray:
Let’sconsidera2-dimensionalarrayof integerswith3rowsand4columns:
intarray[3][4];
array[2][1]-->address10
array[2][2]-->address11
array[2][3]-->address12
Strings
3)Declaring&initializingstringvariables
Designed by J.Ravi Kumar
thestringcanbedefinedastheone-dimensionalarrayofcharactersterminatedbyanull ('\0').
The character array or the string is used to manipulate text such as word or
sentences.Eachcharacterinthearrayoccupiesonebyteofmemory,andthelastcharacter must
always be 0. The termination character ('\0') is important in a string since it is the only
way to identify where the string ends. When we define a string as char s[10], the
character s[10] is implicitly initialized with the null in the memory.
Therearetwowaysto declareastringinclanguage.
1. Bychararray
2. Bystringliteral
1. Bychararray
charch[10]={'j','a','v','a','t','p','o','i','n','t','\0'};
As we know, array index starts from 0, so it will be represented as in the figure given
below.
While declaring string, size is not mandatory. So we can write the above code as given
below:
charch[]={'j','a','v','a','t','p','o','i','n','t','\0'};
2. By string literal
charch[]="javatpoint";
Insuchcase,'\0'willbeappendedattheendofthestringbythe compiler.
Differencebetweenchararrayandstringliteral
Therearetwomaindifferencesbetweenchararrayandliteral.
o We need to add the null character '\0' at the end of the array by ourself whereas,
it is appended internally by the compiler in the case of the character array.
Designed by J.Ravi Kumar
StringExampleinC
Let's see a simple example where a string is declared and being printed. The '%s' is used
as a format specifier for the string in c language.
#include<stdio.h>#
include<string.h>i
nt main(){
charch[11]={'j','a','v','a','t','p','o','i','n','t','\0'};
char ch2[11]="javatpoint";
printf("CharArrayValueis:%s\n",ch);
printf("StringLiteralValueis:%s\n", ch2);
return0;
}
Output
4.Stringhandlingfunctions(or)operations(or)manipulationsinc
Therearemanyimportantstringfunctionsdefinedin"string.h"library.
2) strcpy(destination,source) copiesthecontentsofsourcestringtodestinationstring.
3) strcat(first_string,second_strin concats or joins first string with second string. The result of th
g) string is stored in first string.
Designed by J.Ravi Kumar
4) strcmp(first_string,second_stri compares the first string with second string. If both strings
ng) asame, it returns 0.
5) strrev(string) returnsreversestring.
6) strlwr(string) returnsstringcharactersinlowercase.
7) strupr(string) returnsstringcharactersinuppercase.
1)StringLength:strlen()function
Example:
#include<stdio.h>#
include<string.h>i
nt main(){
charch[20]={'j','a','v','a','t','p','o','i','n','t','\0'};
printf("Lengthofstringis:%d",strlen(ch));
return 0;
}
Output:
Lengthofstringis:10
2. CopyString:strcpy()
Thestrcpy(destination,source)functioncopiesthesourcestringindestination.
Example:
#include<stdio.h>#
include<string.h>i
nt main(){
charch[20]={'j', 'a', 'v', 'a','t','p', 'o','i', 'n', 't', '\0'};
Designed by J.Ravi Kumar
char ch2[20];
strcpy(ch2,ch);
printf("Valueofsecondstringis:%s",ch2);
return 0;
}
Output:
Valueofsecondstringis:javatpoint
3. StringConcatenation:strcat()
Thestrcat(first_string,second_string)functionconcatenatestwostringsandresultis returned
to first_string.
Example:
#include<stdio.h>#
include<string.h>i
nt main(){
charch[10]={'h','e','l','l','o','\0'};
char ch2[10]={'c', '\0'};
strcat(ch,ch2);
printf("Valueoffirststringis:%s",ch); return
0;
}
Output:
Valueoffirststringis: helloc
4. CompareString:strcmp()
Thestrcmp(first_string,second_string)functioncomparestwostringandreturns0ifboth
strings are equal.
Here,weareusinggets()functionwhichreadsstringfromthe console.
Example:
Designed by J.Ravi Kumar
#include<stdio.h>#
include<string.h>i
nt main(){
char str1[20],str2[20];
printf("Enter1ststring:");
gets(str1);//readsstringfromconsole
printf("Enter 2nd string: ");gets(str2);
if(strcmp(str1,str2)==0)
printf("Stringsareequal");
else
printf("Stringsarenotequal"); return
0;
}
Output:
The strrev(string) function returns reverse of the given string. Let's see a simple example
of strrev() function.
Example:
#include<stdio.h>#
include<string.h>i
nt main(){
char str[20];
printf("Enterstring:");
gets(str);//reads string from console
printf("String is:
%s",str);printf("\nReverseStringis:%s",strre
v(str));
return0;
Designed by J.Ravi Kumar
Output:
Enterstring:javatpoint
String is: javatpoint
ReverseStringis: tnioptavaj
6. StringLowercase:strlwr()
Thestrlwr(string)functionreturnsstringcharactersinlowercase.Let'sseeasimple example of
strlwr() function.
#include<stdio.h>#
include<string.h>i
nt main(){
char str[20];
printf("Enterstring:");
gets(str);//reads string from console
printf("String is:
%s",str);printf("\nLowerStringis:%s",strl
wr(str));
return0;
}
Output:
Thestrupr(string)functionreturnsstringcharactersinuppercase.Let'sseeasimple example
of strupr() function.
Example:
#include<stdio.h>#
include<string.h>i
nt main(){
Designed by J.Ravi Kumar
char str[20];
printf("Enterstring:");
gets(str);//readsstringfromconsole
printf("String is: %s",str);
printf("\nUpperStringis:%s",strupr(str));
return 0;
}
Output:
Enterstring:javatpoint
String is: javatpoint
UpperStringis: JAVATPOINT
5.Characterhandlingfunctionsinc
Character functionsneed ctype.hheader filetobe includedinthepgoram.
1. isalpha():
This function checks whether the character variable/constantcontains
alphabet or not.
2. isdigit()
This function checks whether the character variable/ constant contains digit
or not.
3. isalnum()
This function checks whether the character variable/constantcontains an
alphabet or digit.
4. ispunct()
This function checks whether the character variable/constantcontains a
5. isspace()
This function checks whether the character variable/constantcontains a
space or not.
Programtodemonstratetheuseofcharacterfunctions.
#include<ctype.h>
#include<stdio.h>i
nt main()
{
charn;
printf("\nEnter a character=");
n=getche();
if(isalpha(n))
printf("\nYou typed an alphabet");
if(isdigit(n))
printf("\nYou typed a digit");
if(isalnum(n))
printf("\nYou typed an alphabet or digit");
if(isspace(n))
printf("\nYou typed a blank space");
if(ispunct(n))
printf("\nYou typed punctuator");
return(0);
}
Output
Enter a character=A
You typed an alphabet
6.isupper()
This function checks whether the character variable/constantcontains an
7. islower()
This function checks whether the character variable/constantcontains a
8. toupper()
Thisfunctionconvertslowercasealphabetintouppercasealphabet.
9. tolower()
Thisfunctionconvertsanuppercasealphabetintolowercasealphabet.
Programtouseofislower,isupper,tolower(),toupper().
#include<ctype.h>
#include<stdio.h>i
nt main()
{
charn;
printf("\nEnter an alphabet=");
n=getche();
if(islower(n))
n=toupper(ch);
else
ch=tolower(ch);
printf("\nNow alphabet=%c",n);
return(0);
}
Output
Enter an alphabet=A
Now alphabet=a
UNIT-IV
Functions:FunctionPrototype,definitionandcalling.Returnstatement.Nestingoffunctions.C
ategoriesoffunctions.Recursion,ParameterPassingbyaddress&byvalue.
Designed by J.Ravi Kumar
Local and Global variables. Storage classes: automatic, external, static and register.
Pointers: Pointer data type, Pointer declaration, initialization, accessing values using
pointers. Pointer arithmetic. Pointers and arrays, pointers and functions
Functions:
1.FunctionPrototype,definitionandcallinginc
Function:FunctionsinCarethebasicbuildingblocksofaCprogram.Afunctionisaset
ofstatementsenclosedwithincurlybrackets({})thattakeinputs,dothecomputation,and
providetheresultantoutput.Youcancallafunctionmultipletimes,therebyallowing
reusabilityandmodularityinCprogramming.Inotherwordsafunctionisaselfcontained
blockofstatements.
Therearetwo typesoffunctionsinC:
1. Built-in(Library)Functions
o Thesystemprovidedthesefunctionsandstoredtheminthelibrary.
Therefore it is also called Library Functions.
e.g.scanf(),printf(),strcpy,strlwr,strcmp,strlen,strcat,etc.
o YoumustincludetheappropriateCheaderfilestousethese functions.
2. UserDefinedFunctions
o Thesefunctionsaredefinedbytheuserwhenwritingtheprogram.
o Eg:sum(),avg(),total(),suresh(),naresh()etc
Advantage of functions in C
TherearethefollowingadvantagesofC functions.
o By using functions, we can avoid rewriting same logic/code again and again in a
program.
o WecancallCfunctionsanynumberoftimesinaprogramandfromanyplaceina program.
o WecantrackalargeCprogrameasilywhenitisdividedintomultiple functions.
o ReusabilityisthemainachievementofCfunctions.
o However,FunctioncallingisalwaysaoverheadinaC program.
Functionprototype
Afunctionprototypegivesinformationtothecompilerthatthefunctionmaylaterbe used in
the program.
Syntaxoffunctionprototype
returnTypefunctionName(type1argument1,type2argument2............... );
Functiondefinition
Function definition contains the block of code to perform a specific task. A function
definitionspecifiesthenameofthefunction, thetypesandnumberof parametersit
expects to receive, and its return type. A function definition also includes a function
body with the declarations of its local variables, and the statements that determine
what the function does.
Syntaxoffunctiondefinition
returnTypefunctionName(type1argument1,type2argument2,............... )
//localvariable
//bodyofthefunction
//returnstatement
}
Designed by J.Ravi Kumar
Callingafunction
Controloftheprogramistransferredtotheuser-definedfunctionbycallingit.Whena function
is called, the control of the program is transferred to the function definition. And, the
compiler starts executing the codes inside the body of a function.
Syntaxoffunction call
functionName(argument1,argument2,…….);
theuserdefinedfunctionwithargumentsiscallingbythefunctioncalling
Example:
#include<stdio.h>
intgetAreaOfSquare(intside)/*Functionprototype*/
{
intarea;/*localvariabledeclaration*/
area=side*side; functiondef
returnarea;/*Returnstatement*/
}
intmain()
{
intside,area;
printf("Entersideofsquare\n");
scanf("%d", &side);
area=getAreaOfSquare(side); /*CallinggetAreaOfSquarefunction*/
printf("AreaofSquare=%d",area); return
0;
}
2. Returnstatementinc
Designed by J.Ravi Kumar
ReturnstatementWhenprogramexecutionreachesthereturnstatement,itwillleave the
current function and the program execution will resume to the next statement, where it
was actually called.
Syntax:return; or
return(valueorvariable);
return 10;
return a;
returna+b;
Thevaluewillbepassedbacktothefunction whereitwascalled.Wecanreceivethe value and
do the further programming from that point.
PictorialExplanation
Where,
Designed by J.Ravi Kumar
Callingfunction-Mainfunction(thepointfromwherethefunctioniscalled)
Calledfunction-theactualfunctionwhichgoingtoexecute.
answillreceivethesumresultthatis15.inotherwords, answillholdvalue15afterthe execution
of return statement.
Andtheprogramexecutionwillresumefromprintf("10+5=%d",ans);statement.
Whatwillhappenifwewritesomestatementsbelowtothereturn statement?
Iftheprogramexecutionreachesreturnstatement,the statementsbelowtothatwillnot be
executed.
Executioncontrolwillleavethecurrentfunctionimmediately.
Example:
#include<stdio.h>i
ntsum(inta,intb)
{
returna+b;
/*
* printfwillnotbeexecuted,
* asit isbelowtothe return statement
*/
printf("Hello");
}
intmain()
{
intans;
ans =sum(10,5);
//answillhavethereturnvaluei.e a+b
printf("10+5=%d",ans); return
0;
}
3. Nestingoffunctionsinc
Some programmer thinks that defining a function inside an another function is
known as “nested function”. But the reality is that it is not a nested function, it is
treated as lexical scoping. Lexical scoping is not valid in C because the compiler cant
reach/find the correct memory location of the inner function.
Designed by J.Ravi Kumar
return_typefunction_one()
{
statements
function_two();
}
return_typefunction_two(){
statementsfunction_three();
}
return_typefunction_three()
{
statements
}
intmain()
{
function_one();
return 0;
}
Example:
#include<stdio.h>
Designed by J.Ravi Kumar
#include<stdlib.h>
int main()
{
printf("Thisismainmethodinc\n");
function_one();
getch();
return0;
}
voidfunction_one()
{
printf("Thisisauserdefinefunction\n");
function_two();
}
voidfunction_two()
{
printf("Thisisnestedfunctioninc\n");
}
Whentheabovecodeisexecuted,itproducesthefollowing results:
Thisismainmethod inc
Thisisauserdefine function
Thisisnestedfunctioninc
4. Categoriesoffunctionsinc
• Functionswithoutargumentsandwithoutreturnvalues
• Functionswithoutargumentsandwithreturnvalues
• Functionswithargumentsandwithoutreturnvalues
• Functionswithargumentsandwithreturnvalues
Designed by J.Ravi Kumar
1)Functionswithoutargumentsandwithoutreturnvalues
Example
#include<stdio.h>mai
n (){
voidsum();
clrscr ();
sum ();
getch();
}
voidsum ()
{
inta,b,c;
printf("enter2numbers:");
scanf ("%d%d", &a, &b);
c=a+b;
printf("sum=%d",c);
}
Output
Enter2numbers:
3
5
Sum=8
Designed by J.Ravi Kumar
2. Functionswithoutargumentsandwithreturnvalues
Example
#include<stdio.h>mai
n (){
intsum(); int
c;
c= sum ();
printf(“sum=%d”,c);
getch ();
}
intsum (){
inta,b,c;
printf(“enter2numbers”);
scanf (“%d%d”, &a, &b);
c=a+b;
returnc;
}
Output
Entertwonumbers10 20
30
Designed by J.Ravi Kumar
3. Functionswithargumentsandwithoutreturnvalues
Example
#include<stdio.h>mai
n (){
voidsum(int,int); int
a,b;
printf("enter2numbers");
scanf("%d%d", &a,&b);
sum (a,b);
getch();
}
voidsum(inta,intb){ int
c;
c=a+b;
printf(“sum=%d”,c);
}
Output
Entertwonumbers1020
Sum=30
Designed by J.Ravi Kumar
4. Functionswithargumentsandwith returnvalues
Example
#include<stdio.h>mai
n (){
intsum(int,int);
int a,b,c;
printf("enter2numbers");
scanf("%d%d", &a,&b);
c= sum (a,b);
printf("sum=%d",c);
getch ();
}
intsum(inta,intb){ int
c;
c= a+b;
returnc;
}
Output
Entertwonumbers1020
Sum=30
5. Recursioninc
Recursionistheprocesswhichcomesintoexistencewhenafunctioncallsacopyofitself to work
on a smaller problem.
Anyfunctionwhichcallsitselfiscalledrecursivefunction,andsuchfunctioncallsarecalled
recursive calls.
Designed by J.Ravi Kumar
Recursioncodeisshorterthaniterativecodehoweveritisdifficultto understand.
Recursioncannotbeappliedtoalltheproblem,butitismoreusefulforthetasksthatcan be
defined in terms of similar subtasks.
Generally,iterativesolutionsaremoreefficientthanrecursionsincefunctioncallisalways
overhead. Any problem that can be solved recursively, can also be solved iteratively.
However, some problems are best suited to be solved by the recursion, for example,
tower of Hanoi, Fibonacci series, factorial finding, etc.
Example:
#include<stdio.h>
intfact (int);
intmain()
{
intn,f;
printf("Enterthenumberwhosefactorialyouwanttocalculate?"); scanf("%d",&n);
f = fact(n);
printf("factorial=%d",f);
}
intfact(intn)
{
if(n==0)
{
return0;
}
elseif( n==1)
{
return1;
}
Designed by J.Ravi Kumar
else
{
returnn*fact(n-1);
}
}
Output
Enterthenumberwhosefactorialyouwanttocalculate?5
factorial = 120
Recursive Function
A recursive function performs the tasks by dividing it into the subtasks. There is a
terminationconditiondefinedinthe function whichissatisfiedbysomespecificsubtask. After
this, the recursion stops and the final result is returned from the function.
ExampleofrecursioninC
#include<stdio.h>
int fibonacci(int);
void main ()
{
intn,f;
printf("Enterthevalueofn?");
scanf("%d",&n);
f=fibonacci(n);
printf("%d",f);
}
intfibonacci(intn)
{
if(n==0)
{
return0;
}
elseif(n==1)
{
return1;
}
Designed by J.Ravi Kumar
else
{
returnfibonacci(n-1)+fibonacci(n-2);
}
}
Output
Enterthevalueofn?12 144
6. ParameterPassingbyaddress&byvalue
a) CallbyvalueinC
o Incallbyvaluemethod,thevalueoftheactualparametersiscopiedintotheformal
parameters.Inotherwords,wecansaythatthevalueofthevariableisusedinthe function
call in the call by value method.
o In call by value method, we can not modify the value of the actual parameter by
the formal parameter.
o In call by value, different memory is allocated for actual and formal parameters
since the value of the actual parameter is copied into the formal parameter.
o The actual parameter is the argument which is used in the function call whereas
formal parameter is the argument which is used in the function definition.
CallbyValueExample:Swappingthevaluesofthetwo variables
#include
<stdio.h>voidswap(
int,int); int main()
{
inta=10;
intb=20;
printf("Beforeswappingthevaluesinmaina=%d,b=%d\n",a,b); swap(a,b);
printf("Afterswappingvaluesinmaina=%d,b=%d\n",a,b);}
voidswap(inta,intb)
{
int temp;
temp=a;
Designed by J.Ravi Kumar
a=b;
b=temp;
printf("Afterswappingvaluesinfunctiona=%d,b= %d\n",a,b);
}
Output
Beforeswappingthevaluesinmaina=10,b=20 After
swapping values in function a = 20, b = 10 After
swapping values in main a = 10, b = 20
b) CallbyreferenceinC
o In call by reference, the address of the variable is passed into the function call as
the actual parameter.
o The value of the actual parameters can be modified by changing the formal
parameters since the address of the actual parameters is passed.
o In call by reference, the memory allocation is similar for both formal parameters
and actual parameters. All the operations in the function are performed on the
value stored at the address of the actual parameters, and the modified value gets
stored at the same address.
CallbyreferenceExample:Swappingthevaluesofthetwo variables
#include
<stdio.h>voidswap(int
*,int*); int main()
{
inta=10;
intb=20;
printf("Beforeswappingthevaluesinmaina=%d,b=%d\n",a,b); swap(&a,&b);
printf("Afterswappingvaluesinmaina=%d,b=%d\n",a,b);
}
voidswap(int*a,int*b)
{
int temp;
temp=*a;
*a=*b;
Designed by J.Ravi Kumar
*b=temp;
printf("Afterswappingvaluesinfunctiona=%d,b= %d\n",*a,*b);
}
Output
Beforeswappingthevaluesinmaina=10,b=20 After
swapping values in function a = 20, b = 10 After
swapping values in main a = 20, b = 10
7. LocalandGlobalvariablesinc
Scope ofVariable
Eachvariableisdefinedandcanbeusedwithinitsscopeanddeterminesthatwhereinthe
program thisvariableisavailable touse. The scope meansthe lifetimeof that variable. It
means the variable can only be accessed or visible within its scope.
The scope of variables can be defined with their declaration, and variables are declared
mainly in two ways:
o GlobalVariable:Outsideofallthefunctions
o LocalVariable:Withinafunctionblock:
WhatisaGlobal Variable?
o Globalvariablesarethosevariableswhicharedeclaredoutsideofallthefunctions or
block and can be accessed globally in a program.
o Itcanbeaccessed byanyfunctionpresentinthe program.
o Once we declare a global variable, its value can be varied as used with different
functions.
o Thelifetimeoftheglobal variable existstillthe programexecutes.Thesevariables are
stored in fixed memory locations given by the compiler and do not automatically
clean up.
o Globalvariablesaremostlyusedinprogrammingandusefulforcaseswhereallthe
functions need to access the same data.
Example:
#include<stdio.h>
inta=50, b=40;
Designed by J.Ravi Kumar
voidmain()
{
printf("a=%dandb=%d",a,b);
}
Intheaboveexample,aandbaretheglobal variables.
AdvantagesofGlobal Variable
o Globalvariablescanbeaccessedbyallthefunctionspresentintheprogram.
o Onlyasingledeclarationisrequired.
o Veryusefulifallthefunctionsareaccessingthesame data.
DisadvantagesofGlobalVariable
o The value of aglobal variable can be changed accidently as it can be usedby any
function in the program.
o If we use a large number of global variables, then there is a high chance of error
generation in the program.
Example:
#include<stdio.h>
Designed by J.Ravi Kumar
voidmain()
{
intx=50, y=40;
printf("x=%dandy=%d",x,y);
}
In the above example, we have declared x and y two variables inside the main function.
Hence these are local variables.
AdvantagesofLocal Variable
o The same name of a local variable can be used in different functions as it is only
recognized by the function in which it is declared.
o Localvariablesusememoryonlyforthelimitedtimewhenthefunctionisexecuted; after
that same memory location can be reused.
DisadvantagesofLocalVariables
o The scope of the local variable is limited to its function only and cannot be used
by other functions.
o Datasharingbythelocalvariableisnot allowed.
8. Storageclasses:automatic,external,staticandregisterinc
Storage classes in C are used to determine the lifetime, visibility, memory location, and
initial value of a variable. There are four types of storage classes in C
o Automatic
o External
o Static
o Register
Automatic
Automaticstorageclass:thefeatureofavariabledefinedinautomaticstorageclassas.
Keyword:auto
Storage: mainmemory
Designed by J.Ravi Kumar
Defaultvalue: Anunpredictablevalue(garbagevalue)
Output:
garbagegarbagegarbage
Static
Staticstorageclass:featureofavariabledefinedisregisterstorageclassas
Keyword:static
Storage:
mainmemory
Defaultvalue:
zero
printf("%d%d%f%s",c,i,f);.
}
Output:
00 0.000000(null)
Register
Registerstorageclass:thefeatureofavariabledefinedisregisterstorageclassas
Keyword:register
Storage:CPU registers
Defaultvalue:Anunpredictablevalue(garbagevalue)
Output:0
External
ExternalStorageclass:featureofavariabledefinedisregisterstorageclassas
Keyword:
externStorage:
mainmemory
Defaultvalue:
zero
Scope:global
Lifetime:Aslongastheprogramexecutiondoesn‟tcomestoend.
Example
#include<stdio.h>
Designed by J.Ravi Kumar
inta;
intmain()
{
extern int a;
printf("%d",a);
}
Output:0
Pointers:
Pointerdatatype:
intn=10;
int*p=&n;
Pointerdeclaration,initialization,accessingvaluesusingpointers Pointer
Declaringapointer
int *ptr;
Designed by J.Ravi Kumar
‘ptr’isapointervariablethatholdstheaddressof anotherintegervariable.
Initializationofa pointer
Addressoperator(&)isusedtoinitializeapointervariable.
inta=44;
int *b;
b=&a;
Inthisprogram,wearetryingtoaccessanelementwhichispresentatparticularlocation. The
location can be found by using an operation.
Byaddingpreincrementedpointertopreincrementedpointerstringandthesubtracting 32,
you get the value at that location.
Accessingofpointervariable
#include<stdio.h>
intmain(){
intnumber=50;
int *p; //pointer declaration
p=&number;//pointer initialization
printf("Addressofpvariableis%x\n",p);
printf("Valueofpvariableis%d\n",*p);//pointervariableaccessing return 0;
}
Output
Addressofnumbervariableisfff4
Address of p variable is fff4
Valueofpvariableis50
10. Pointerarithmeticin c
We can perform arithmetic operations on the pointers like addition, subtraction, etc.
However, as we know that pointer contains the address, the result of an arithmetic
operation performed on the pointer will also be a pointer if the other operand is of type
integer.Inpointer-from-pointersubtraction,theresultwillbeanintegervalue.Following
arithmetic operations are possible on the pointer in C language:
o Increment
o Decrement
o Addition
o Subtraction
Designed by J.Ravi Kumar
1. IncrementingPointerinC
If we increment a pointer by 1, the pointer will start pointing to the immediate next
location. This is somewhat different from the general arithmetic since the value of the
pointer will get increased by the size of the data type to which the pointer is pointing.
Example:
#include<stdio.h>
intmain(){
intnumber=50;
int *p;
p=&number;
printf("Addressofpvariableis%u\n",p);
p=p+1;
printf("Afterincrement: Addressofpvariableis%u \n",p);
return0;
Output
Addressofpvariableis3214864300
Afterincrement:Addressofpvariableis3214864304
2. DecrementingPointerinC
Example:
#include<stdio.h>
voidmain(){
intnumber=50;
int *p;
p=&number;
printf("Addressofpvariableis%u\n",p);
p=p-1;
printf("Afterdecrement: Addressof pvariableis%u\n",p);
}
Designed by J.Ravi Kumar
Output
Addressofpvariableis3214864300
Afterdecrement:Addressofpvariableis3214864296
3. CPointerAddition
Wecanaddavaluetothepointervariable.Theformulaofaddingvaluetopointerisgiven below:
Example:
#include<stdio.h>
intmain(){
intnumber=50;
int *p;
p=&number;
printf("Addressofpvariableis%u\n",p);
p=p+3;
printf("Afteradding3: Addressof pvariableis%u\n",p);
return0;
}
Output
Addressofpvariableis3214864300
Afteradding3:Addressofpvariableis3214864312
4. CPointerSubtraction
Like pointer addition, we can subtract a value from the pointer variable. Subtracting any
number from a pointer will give an address. The formula of subtracting value from the
pointer variable is given below:
Example:
#include<stdio.h>
intmain(){
intnumber=50;
int *p;
p=&number;
Designed by J.Ravi Kumar
printf("Addressofpvariableis%u\n",p);
p=p-3;
printf("Aftersubtracting3:Addressofpvariableis%u \n",p);
return0;
}
Output
Addressofpvariableis3214864300
Aftersubtracting3:Addressofpvariableis3214864288
11.Pointersandarraysin c
Pointer
Arrayisagroupofelementsthatshareacommonname,andthataredifferentfrom one
another by their positions within the array. Under one name, a collection of elements
of the same type is stored in memory.
canbeofanydatatype,e.g.,integer,character,longinteger,float,double,etc. even
collection of arrays
Arraysofstructure,pointer,unionetc.arealsoallowed
Advantages:
Foreaseofaccesstoanyelementofanarray
Passing a group of elements to a function
Howarraysarestoredinmemory?
PointersandarraysinC:
RelationshipbetweenArraysandPointers
Example:
#include<stdio.h>
#define N 5
intmain(){
Designed by J.Ravi Kumar
inti,*ptr,sum =0;
intnums[N]={1,2,3,4,5}; ptr =
nums;
for(i=0;i<N;++i) sum
+= ptr[i];
printf("Sum=%d",sum);//Sum=15
}Output:
Sum=15
Differencebetweenpointerandarray
12. Pointersandfunctionsin c
TheClanguagemakesextensiveuseofpointers,aswehaveseen.Theycanbeusedto provide
indirect references to primitive types, to create dynamically sized arrays, to create
instances of structs on demand, and to manipulate string data, among other things.
Pointers can also be used to create references to functions. In other words, a function
pointer is a variable that contains the address of a function.
Functionsaspointers
• Memorystoresthefunctioncode
• Theaddressorstartofafunctionisreferredtoasa"functionpointer"
• Sincefunctionpointersdonotallocateordeallocatememory,theyare"different" from
other pointers
• Itispossibletopassfunctionpointersasargumentsto otherfunctionsoras
returns from other functions
Whyusefunctionpointers?
• Efficiency
• Elegance
• Runtimebinding
Designed by J.Ravi Kumar
Functionpointerdeclarations
Unlikeafunctiondeclaration,afunctionpointerdeclarationwrapsthefunctionnamein
parentheses and precedes it with an asterisk. Here is an example:
• intfunction(intx,inty);/*afunctiontakingtwointargumentsandreturningan int */
• int(*pointer)(intx,inty);/*apointertosuchafunction*/
PointersasArguments
Bypassingapointerintoafunction,thefunctionmayreadorchangememoryoutside of its
activation record.
Example:Pointersandfunctions
Inthefollowingexample,functionpassesthevalueofpandtheaddressofq,whichare used to
initialize the variables x and ptry in the function test.
Example:
#include<stdio.h>
voidtest(intx,int*ptry){ x =
200;
*ptry=200;
return;
intmain(void ){
intp =10,q=20;
&q );
return0;
Output:
UNIT-V
1. DynamicMemoryManagement:Introduction,Functions-malloc,
calloc, realloc, free in c
1. malloc()
2. calloc()
3. realloc()
4. free()
Before learning above functions, let's understand the difference between static memory
allocation and dynamic memory allocation.
staticmemoryallocation dynamicmemoryallocation
memory can't be increased while executing memory can be increased while executin
program. program.
Designed by J.Ravi Kumar
Nowlet'shaveaquicklookatthemethodsusedfordynamicmemory allocation.
malloc() allocatessingleblockofrequestedmemory.
calloc() allocatesmultipleblockofrequestedmemory.
free() freesthedynamicallyallocatedmemory.
1. malloc()functioninC
Themalloc()functionallocatessingleblockofrequestedmemory.
Itdoesn'tinitializememoryatexecutiontime, soithasgarbagevalueinitially. It
Thesyntaxofmalloc():
ptr=(cast-type*)malloc(byte-size);
#include<stdio.h>
#include<stdlib.h>
int main(){
intn,i,*ptr,sum=0;
printf("Enternumberofelements:");
scanf("%d",&n);
ptr=(int*)malloc(n*sizeof(int));//memoryallocatedusingmalloc
if(ptr==NULL)
{
printf("Sorry!unabletoallocatememory");
Designed by J.Ravi Kumar
exit(0);
}
printf("Enterelementsofarray:");
for(i=0;i<n;++i)
{
scanf("%d",ptr+i);
sum+=*(ptr+i);
}
printf("Sum=%d",sum);
free(ptr);
return0;
}
Output
2. calloc()functioninC
Thecalloc()functionallocatesmultipleblockofrequestedmemory. It
ItreturnsNULLifmemoryisnotsufficient.
Thesyntaxofcalloc():
ptr=(cast-type*)calloc(number,byte-size);
Example of calloc() function.
#include<stdio.h>
#include<stdlib.h>
intmain(){
intn,i,*ptr,sum=0;
printf("Enternumberofelements:");
Designed by J.Ravi Kumar
scanf("%d",&n);
ptr=(int*)calloc(n,sizeof(int));//memoryallocatedusingcalloc
if(ptr==NULL)
{
printf("Sorry!unabletoallocatememory");
exit(0);
}
printf("Enterelementsofarray:");
for(i=0;i<n;++i)
{
scanf("%d",ptr+i);
sum+=*(ptr+i);
}
printf("Sum=%d",sum);
free(ptr);
return0;
}
Output
syntaxofrealloc()function.
ptr=realloc(ptr, new-size)
4.free() function in C: The memory occupied by malloc() or calloc() functions must be
releasedbycallingfree()function.Otherwise,itwillconsumememoryuntilprogramexit.
syntaxoffree()function.
free(ptr)
Designed by J.Ravi Kumar
Structures:
2).Basicsofstructure,structuremembers,accessingstructuremembers
a) Basicsof structure:
WhatisStructure:Structureincisauser-defineddatatypethatenablesustostorethe
collection of different data types. Each element of a structure is called a member.
Structuresca;simulatetheuseofclassesandtemplatesasitcanstorevariousinformation
The,structkeywordisusedtodefinethe structure.
syntax:
structstructure_name
{
data_typemember1;
data_typemember2;
.
.
data_typememeberN;
};
Example:
structemployee
{
intid;
charname[20];
floatsalary;
};
Here,structisthekeyword; employee isthenameofthestructure; id,name,andsalary arethe
members or fields of the structure. Let's understand it by the diagram given below:
b) Membersof structure:
Designed by J.Ravi Kumar
Declaringstructurevariable
Wecandeclareavariableforthestructuresothatwecanaccessthememberofthe structure
easily. There are two ways to declare structure variable:
1. Bystructkeywordwithinmain() function
2. Bydeclaringavariableatthetimeof definingthe structure.
1stway:Let'sseetheexampletodeclarethestructurevariablebystructkeyword.It should be
declared within the main function.
structemployee
{ intid;
charname[50];
floatsalary;
};
Nowwritegivencodeinsidethemain() function.
structemployeee1,e2;
Thevariablese1ande2canbeusedtoaccessthevaluesstoredinthestructure.Here,e1 and e2
can be treated in the same way as the objects in C++and Java.
2ndway:Let'sseeanotherwaytodeclarevariableatthetimeofdefiningthe structure.
structemployee
{
intid;
charname[50];
floatsalary;
Designed by J.Ravi Kumar
}e1,e2;
c) Accessingmembersofthe structure
Therearetwowaystoaccessstructure members:
1. By.(memberordotoperator)
Let'sseethecodetoaccesstheidmemberofp1variableby.(member) operator.
p1.id
CStructureexample
#include<stdio.h>#
include<string.h>st
ruct employee
{ intid;
charname[50];
}e1;
intmain()
{
e1.id=101;
strcpy(e1.name, "Sonoo Jaiswal");
printf("employee1id:%d\n",e1.id);
printf("employee1name:%s\n",e1.name);
return0;
}
Output:
employee1id:101
employee1name:SonooJaiswal
3. NestedStructureinC
Cprovidesusthefeatureofnestingonestructurewithinanotherstructurebyusingwhich,
complex data types are created. For example, we may need to store the address of an
entityemployeeinastructure.Theattributeaddressmayalsohavethesubpartsasstreet
number, city,state,andpincode.Hence,tostoretheaddressoftheemployee,weneed
Designed by J.Ravi Kumar
tostoretheaddressoftheemployeeintoaseparatestructureandnestthestructure address
into the structure employee. Consider the following program.
Example:
#include<stdio.h>
structaddress
{
charcity[20];
intpin;
charphone[14];
};
structemployee
{
charname[20];
structaddressadd;
};
voidmain()
{
structemployeeemp;
printf("Enteremployeeinformation?\n");
scanf("%s%s%d%s",emp.name,emp.add.city,&emp.add.pin,emp.add.phone);
printf("Printing the employee information ...\n");
printf("name:%s\nCity:%s\nPincode:%d\nPhone:%s",emp.name,emp.add.city,emp.add.
pin,emp.add.phone);
}
Output
Enteremployeeinformation? Arun
Delhi
110001
Designed by J.Ravi Kumar
1234567890
Printingtheemployeeinformation.... name:
Arun
City: Delhi
Pincode:110001
Phone:1234567890
Thestructurecanbenestedinthefollowing ways.
1. Byseparate structure
2. ByEmbedded structure
1) Separatestructure
Here, we create two structures, but the dependent structure should be used inside
themain structure as a member. Consider the following example.
structDate
{
int dd;
int mm;
intyyyy;
};
structEmployee
{
intid;
charname[20];
structDate doj;
}emp1;
2) Embeddedstructure
The embedded structure enables us to declare the structure inside the structure. Hence,
it requires less line of codes but it can not be used in multiple data structures. Consider
the following example.
structEmployee
{
intid;
charname[20];
structDate
{
int dd;
int mm;
intyyyy;
}doj;
}emp1;
4. Arrayofstructuresinc
Example:
#include<stdio.h>#
include<string.h>st
ruct student{
introllno;
charname[10];
};
intmain(){
inti;
structstudentst[5];
printf("EnterRecordsof5students");
for(i=0;i<5;i++){
printf("\nEnterRollno:");
scanf("%d",&st[i].rollno);
printf("\nEnter Name:");
scanf("%s",&st[i].name);
}
printf("\nStudentInformationList:");
for(i=0;i<5;i++){
printf("\nRollno:%d,Name:%s",st[i].rollno,st[i].name);
}
return0;
}
Output:
EnterRecordsof5 students
Enter Rollno:1
EnterName:Sonoo
Enter Rollno:2
Enter Name:Ratan
Enter Rollno:3
Enter Name:Vimal
Enter Rollno:4
Enter Name:James
Enter Rollno:5
Designed by J.Ravi Kumar
Enter Name:Sarfraz
StudentInformationList:
Rollno:1, Name:Sonoo
Rollno:2, Name:Ratan
Rollno:3, Name:Vimal
Rollno:4, Name:James
Rollno:5, Name:Sarfraz
Whyuseanarrayofstructures?
#include<stdio.h>
structstudent
{
charname[20];
intid;
floatmarks;
};
voidmain()
{
structstudents1,s2,s3;
intdummy;
printf("Enterthename,id,andmarksofstudent1");
scanf("%s %d %f",s1.name,&s1.id,&s1.marks);
scanf("%c",&dummy);
printf("Enterthename,id,andmarksofstudent2");
scanf("%s %d %f",s2.name,&s2.id,&s2.marks);
scanf("%c",&dummy);
printf("Enterthename,id,andmarksofstudent3");
scanf("%s %d %f",s3.name,&s3.id,&s3.marks);
scanf("%c",&dummy);
printf("Printingthedetails\n");
printf("%s%d%f\n",s1.name,s1.id,s1.marks);
printf("%s%d%f\n",s2.name,s2.id,s2.marks);
printf("%s%d%f\n",s3.name,s3.id,s3.marks);
Designed by J.Ravi Kumar
Output
Functionsaretheblocksofcodesthatperformaspecifictaskwhencalled.Weneedto
passtheparameterstothefunction,andthefunctionreturnstheresult.Structurescan also be
passed as parameters to the functions.
When a function is called, if we pass the values of the variables to the function, it is
knownasthecallbyvalue.Insteadofpassingthevalues,ifwepasstheaddressofthe variables
to the function, it is known as call by reference.
Withthesebasicsofstructuresandfunctions,Itwillbeeasytounderstandstructure functions
clearly.
Structure-functioncan beeffectivelyusedwhilewritingcode.Structurescanbepassed as
arguments to the functions. This can be done in three ways. They are,
• Passingthemembersofthestructuresasanargument.
• Passingtheentirestructureasanargument.
• Passingtheaddressofthe structureasarguments.
Designed by J.Ravi Kumar
#include<stdio.h>
int add(int, int) ;int
main()
{
structaddition
{
inta,b;
int c;
}sum;
printf("Enter the value of a : ");
scanf("%d",&sum.a);
printf("\nEnterthevalueofb:");
scanf("%d",&sum.b);
sum.c=add(sum.a,sum.b); //passingstructuremembersasargumentstofunction
printf("\nThesumoftwovalueare:");
printf("%d ", sum.c);
return0;
}
//Functiondefinition
intadd(intx,inty)
{
int sum1;
sum1=x+y;
return(sum1);
}
Designed by J.Ravi Kumar
HowtoPassStructureMembersToFunctions?
Sometimeswedon’twanttopasstheentirestructuretothefunction.Wewanttopass only a
few members of the structure. We can use the dot (.) operator to access the individual
members of the structure and pass them to the function.
Let us create a structure to hold the details of a student, such as the name of the
student,rollnumber,andmarks,andprintout justtherollnumberandmarksusinga function.
Passingthe entire structure to the functionisunnecessary whenwe want to print only a
few structure members.
In the above example, the structure contains the name of the student as well, but we
needtoprintonlythepercentage androllnumber.Thereforewepassonlytherequired
structure members to function.
6. structuresandpointersin c
DeclareaStructurePointer
Thedeclarationofastructurepointerissimilartothedeclarationofthestructurevariable. So, we
can declare the structure pointer and variable inside and outside of the main() function.
To declare a pointer variable in C, we use the asterisk (*) symbol before the variable's
name.
structstructure_name*ptr;
Afterdefiningthestructurepointer,weneedtoinitializeit,asthecodeis shown:
InitializationoftheStructurePointer
ptr= &structure_variable;
WecanalsoinitializeaStructurePointer directlyduringthedeclarationofapointer.
structstructure_name*ptr=&structure_variable;
Designed by J.Ravi Kumar
Aswecansee,apointerptrispointingtotheaddressstructure_variableoftheStructure.
AccessStructurememberusingpointer:
#include <stdio.h>
structEmployee
{
charname[30];
intid;
charcity[40];
};
structEmployeeemp,*ptr;
intmain()
{
ptr1=&emp;
printf("EnterthenameoftheEmployee(emp):"); scanf
(" %s", &ptr.name);
printf("EntertheidoftheEmployee(emp): ");
scanf (" %d", &ptr.id);
printf("EnterthecityoftheEmployee(emp):"); scanf ("
%s", &ptr.city);
printf("\nDisplaytheDetailsoftheEmployeeusingStructurePointer"); printf ("\n
Details of the Employee (emp) \n");
printf("Name:%s\n",ptr.name);
printf(" Id: %d\n", ptr1.id);
printf(" City: %s\n", ptr.city);
return 0;
}
Output:
EnterthenameoftheEmployee(emp):John Enter
the id of the Employee (emp): 1099
Enterthecityof theEmployee(emp1):California
DisplaytheDetailsoftheEmployeeusingStructurePointer
Designed by J.Ravi Kumar
DetailsoftheEmployee (emp)
Name:John
Id: 1099
City: California
Intheaboveprogram,wehavecreatedan Employeestructurecontainingtwostructure
variables emp a, with the pointer variables *ptr. The structure Employee is having the
name, id and city as the members. All the Employee structure members take their
respectivevaluesfromtheuseronebyoneusingthepointervariableanddot(.)operator that
determine their space in memory.
Unions
7. uniondefinitionin c
The Union is a user-defined data type in C language that can contain elements of the
different data types just like structure. But unlike structures, all the members in the C
union are stored in the same memory location. Due to this, only one member can
store data at the given instance.
SizeofUnion
The size of the union will always be equal to the size of the largest member of the
array. All the less-sized elements can store the data in the same space without any
overflow.
MemoryAllocationinCUnion
SyntaxofUnioninC
union union_name
{
datatype member1;
datatypemember2;
...
};
Designed by J.Ravi Kumar
Keepinmindthatwehavetoalwaysendtheuniondeclarationwithasemi-colon.
Ex:
DifferentWaystoDefineaUnionVariable
We need to define a variable of the union type to start using union members. There
are two methods using which we can define a union variable.
1. WithUnionDeclaration
2. AfterUnionDeclaration
1. Defining Union Variable with Declaration
union union_name
{
datatypemember1;
datatypemember2;
...
}var1,var2,...;
2. Defining Union Variable after Declaration
union union_name var1, var2, var3...;
whereunion_nameisthenameofanalreadydeclaredunion.
AccessUnionMembers
We can access the members of a union by using the ( . ) dot operatorjust like
structures.
var1.member1;
wherevar1istheunionvariableandmember1isthememberoftheunion.
The above method of accessing the members of the union also works for the nested
unions.
var1.member1.memberA;
Here,
• var1isaunionvariable.
• member1isamemberoftheunion.
Designed by J.Ravi Kumar
• memberAisamemberofmember1.
InitializationofUnioninC
The initialization of a union is the initialization of its members by simply assigning the
value to it.
var1.member1=some_value;
One important thing to note here is thatonly one member can contain some value at
a given instance of time.
ExampleofUnion
#include<stdio.h>
union un {
int member1;
char member2;
floatmember3;
};
int main(){
unionunvar1;
var1.member1=15;
return 0;}
Output
Thevaluestoredinmember1=15
Designed by J.Ravi Kumar
8. Differencebetweenstructuresandunionsinc
Structure (struct)is a user-defined data type in a programming language that stores
different data types' values together. The struct keyword is used to define a structure
datatypeinaprogram.Thestructdatatypestoresoneormorethanone dataelement of
different kinds in a variable.
Syntax of
structstruct[structure_
name]
{
typemember_1;
type member_2;
...
type member_n;
};
Example
structemployee
{
intid;
char name[50];
stringdepartment;
string email;
};
Syntax of Union
union[unionname]
{
type member_1;
Designed by J.Ravi Kumar
type member_2;
...
type member_n;
};
Example
unionemployee
{
string
name;stringdepart
ment; int phone;
stringemail;
};
DifferencebetweenStructureand Union
Struct Union
2.When the variables are declared in a When the variable is declared in the union,
structure, the compiler allocates thecompilerallocatesmemorytothelargest
memorytoeachvariablesmember.The size variable member. The size of a union is
sizeofastructureisequalorgreaterto the equal to the size of its largest data member
sum of the sizes of each data member. size.
4.Changing the value of a member will Changing the value of one member will also
not affect other variables members. affect other variables members.
The end
THANKYOU
J. RAVI KUMAR
Let's summarize the above discussed topic about the Struct and Union in the form of a
table that highlight the differences between structure and union: