0% found this document useful (0 votes)
57 views134 pages

C PDF

The document outlines a course on Problem Solving using C, covering fundamental concepts of computers and programming, including hardware and software components, data types, control statements, functions, and memory management. It details the structure of a C program, various data types, and the importance of functions and pointers in programming. Additionally, it explains the basic block diagram of a computer system, highlighting the roles of the input unit, CPU, and output unit.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
57 views134 pages

C PDF

The document outlines a course on Problem Solving using C, covering fundamental concepts of computers and programming, including hardware and software components, data types, control statements, functions, and memory management. It details the structure of a C program, various data types, and the importance of functions and pointers in programming. Additionally, it explains the basic block diagram of a computer system, highlighting the roles of the input unit, CPU, and output unit.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 134

Designed by J.

Ravi Kumar

VAMSADHARA DEGREE COLLEGE

II nd Semester
Course3:

Problem Solving using C


UNIT-I

Introductionto computer and programming: Introduction, Basic block diagram and


functions of various components of computer, Concepts of Hardware and software,
Typesofsoftware,Compilerandinterpreter,ConceptsofMachinelevel,Assemblylevel and
high-level programming, Flowcharts and Algorithms.

Fundamentals of C: History of C, Features of C, C Tokens-variables and keywords and


identifiers, constants and Datatypes, Rules for constructingvariable names, Operators,
StructureofCprogram,Input/outputstatementsinC-FormattedandUnformattedI/O

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

Derived data types in C: Arrays: One Dimensional arrays - Declaration, Initialization


and Memory representation; Two Dimensional arrays -Declaration, Initialization and
Memoryrepresentation.Strings:Declaring&Initializingstringvariables;Stringhandling
functions, Character handling functions

UNIT-IV

Functions: Function Prototype, definition and calling. Return statement. Nesting of


functions. Categories of functions. Recursion, Parameter Passingbyaddress & byvalue.
Local and Global variables. Storage classes: automatic, external, static and register.
Pointers:Pointerdatatype,Pointerdeclaration,initialization,accessingvaluesusing
pointers. Pointer arithmetic. Pointers and arrays, pointers and functions.

UNIT-V

DynamicMemoryManagement:Introduction,Functions-malloc,calloc,realloc,free
Structures:Basicsofstructure,structuremembers,accessingstructuremembers,nested
Designed by J.Ravi Kumar

VAMSADHARA DEGREE COLLEGE

structures,arrayofstructures,structureandfunctions,structuresandpointers. Unions-
Union definition; difference between Structures and Unions.

UNIT-I

Introduction to computer and programming: Introduction, Basic block diagram and


functions of various components of computer, Concepts of Hardware and software,
Typesofsoftware,Compilerandinterpreter,ConceptsofMachinelevel,Assemblylevel and
high-level programming, Flowcharts and Algorithms.

Fundamentals of C: History of C, Features of C, C Tokens-variables and keywords and


identifiers, constants and Datatypes, Rules for construct in gvariable names, Operators,
StructureofCprogram,Input/outputstatementsinC-FormattedandUnformattedI/O

1) Introduction to computer and programming


a) Introduction to computer

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

VAMSADHARA DEGREE COLLEGE

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

VAMSADHARA DEGREE COLLEGE

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.

4. Automation :A computer may conduct tasks automatically after instructions


are programmed. By executing jobs automatically,
5. Versatility: A computer can perform multiple tasks at the same time this is
known as versatility. For example, while listening to music, we may develop our
project using Power Point and Wordpad, or we can design a website.
6. Memory: A computer can store millions of records. these records may be
accessed with complete precision. Computer memory storage capacity is
measured in Bytes, Kilobytes(KB), Megabytes(MB), Gigabytes(GB), and
Terabytes(TB).
7. Accuracy :When a computer performs a computation or operation, the
chances of errors occurring are low. Errors in a computer are caused by human’s
submitting incorrect data. A computer can do a variety of operations and
calculations fast and accurately.

b) Introduction to computer programming


Acomputerprogramconsistsofcodethatisexecutedonacomputertoperform
particular tasks. This code is written by programmers.

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.

Source code needs to be converted into machine language so machines can


understandtheinstructionsandexecutetheprogram.Thisprocessofconverting
source code into machine language is known as compiling.

Examples of compiled programming Languages would be C and C++.


Designed by J.Ravi Kumar

VAMSADHARA DEGREE COLLEGE

Thereareotherlanguagesthatdonotusecompilers.Instead,theselanguages will use


an interpreter that will read and execute the code.

Examples of interpreted programming languages would be JavaScript and PHP.


Once the code is executed, then the computer program can run. The different
typesofcomputerprogramsincludeWordprocessors,Databasesystems,video
games, and websites.

Thesecomputerprogramsallowustointeractivewithdifferentsoftwaredevices and
services like phones, websites, and the computers themselves.

2. Basic block diagram of computer

Block diagram of a computer displays a structural representation of a computer system.


Theblockdiagramgivesyouaquickoverviewoftheworkingprocessofacomputerfrom
inputting the data to retrieving the desired results.

The following diagram represents a block diagram of the computer

system.: A computer system is a combination of three components:

• Input Unit
Designed by J.Ravi Kumar

VAMSADHARA DEGREE COLLEGE

• CPU(Central Processing Unit)

• 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 performs the following major functions:

• 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.

Central Processing Unit

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

VAMSADHARA DEGREE COLLEGE

Intheabovediagram,theControlUnit(CU)andArithmetic&LogicUnit(ALU)arejointly called
the Central Processing Unit (CPU).

Let'sdiscussallthepartsdisplayedintheabovediagramonebyone:

ControlUnit

Asthename suggests,thecontrol unitof aCPUcontrols alltheactivitiesand operations of the


computer. It is also responsible for controlling input/output, memory, and other devices
connected to the CPU.

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.

Ontheotherside,thelogicalunitcontrolsthelogicaloperationssuchas AND,OR,Equal, greater


than, and less than, etc. Apart from it, the logic unit also responsible for
performingseveralotheroperationssuchascomparing,selecting,matching,andmerging
data.

MemoryUnit

MemoryUnitisanessential partofthecomputersystemwhichisusedtostore dataand


instructions before and after processing.The memory unit transmits the information to
other units of the computer system when required.

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

VAMSADHARA DEGREE COLLEGE

results.Theprimarymemoryisalsoknownasthe MainMemoryortemporary memory.


Random Access Memory (RAM) is an example of primary memory.

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

VAMSADHARA DEGREE COLLEGE

addition, subtraction, multiplication and division. Logical decisions involve


comparisonoftwodataitemstoseewhichoneis largerorsmallerorequal.
• ControlUnit: TheControlunitcoordinatesandcontrolsthedataflowinandoutof CPU
and also controls all the operations of ALU, memory registers and also
input/outputunits.Itisalsoresponsibleforcarryingoutallthe instructionsstoredin the
program. It decodes the fetched instruction, interprets it and sends control
signalstoinput/outputdevicesuntiltherequiredoperationisdoneproperlybyALU and
memory.
• MemoryRegisters:
• A register is a temporary unit ofmemory in the CPU. These are used to store
thedatawhichisdirectlyusedbytheprocessor.Registerscanbeofdifferentsizes(16bit, 32
bit, 64 bit and so on) and each register inside the CPU has a specific function like
storing data, storing an instruction, storing address of a location in memory etc.
• Memory:
Memory attached to the CPU is used for storage of data and instructions and is
calledinternalmemoryTheinternalmemoryisdividedintomanystoragelocations, each
of which can store data or instructions. Each memory location is of the same size
and has an address.
• Theoutputunitconsistsofoutputdevicesthatareattachedwiththecomputer.It
converts the binary data coming from CPU to human understandable form. The
common output devices are monitor, printer, plotter etc.
InterconnectionbetweenFunctionalComponents
A computer consists of input unit that takes input, a CPU that processes the input
andanoutputunitthatproducesoutput.Allthesedevicescommunicatewitheach other
through a common bus.
Designed by J.Ravi Kumar

VAMSADHARA DEGREE COLLEGE

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

VAMSADHARA DEGREE COLLEGE

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

VAMSADHARA DEGREE COLLEGE

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

VAMSADHARA DEGREE COLLEGE

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

VAMSADHARA DEGREE COLLEGE

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

VAMSADHARA DEGREE COLLEGE

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

VAMSADHARA DEGREE COLLEGE

DisadvantagesofInterpreter

• TheinterpretercanrunonlythecorrespondingInterpretedprogram.
• InterpretedcoderunsslowerincomparisontoCompiledcode.
7) Concepts of Machine level, Assembly level and high-level
programming(concept of programming languages)

A programming language defines a set of instructions that are compiled together to


performaspecifictaskbytheCPU(CentralProcessingUnit).Theprogramminglanguage mainly
refers to high-level languages such as C, C++, Pascal, Ada, COBOL, etc.

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

VAMSADHARA DEGREE COLLEGE

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.

As we know that computers can only understand the machine-level instructions, so we


require a translator that converts the assembly code into machine code. The translator
used for translating the code is known as an assembler.

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.

High-Level Language: The high-level language is a programming language that allows


aprogrammertowritetheprogramswhichareindependentofaparticulartypeof
Designed by J.Ravi Kumar

VAMSADHARA DEGREE COLLEGE

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 Input/outputSymbol: The input symbol isusedtorepresent the input data, and


theoutputsymbolisusedtodisplaytheoutputoperation.Thesymbolgivenbelow
isusedforrepresentingtheInput/outputsymbol.

o Processing Symbol:It is represented in a flowchart with the help of a rectangle


boxusedtorepresentthearithmeticanddatamovementinstructions.Thesymbol
givenbelowisusedtorepresenttheprocessingsymbol.
Designed by J.Ravi Kumar

VAMSADHARA DEGREE COLLEGE

o Decision Symbol: Diamond symbol is used for represents decision-making


statements.Thesymbolgivenbelowisusedtorepresentthedecisionsymbol.

o Connector Symbol:The connector symbol is used if flows discontinued at some


point and continued again at another place. The following symbol is the
representation of the connector symbol.

o Flow lines: It represents the exact sequence in which instructions are executed.
Arrowsareusedtorepresenttheflowlinesinaflowchart.Thesymbolgivenbelow is used
for representing the flow lines:

AdvantagesofFlowchartinC:

Followingarethevariousadvantagesofflowchart:

o Communication: Aflowchartisabetterwayofcommunicatingthelogicofa program.


o Synthesis:Flowchart is used as working models in designing new programs and
software systems.
o EfficientCoding:Flowchartsactasaguideforaprogrammerinwritingtheactual code
in a high-level language.
o ProperDebugging:Flowchartshelpinthedebuggingprocess.
o Effective Analysis: Effective analysis of logical programs can be easily done with
the help of a related flowchart.
Designed by J.Ravi Kumar

VAMSADHARA DEGREE COLLEGE

o ProperDocumentation:Flowchartprovides betterandproper documentation.It


consistsofvariousactivitiessuchascollecting,organizing,storing,andmaintaining all
related program records.
o Testing:Aflowcharthelpsinthetesting process.
o Efficientprogrammaintenance:Themaintenanceoftheprogrambecomeseasy with
the help of a flowchart.

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

VAMSADHARA DEGREE COLLEGE

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:2 input the firsty number as B

Step:3if A = B

Then
print“equal”
else
PrintNotEqual“
Designed by J.Ravi Kumar

VAMSADHARA DEGREE COLLEGE

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:2 repeat step while I<=N

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

VAMSADHARA DEGREE COLLEGE

• 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.

History of C language is interesting to know. Here we are going to discuss a


briefhistory of the c language.

Cprogramminglanguage wasdevelopedin1972byDennisRitchieatbell laboratories


of AT&T (American Telephone & Telegraph), located in the U.S.A.
Designed by J.Ravi Kumar

VAMSADHARA DEGREE COLLEGE

DennisRitchie isknownasthe founderoftheclanguage.

Itwasdevelopedtoovercometheproblemsof previouslanguagessuchasB,BCPL,etc.

Initially,Clanguagewasdevelopedtobeusedin UNIXoperatingsystem.Itinherits many


features of previous languages such as B and BCPL.

Let'sseetheprogramminglanguagesthatweredevelopedbeforeC language.

Language Year DevelopedBy

Algol 1960 InternationalGroup

BCPL 1967 MartinRichard

B 1970 Ken Thompson

TraditionalC 1972 DennisRitchie

K&RC 1978 Kernighan&DennisRitchie

ANSIC 1989 ANSICommittee

ANSI/ISOC 1990 ISOCommittee

C99 1999 StandardizationCommittee

10. FeaturesofC
Designed by J.Ravi Kumar

VAMSADHARA DEGREE COLLEGE

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

Cisasimple languageinthe sense that itprovidesa structured approach(tobreakthe


problem into parts), the rich set of library functions, data types, etc.

2) MachineIndependentor Portable

Unlike assembly language, c programs can be executed on different machines with


some machine specific changes. Therefore, C is a machine independent language.

3) Mid-levelprogramminglanguage

Although, C isintended to do low-level programming. It is used to develop system


applications such as kernel, driver, etc. It also supports the features of a high-level
language. That is why it is known as mid-level language.

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

VAMSADHARA DEGREE COLLEGE

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

VAMSADHARA DEGREE COLLEGE

o KeywordsinC
o IdentifiersinC
o StringsinC
o OperatorsinC
o ConstantinC
o SpecialCharactersinC

Let'sunderstandeachtokenonebyone.

11) KeywordsinC

Keywords in Ccan be defined as the pre-definedor thereserved wordshaving its own


importance, and each keyword has its own functionality. Since keywords are the pre-
definedwordsusedbythecompiler,sotheycannotbeusedasthevariablenames.Ifthe
keywords are used as the variable names, it means that we are assigning a different
meaning to the keyword, which is not allowed. C language supports 32 keywords given
below:

auto double int struct

break else long switch

case enum register typedef


Designed by J.Ravi Kumar

VAMSADHARA DEGREE COLLEGE

char extern return union

const float short unsigned

continue for signed void

default goto sizeof volatile

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:

o The first character of an identifier should be either an alphabet or an underscore,


and then it can be followed by any of the character, digit, or underscore.
o Itshouldnotbeginwithanynumerical digit.
o Inidentifiers, bothuppercase andlowercase lettersare distinct. Therefore, we can
say that identifiers are case sensitive.
o Commasorblankspacescannotbespecifiedwithinanidentifier.
o Keywordscannotberepresentedasanidentifier.
o Thelengthoftheidentifiersshouldnotbemorethan31characters.
o Identifiersshould bewrittenin such awaythatitismeaningful,short, andeasyto read.

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

VAMSADHARA DEGREE COLLEGE

Now,wedescribethestringsindifferent ways:

chara[10]="javatpoint";//The compilerallocatesthe10bytestothe'a'array. char a[]

= "javatpoint"; // The compiler allocates the memory at the run time.

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

VAMSADHARA DEGREE COLLEGE

Operator Description Example

+ Addstwooperands. A + B= 30

– Subtractssecondoperandfromthefirst. A − B=-10

* Multipliesbothoperands. A *B= 200

/ 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

Operator Description Example

Checksifthevaluesoftwooperandsareequalor not. If (A==B)isnot


==
yes, then the condition becomes true. true.

Checks if the values of two operands are equal or


!= not.Ifthevaluesarenotequal,thenthecondition (A!= B) istrue.
becomestrue.
Designed by J.Ravi Kumar

VAMSADHARA DEGREE COLLEGE

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

Operator Description Example

CalledLogicalANDoperator.Ifboththeoperandsarenon- zero, (A&&B)


&&
then the condition becomes true. is false.

CalledLogicalOROperator.Ifanyofthetwooperandsis non- (A||B)is


||
zero, then the condition becomes true. true.

CalledLogicalNOTOperator. Itisusedtoreversethe
!(A&&B)
! logicalstateofitsoperand.Ifaconditionistrue,then
is true.
Logical NOT operator will make it false.
Designed by J.Ravi Kumar

VAMSADHARA DEGREE COLLEGE

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 1101

A^B=0011 0001

~A= 1100 0011

ThefollowingtableliststhebitwiseoperatorssupportedbyC.Assumevariable'A'holds 60 and
variable 'B' holds 13, then −

Example:

Operator Description Example


Designed by J.Ravi Kumar

VAMSADHARA DEGREE COLLEGE

BinaryANDOperatorcopiesabittotheresult ifitexistsinboth (A & B) = 12,


&
operands. i.e.,00001100

(A|B)=61,i.e.,
| BinaryOROperatorcopiesabitifitexistsineither operand.
0011 1101

BinaryXOROperatorcopiesthebitifitissetinoneoperand but not (A ^ B) = 49,


^
both. i.e.,00110001

BinaryOne'sComplementOperatorisunaryandhastheeffect of (~A)=~(60),
~
'flipping' bits. i.e,.-0111101

BinaryLeftShiftOperator.Theleftoperandsvalueismovedleft by the A<< 2= 240


<<
number of bits specified by the right operand. i.e., 1111 0000

BinaryRightShiftOperator.Theleftoperandsvalueismoved right by A>> 2= 15


>>
the number of bits specified by the right operand. i.e., 0000 1111

AssignmentOperators

ThefollowingtableliststheassignmentoperatorssupportedbytheClanguage− Show

Examples

Operator Description Example

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

VAMSADHARA DEGREE COLLEGE

Subtract AND assignment operator. It subtracts the right C -= A is


-= operandfromtheleftoperandandassignstheresulttotheleft equivalenttoC
operand. = C-A

Multiply AND assignment operator. It multiplies the right C *= A is


*= operandwiththeleftoperandandassignsthe resulttotheleft equivalenttoC
operand. = C*A

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

Besidestheoperatorsdiscussedabove,there areafewother importantoperators including


sizeof and ? : supported by the C Language.
Designed by J.Ravi Kumar

VAMSADHARA DEGREE COLLEGE

ShowExamples

Operator Description Example

sizeof(a),whereaisinteger,will
sizeof() Returnsthesizeof avariable.
return 4.

&a;returnstheactualaddressof the
& Returnstheaddressofavariable.
variable.

* Pointertoa variable. *a;

IfConditionistrue?thenvalueX:
?: ConditionalExpression.
otherwise value Y

15) ConstantsinC

Aconstantisavalueassignedtothevariable whichwillremainthesamethroughoutthe
program, i.e., the constant value cannot be changed.

TypesofconstantsinC

Constant Example

Integerconstant 10, 11,34,etc.

Floating-pointconstant 45.6,67.8,11.2, etc.

Octalconstant 011,088,022, etc.

Hexadecimalconstant 0x1a,0x4b,0x6b,etc.

Characterconstant 'a','b','c',etc.
Designed by J.Ravi Kumar

VAMSADHARA DEGREE COLLEGE

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

Youcanuseconstprefixtodeclareconstants withaspecifictype asfollows− const

type variable = value;

Example

#include<stdio.h>i
nt main() {
constintLENGTH=10;
Designed by J.Ravi Kumar

VAMSADHARA DEGREE COLLEGE

const intWIDTH =
5;constcharNEWLINE='\n';
int area;
area=LENGTH*WIDTH;
printf("valueofarea:%d",area); printf("%c",
NEWLINE);
return0;
}

Output:

valueofarea:50

16) Specialcharactersin C

SomespecialcharactersareusedinC,andtheyhavea specialmeaningwhichcannotbe used for


another purpose.

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

VAMSADHARA DEGREE COLLEGE

A data type specifies the type of data that a variable can store such as integer, floating,
character, etc.

TherearethefollowingdatatypesinClanguage.

Types DataTypes

BasicData Type int,char,float,double

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

VAMSADHARA DEGREE COLLEGE

DataTypes MemorySize Range

char 1byte −128to127

signedchar 1byte −128to127

unsignedchar 1byte 0to 255

short 2byte −32,768to32,767

signedshort 2byte −32,768to32,767

unsignedshort 2byte 0to 65,535

int 2byte −32,768to32,767

signed int 2byte −32,768to32,767

unsignedint 2byte 0to 65,535

shortint 2byte −32,768to32,767

signedshortint 2byte −32,768to32,767

unsignedshortint 2byte 0to 65,535

long int 4byte -2,147,483,648to2,147,483,647

signedlong int 4byte -2,147,483,648to2,147,483,647

unsignedlong int 4byte 0to 4,294,967,295


Designed by J.Ravi Kumar

VAMSADHARA DEGREE COLLEGE

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:

Individualcharactersarerepresentedbythe chardatatype.Typicallyusedto holdASCIIorUTF-


8encodingschemecharacters,suchasletters,numbers,symbols,
orcommas.Thereare256charactersthatcanberepresentedbyasinglechar,whichtakes
uponebyteofmemory.Characterssuchas'A','b','5',or'$'areenclosedinsinglequotes.

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

VAMSADHARA DEGREE COLLEGE

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.

int age = 25;


chargrade='A';
float temperature = 98.6;
doublepi=3.14159265359;

18)VariableandRulesforconstructingvariablenames

Avariableisanameofthememorylocation.Itisusedtostoredata.Itsvaluecanbe changed, and


it can be reused many times.

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

VAMSADHARA DEGREE COLLEGE

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

be declared at the start of the block.

voidfunction1()
{
intx=10;//localvariable
}

Youmusthavetoinitializethelocalvariablebeforeitisused.

2) Global Variable
Designed by J.Ravi Kumar

VAMSADHARA DEGREE COLLEGE

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

VAMSADHARA DEGREE COLLEGE

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

Itincludesthestatementspecifiedatthebeginningofaprogram,suchasa program's name,


date, description, and title. It is represented as:

//nameofaprogramOr/*Overviewof thecode.*/
Designed by J.Ravi Kumar

VAMSADHARA DEGREE COLLEGE

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:

floatnum= 2.54; inta= 5;charch ='z';

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.

main():Wecanalsouseintormainwiththemain().Thevoidmain()specifiesthattheprogram will not


return any value. The int main() specifies that the program can return integer type data. int
main() Orvoid main()

Main function is further categorized into local declarations,


statements, and expressions.
Designed by J.Ravi Kumar

VAMSADHARA DEGREE COLLEGE

The user defined functions specified the functions


6. User defined functions:
specified as per the requirements of the user. For example, color(), sum(),
division(), etc.

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

/* Sum ofthe two It is the comment section. Any statement described in it is


numbers */ not considered as a code. It is a part of the description
section in a code.
Thecommentlineisoptional.Itcanbeinaseparatelineor part of
an executable line.

#include<stdio.h> It isthe standardinput-output headerfile. It isacommand of


the preprocessor section.

intmain() main()isthefirstfunctiontobeexecutedineveryprogram. We
have used int with the main() in order to return an integer
value.
Designed by J.Ravi Kumar

VAMSADHARA DEGREE COLLEGE

{… Thecurlybracesmarkthebeginningandendofafunction. It is
} mandatory in all the functions.

printf() The printf() prints text on the screen. It is a function for


displaying constant or variables data. Here, 'Enter two
numbers to be added' is the parameter passed to it.

scanf() Itreadsdatafromthestandardinputstreamandwritesthe result


into the specified arguments.

sum =a +b Theadditionofthespecifiedtwonumberswillbepassedto the


sum parameter in the output.

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

VAMSADHARA DEGREE COLLEGE

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

VAMSADHARA DEGREE COLLEGE

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

VAMSADHARA DEGREE COLLEGE

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

VAMSADHARA DEGREE COLLEGE

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

VAMSADHARA DEGREE COLLEGE

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

VAMSADHARA DEGREE COLLEGE

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

VAMSADHARA DEGREE COLLEGE

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

VAMSADHARA DEGREE COLLEGE

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

VAMSADHARA DEGREE COLLEGE

//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

VAMSADHARA DEGREE COLLEGE

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

VAMSADHARA DEGREE COLLEGE

Switch(expression)

case value1:

//Statements

break;

casevalue2:

//Statements

break;

casevalue3:

//Statements

case value n:

//Statements

break;

Default:

//Statements

}
Designed by J.Ravi Kumar

VAMSADHARA DEGREE COLLEGE

switchstatementExample

#include<stdio.h>#include<conio

.h>

voidmain()

chargrade='B';

if(grade=='A')
Designed by J.Ravi Kumar

VAMSADHARA DEGREE COLLEGE

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

VAMSADHARA DEGREE COLLEGE

2)Iterative(or)loopingstatementsinc

Iterationisafundamentalconceptinprogrammingthatinvolvesrepeatingaspecificset
ofinstructionsmultipletimesuntilacertainconditionismet.InCprogramminglanguage, there
are three types of iteration statements:

i) forloop

ii) while loop

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.

Hereisanexampleofaforloop thatprintsthenumbersfrom1to10: Example:

#include<stdio.h>i
nt main() {
inti;
for (i=1;i<=10;i++){
Designed by J.Ravi Kumar

VAMSADHARA DEGREE COLLEGE

printf("%d\n",i);
}
return0;
}

Output:

1
2
3
4
5
6
7
8
9
10

ii) While Loop

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.

Hereisanexampleofawhileloopthatprints thenumbersfrom 1to10: Example:

#include<stdio.h>i
nt main() {
inti=1;
Designed by J.Ravi Kumar

VAMSADHARA DEGREE COLLEGE

while(i<=10){
printf("%d\n",i);
i++;
}
return0;
}

Output:

1
2
3
4
5
6
7
8
9
10

iii) Do-WhileLoop

Thedo-whileloopisusedtoexecutea setof statements repeatedlyaslong as a certain


condition istrue. The difference between the while loopand thedo-while loopis that
thedo-while loop executes the code inside the loop at least once before checking the
condition.

Thesyntaxof thedo-whileloop isas follows:

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

VAMSADHARA DEGREE COLLEGE

#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:

Thegoto statement is utilized to transfer control to a labeled statement in the same


function.Itisoftenconsideredbadpracticetouse goto statementsastheycanmakethe
Designed by J.Ravi Kumar

VAMSADHARA DEGREE COLLEGE

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

VAMSADHARA DEGREE COLLEGE

Thebreakstatement isutilizedtoexitaloopor switchstatement beforeitsnormal


termination. It is commonly utilized in loops to exit early if any specific condition is met.

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

VAMSADHARA DEGREE COLLEGE

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

Derived data types in C: Arrays: One Dimensional arrays - Declaration, Initialization


and Memory representation; Two Dimensional arrays -Declaration, Initialization and
Memoryrepresentation.Strings:Declaring& initializingstringvariables;Stringhandling
functions, Character handling functions

DeriveddatatypesinC
Designed by J.Ravi Kumar

VAMSADHARA DEGREE COLLEGE

1. OneDimensionalarrays-Declaration,InitializationandMemory
representation

An array is defined as the collection of similar type of data items stored at


contiguous memory locations. Arrays are the derived data type in C programming
languagewhichcanstoretheprimitivetypeofdatasuchasint,char,double,float,etc.It also has
the capability to store the collection of derived data types, such as pointers, structure,
etc. The array is the simplest data structure where each data element can be randomly
accessed by using its index number.

Anarraywhichishavingtheonesubscriptiscalledonedimensionalarray

Declaration of one dimensional Array

Wecandeclareanarrayintheclanguageinthefollowingway.

datatypearrayname[array_size];

Example to declare the array.

intmarks[5];

Here,intisthedatatype,marksarethearrayname,and5isthearray_size. Initialization of

one dimemsional Array

Thesimplestwaytoinitializeanarrayisbyusingtheindexofeachelement.Wecan initialize each


element of the array by using the index. Consider the following example.

marks[0]=80;//initializationofarray
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;
Designed by J.Ravi Kumar

VAMSADHARA DEGREE COLLEGE

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

Arraysare representedwithdiagramsthatrepresenttheirmemoryuseonthecomputer. These


are represented by the square boxes that represent every bit of the memory. We
Designed by J.Ravi Kumar

VAMSADHARA DEGREE COLLEGE

canwritethevalueoftheelementinsidethe box.Belowisthefigurethatrepresentsthe memory


representation in an array.

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;

Intheexampleabove,‘a’isthe pointertothememoryforallofitselements.Now, inthe


computer memory, there is an allocation of the data bit like follows:
Designed by J.Ravi Kumar

VAMSADHARA DEGREE COLLEGE

2.)Two Dimensional arrays-Declaration, Initializationand


Memoryrepresentation

Thetwo-dimensionalarraycanbedefinedasanarrayofarrays.The2Darrayisorganized
asmatriceswhichcanberepresentedasthecollectionofrowsandcolumns.However,2D
arraysarecreatedtoimplementarelationaldatabaselookalikedatastructure.Itprovides
easeofholdingthebulkofdataatoncewhichcanbepassedtoanynumberoffunctions herever
required.

Anarraywhichishavingtwosubscriptsarecalledtwodimensionalarray Declaration of

two dimensional Array in C

Thesyntaxtodeclarethe2Darrayisgivenbelow. Data

type array name[rows][columns]; Consider the

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

VAMSADHARA DEGREE COLLEGE

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

In memory, a 2-dimensional array is typically represented as a contiguous block of


memorycells.Theelementsofthearrayarestoredrowbyrow,witheachrowoccupying a
continuous segment of memory. The memory map follows a row-major order, meaning
that the elements of each row are stored together.

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:

address=base_address+(i* columns+j)* element_size

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

VAMSADHARA DEGREE COLLEGE

ExampleofMemoryMapof a2-DimensionalIntegerArray:

Let’sconsidera2-dimensionalarrayof integerswith3rowsand4columns:

intarray[3][4];

Inmemory,thearraywouldberepresentedas acontiguousblockof12integers.The memory


map would look like this:

array[0][0] --> address1

array[0][1] --> address2

array[0][2] --> address3

array[0][3] --> address4

array[1][0] --> address5

array[1][1] --> address6

array[1][2] --> address7

array[1][3] --> address8

array[2][0] --> address9

array[2][1]-->address10

array[2][2]-->address11

array[2][3]-->address12

Strings

3)Declaring&initializingstringvariables
Designed by J.Ravi Kumar

VAMSADHARA DEGREE COLLEGE

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

VAMSADHARA DEGREE COLLEGE

o The string literal cannot be reassigned to another set of characters whereas,


wecan reassign the characters of the array.

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

Char Array Value is: javatpoint


StringLiteralValueis:javatpoint

4.Stringhandlingfunctions(or)operations(or)manipulationsinc

Therearemanyimportantstringfunctionsdefinedin"string.h"library.

No. Function Description

1) strlen(string_name) returnsthelengthofstring name.

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

VAMSADHARA DEGREE COLLEGE

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

Thestrlen()functionreturnsthelengthofthe givenstring.Itdoesn'tcountnullcharacter '\0'.

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

VAMSADHARA DEGREE COLLEGE

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

VAMSADHARA DEGREE COLLEGE

#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:

Enter 1st string: hello


Enter2ndstring:hello
Strings are equal
5. ReverseString:strrev()

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

VAMSADHARA DEGREE COLLEGE

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:

Enter string: JAVATpoint


String is: JAVATpoint
LowerStringis:javatpoint
7. StringUppercase:strupr()

Thestrupr(string)functionreturnsstringcharactersinuppercase.Let'sseeasimple example
of strupr() function.

Example:

#include<stdio.h>#
include<string.h>i
nt main(){
Designed by J.Ravi Kumar

VAMSADHARA DEGREE COLLEGE

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.

Differentcharacter functions provided byC Language are:

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

punctuator ornot. Punctuatorsare comma, semicolon etc.


Designed by J.Ravi Kumar

VAMSADHARA DEGREE COLLEGE

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

capital letteralphabetor not.


Designed by J.Ravi Kumar

VAMSADHARA DEGREE COLLEGE

7. islower()
This function checks whether the character variable/constantcontains a

lowercase alphabet or not.

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

VAMSADHARA DEGREE COLLEGE

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

Afunctionprototypeissimplythe declarationofafunctionthatspecifiesfunction's name,


parameters and return type. It doesn't contain function body.
Designed by J.Ravi Kumar

VAMSADHARA DEGREE COLLEGE

Afunctionprototypegivesinformationtothecompilerthatthefunctionmaylaterbe used in
the program.

Syntaxoffunctionprototype

returnTypefunctionName(type1argument1,type2argument2............... );

Intheabove example, intaddNumbers(inta,intb); isthefunctionprototypewhich


providesthefollowinginformationtothecompiler:
name of the function is addNumbers()
returntypeofthefunctionisint
twoargumentsoftypeintarepassedtothe function
Thefunctionprototypeisnotneedediftheuser-definedfunctionisdefinedbefore
the main() function.

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

VAMSADHARA DEGREE COLLEGE

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

VAMSADHARA DEGREE COLLEGE

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

VAMSADHARA DEGREE COLLEGE

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

VAMSADHARA DEGREE COLLEGE

Nested function is not supported by C because we cannot define a function within


another function in C. We can declare a function inside a function, but it’s not a nested
function.
Because nested functions definitions can not access local variablesof the surrounding
blocks, they can access only global variables of the containing module. This is done so
that lookup of global variables doesn’t have to go through the directory. As in C, there
are two nested scopes: local and global (and beyond this, built-ins). Therefore, nested
functions have only a limited use. If we try to approach nested function in C, then we
will get compile time error.
Syntax:

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

VAMSADHARA DEGREE COLLEGE

#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

Dependingon whether arguments are present or not andwhether avalue is returnedor


not, functions are categorized into −

• Functionswithoutargumentsandwithoutreturnvalues
• Functionswithoutargumentsandwithreturnvalues
• Functionswithargumentsandwithoutreturnvalues
• Functionswithargumentsandwithreturnvalues
Designed by J.Ravi Kumar

VAMSADHARA DEGREE COLLEGE

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

VAMSADHARA DEGREE COLLEGE

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

VAMSADHARA DEGREE COLLEGE

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

VAMSADHARA DEGREE COLLEGE

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

VAMSADHARA DEGREE COLLEGE

Recursioninvolvesseveralnumbersof recursivecalls. However, itisimportant toimpose a


termination condition of recursion.

Recursioncodeisshorterthaniterativecodehoweveritisdifficultto understand.

Recursioncannotbeappliedtoalltheproblem,butitismoreusefulforthetasksthatcan be
defined in terms of similar subtasks.

For Example, recursion may be applied to sorting, searching, and traversal


problems.

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

VAMSADHARA DEGREE COLLEGE

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

VAMSADHARA DEGREE COLLEGE

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

VAMSADHARA DEGREE COLLEGE

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

VAMSADHARA DEGREE COLLEGE

*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

VAMSADHARA DEGREE COLLEGE

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.

Whatisa Local Variable?


o Variables that are declared within or inside a function block are known as
Local variables.
o Thesevariablescanonlybeaccessedwithinthefunctioninwhichtheyaredeclared.
o Thelifetimeofthelocalvariableiswithinitsfunctiononly,whichmeansthevariable exists
till the function executes. Once function execution is completed, local variables
are destroyed and no longer exist outside the function.
o Thereasonforthelimitedscopeoflocalvariablesisthatlocalvariablesarestored
inthestack,whichisdynamicinnatureandautomaticallycleansupthedatastored within
it.
o But by makingthe variable static with "static" keyword, we can retain the value of
local variable.

Example:

#include<stdio.h>
Designed by J.Ravi Kumar

VAMSADHARA DEGREE COLLEGE

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

VAMSADHARA DEGREE COLLEGE

Defaultvalue: Anunpredictablevalue(garbagevalue)

Scope: localtotheblockinwhichitis defined.


Lifetime:Tillthecontrolremainswithintheblockinwhichthevariableisdefined.
Example
#include<stdio.h>
intmain()
{
autointa;
char b;
float c;
printf("%d%c %f",a,b,c);
}

Output:

garbagegarbagegarbage

Static
Staticstorageclass:featureofavariabledefinedisregisterstorageclassas

Keyword:static

Storage:

mainmemory

Defaultvalue:
zero

Scope: localtotheblockinwhichitis defined.


Lifetime:valueofthevariablepresentsbetweendifferentfunctioncalls
Example:
#include<stdio.h>
static char c;
static int i;
static float f;
staticchars[100];
void main ()
{
Designed by J.Ravi Kumar

VAMSADHARA DEGREE COLLEGE

printf("%d%d%f%s",c,i,f);.
}

Output:

00 0.000000(null)
Register
Registerstorageclass:thefeatureofavariabledefinedisregisterstorageclassas

Keyword:register

Storage:CPU registers

Defaultvalue:Anunpredictablevalue(garbagevalue)

Scope: localtotheblockinwhichitis defined.


Lifetime:Tillthecontrolremainswithintheblockinwhichthevariableisdefined.
Example
#include<stdio.h>
intmain()
{
register int a;
printf("%d",a);
}

Output:0

External
ExternalStorageclass:featureofavariabledefinedisregisterstorageclassas

Keyword:
externStorage:
mainmemory

Defaultvalue:
zero

Scope:global

Lifetime:Aslongastheprogramexecutiondoesn‟tcomestoend.
Example
#include<stdio.h>
Designed by J.Ravi Kumar

VAMSADHARA DEGREE COLLEGE

inta;
intmain()
{
extern int a;
printf("%d",a);
}

Output:0

Pointers:

9. Pointer data type, Pointer declaration, initialization, accessing values


using pointers in c

Pointerdatatype:

The pointerinC language isavariable whichstoresthe addressof anothervariable. This


variable can be of type int, char, array, function, or any other pointer. The size of the
pointerdependsonthearchitecture.However,in32-bitarchitecturethesizeofapointer
is2byte. Considerthefollowingexampleto defineapointer which storestheaddress of an
integer.

intn=10;
int*p=&n;

Pointerdeclaration,initialization,accessingvaluesusingpointers Pointer

declaration, initialization and accessing


Considerthefollowingstatement

Declaringapointer

int *ptr;
Designed by J.Ravi Kumar

VAMSADHARA DEGREE COLLEGE

‘ptr’isapointervariablethatholdstheaddressof anotherintegervariable.

Initializationofa pointer

Addressoperator(&)isusedtoinitializeapointervariable.

inta=44;
int *b;
b=&a;

Let’sconsider anexamplehowthepointerisusefulinaccessingtheelementsin anarray of


string.
Designed by J.Ravi Kumar

VAMSADHARA DEGREE COLLEGE

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

VAMSADHARA DEGREE COLLEGE

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

Like increment, we can decrement a pointer variable. If we decrement a pointer, it will


start pointingtotheprevious location. Theformulaof decrementingthepointerisgiven
below:

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

VAMSADHARA DEGREE COLLEGE

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

VAMSADHARA DEGREE COLLEGE

printf("Addressofpvariableis%u\n",p);
p=p-3;
printf("Aftersubtracting3:Addressofpvariableis%u \n",p);
return0;
}

Output

Addressofpvariableis3214864300
Aftersubtracting3:Addressofpvariableis3214864288
11.Pointersandarraysin c
Pointer

Address of a variable in memory


Allowsustoindirectlyaccessvariables
inotherwords,wecantalkaboutitsaddressratherthanitsvalue
Arrays:

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?

CArray: Syntax and Declaration


Designed by J.Ravi Kumar

VAMSADHARA DEGREE COLLEGE

PointersandarraysinC:

RelationshipbetweenArraysandPointers

Example:

#include<stdio.h>

#define N 5

intmain(){
Designed by J.Ravi Kumar

VAMSADHARA DEGREE COLLEGE

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

Basis for Pointer Array


Comparison

Declaration //InC++type*var_name; //In C++type var_name[size];//In


Java.type var-name[ ];var_name = new
type[size];

Working It generally stores the address Arrayusuallystoresthevalueofthe variable


ofanothervariableofthesame of the same datatype.
data type as the pointer
variable's datatype.

Generation Apointertoanarraycanbe Anarrayofpointerscanbe generated.


generated.

Storage Pointersarespeciallydesigned A normal array stores values of variables,


to store the address of and pointer array stores the address of
variables. variables.

Capacity Usually, arrays can store the Apointervariablecanstoretheaddressof


number of elements the same only one variable at a time.
size as the size of the array
variable.
Designed by J.Ravi Kumar

VAMSADHARA DEGREE COLLEGE

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

VAMSADHARA DEGREE COLLEGE

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;

printf("Initialvalueofp=%dandq=%d\n", p,q); test( p,

&q );

printf("Afterpassesto testfunction: p=%d, q=%d\n",p,q);


Designed by J.Ravi Kumar

VAMSADHARA DEGREE COLLEGE

return0;

Output:

Initialvalueofp=10 andq =20

Afterpassesto testfunction: p=10, q=200

UNIT-V

Dynamic Memory Management: Introduction, Functions-malloc, calloc, realloc, free


Structures:Basicsofstructure,structuremembers,accessingstructuremembers,nested
structures, array of structures, structure and functions, structures and pointers. Unions -
Union definition; difference between Structures and Unions.

1. DynamicMemoryManagement:Introduction,Functions-malloc,
calloc, realloc, free in c

The concept of dynamic memory allocation in c language enables the C programmer


toallocatememoryatruntime.Dynamicmemoryallocationinclanguageispossibleby4
functions of stdlib.h header file.

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

memoryisallocatedatcompile time. memoryisallocatedatrun time.

memory can't be increased while executing memory can be increased while executin
program. program.
Designed by J.Ravi Kumar

VAMSADHARA DEGREE COLLEGE

usedinarray. usedinlinked list.

Nowlet'shaveaquicklookatthemethodsusedfordynamicmemory allocation.

malloc() allocatessingleblockofrequestedmemory.

calloc() allocatesmultipleblockofrequestedmemory.

realloc() reallocatesthememoryoccupiedbymalloc()orcalloc() functions.

free() freesthedynamicallyallocatedmemory.

1. malloc()functioninC

Themalloc()functionallocatessingleblockofrequestedmemory.

Itdoesn'tinitializememoryatexecutiontime, soithasgarbagevalueinitially. It

returns NULL if memory is not sufficient.

Thesyntaxofmalloc():

ptr=(cast-type*)malloc(byte-size);

Example of malloc() function.

#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

VAMSADHARA DEGREE COLLEGE

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

Enter elements of array: 3


Enterelementsofarray:10 10
10
Sum=30

2. calloc()functioninC

Thecalloc()functionallocatesmultipleblockofrequestedmemory. It

initially initialize all bytes to zero.

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

VAMSADHARA DEGREE COLLEGE

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

Enter elements of array: 3


Enterelementsofarray:10 10
10
Sum=30
3.realloc()functioninC:Ifmemoryisnotsufficientformalloc()orcalloc(),youcan reallocate
the memory by realloc() function. In short, it changes the memory size.

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

VAMSADHARA DEGREE COLLEGE

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

VAMSADHARA DEGREE COLLEGE

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

VAMSADHARA DEGREE COLLEGE

}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

VAMSADHARA DEGREE COLLEGE

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

VAMSADHARA DEGREE COLLEGE

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;

Asyoucansee,doj(dateofjoining)is thevariableoftypeDate.Heredojis used asa


memberinEmployeestructure.Inthisway,wecanuseDatestructureinmanystructures.
Designed by J.Ravi Kumar

VAMSADHARA DEGREE COLLEGE

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

Anarray ofstructresinCcan bedefined asthecollectionofmultiplestructuresvariables


whereeachvariablecontainsinformationabout different entities. Thearrayof
structuresinCareusedtostoreinformationaboutmultipleentitiesofdifferentdatatypes.Thearr
ay of structures is also known as the collection of structures.
Designed by J.Ravi Kumar

VAMSADHARA DEGREE COLLEGE

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

VAMSADHARA DEGREE COLLEGE

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?

Consideracase, where we needtostore the dataof 5students. We canstore it by using the


structure as given below.

#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

VAMSADHARA DEGREE COLLEGE

Output

Enter the name, id, and marks of student 1 James 90 90


Enterthename,id,andmarksofstudent2Adoms9090 Enter the
name, id, and marks of student 3 Nick 90 90 Printing the
details....
James9090.000000
Adoms9090.000000
Nick9090.000000
In the above program, we have stored data of 3 students in the structure. However, the
complexity of the program will be increasedif there are 20 students. Inthat case, we will
havetodeclare20differentstructurevariablesandstorethemonebyone.Thiswillalways be
tough since we will have to declare a variable every time we add a student.
Remembering the name of all the variables is also a very tricky task. However, c enables
us to declare an array of structures by using which, we can avoid declaring the different
structurevariables;insteadwecanmakeacollectioncontainingallthestructuresthat
storetheinformationofdifferententities.
5. structureandfunctionsinc

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.

Thedot(.)operatorisusedtoaccessastructure member.Thearrow(->)operatoristo access


the members of a structure when the pointer references the structure.

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

VAMSADHARA DEGREE COLLEGE

#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

VAMSADHARA DEGREE COLLEGE

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

Thestructure pointerpoints to the address of a memory block where the Structure is


beingstored.Likeapointerthattellstheaddressofanothervariableofanydatatype(int, char,
float) in memory. And here, we use a structure pointer which tells the address of a
structure in memory by pointing pointer variable ptr to the structure variable.

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

VAMSADHARA DEGREE COLLEGE

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

VAMSADHARA DEGREE COLLEGE

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

VAMSADHARA DEGREE COLLEGE

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

VAMSADHARA DEGREE COLLEGE

• 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;

printf("The value stored in member1 = %d", var1.member1);

return 0;}

Output
Thevaluestoredinmember1=15
Designed by J.Ravi Kumar

VAMSADHARA DEGREE COLLEGE

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;
};

In"c,"programming unionisauser-defineddatatypethatisusedtostorethedifferent data


type's values. However, in the union, one member will occupy the memory at once.
Inotherwords,wecansaythatthesizeoftheunionisequaltothesizeofitslargestdata
membersize.Unionoffersaneffectivewaytousethesamememorylocationseveraltimes
byeachdatamember.Theunionkeywordisusedtodefineandcreateauniondatatype.

Syntax of Union

union[unionname]
{
type member_1;
Designed by J.Ravi Kumar

VAMSADHARA DEGREE COLLEGE

type member_2;
...
type member_n;
};

Example

unionemployee
{
string
name;stringdepart
ment; int phone;
stringemail;
};
DifferencebetweenStructureand Union

Struct Union

1.Thestructkeywordisusedtodefinea Theunionkeywordisusedtodefine union.


structure.

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.

3.Eachvariablememberoccupieda Variables members share the memory space


unique memory space. of the largest size variable.
Designed by J.Ravi Kumar

VAMSADHARA DEGREE COLLEGE

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.

5.Each variable member will Onlyonevariablememberwillbeassessedat a


beassessed at a time. time.

6.Wecaninitializemultiplevariablesof In union, only the first data member can be


astructureata time. initialized.

7.Allvariablemembersstoresome value Exactly only one data member stores a value


at any point in the program. at any particular instance in the program.

8.The structure allows Unionallowsinitializingonlyonevariable


initializingmultiple variable member at once.
members at once.

9.It is used to store different data type Itisusedforstoringoneatatimefromdifferent


values. data type values.

10.Itallowsaccessingandretrieving any Itallowsaccessingandretrievinganyone data


data member at a time. member at a time.

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:

You might also like