The document provides an overview of algorithms and computational complexity. It defines an algorithm as a set of unambiguous steps to solve a problem, and discusses how algorithms can be expressed using different languages. It then covers algorithmic complexity and how to analyze the time complexity of algorithms using asymptotic notation like Big-O notation. Specific time complexities like constant, linear, logarithmic, and quadratic time are defined. The document also discusses flowcharts as a way to represent algorithms graphically and introduces some basic programming concepts.
PE 459 LECTURE 2- natural gas basic concepts and properties
Basic Computer Engineering Unit II as per RGPV Syllabus
1. BCE/UNIT II Truba College of Science & Technology,
Bhopal
By: Ms. Nandini Sharma [CSE Deptt.] Page 1
1. Definition
A formula or set of steps for solving a particular problem. To be an algorithm, a set of rules
must be unambiguous and have a clear stopping point. Algorithms can be expressed in
any language, from natural languages like English or French to programming
languages like FORTRAN.
We use algorithms every day. For example, a recipe for baking a cake is an algorithm.
Most programs, with the exception of some artificial intelligence applications, consist of
algorithms. Inventing elegant algorithms -- algorithms that are simple and require the fewest
steps possible -- is one of the principal challenges in programming.
2. Introduction
Algorithmic complexity is concerned about how fast or slow particular algorithm performs. We
define complexity as a numerical function T(n) - time versus the input size n. We want to define
time taken by an algorithm without depending on the implementation details. But you agree
that T(n) does depend on the implementation! A given algorithm will take different amounts of
time on the same inputs depending on such factors as: processor speed; instruction set, disk
speed, brand of compiler and etc. The way around is to estimate efficiency of each
algorithm asymptotically. We will measure time T(n) as the number of elementary "steps"
(defined in any way), provided each such step takes constant time.
2. BCE/UNIT II Truba College of Science & Technology,
Bhopal
By: Ms. Nandini Sharma [CSE Deptt.] Page 2
Let us consider two classicalexamples: addition of two integers. We will add two integers digit
by digit (or bit by bit), and this will define a "step" in our computational model. Therefore, we
say that addition of two n-bit integers takes n steps. Consequently, the total computational
time is T(n) = c * n, where c is time taken by addition of two bits. On different computers,
addition of two bits might take different time, say c1 and c2, thus the addition of two n-bit
integers takes T(n) = c1 * nand T(n) = c2* n respectively. This shows that different machines
result in different slopes, but time T(n) grows linearly as input size increases.
The process of abstracting away details and determining the rate of resource usage in terms of
the input size is one of the fundamental ideas in computer science.
Asymptotic Notations
The goal of computational complexity is to classify algorithms according to their performances.
We will represent the time function T(n) using the "big-O" notation to express an algorithm
runtime complexity. For example, the following statement
T(n) = O(n2)
says that an algorithm has a quadratic time complexity.
Definition of "big Oh"
For any monotonic functions f(n) and g(n) from the positive integers to the positive integers, we
say that f(n) = O(g(n)) when there exist constants c > 0 and n0 > 0 such that
f(n) ≤ c * g(n), for all n ≥ n0
Intuitively, this means that function f(n) does not grow faster than g(n), or that function g(n) is
an upper bound for f(n), for all sufficiently large n→∞
Here is a graphic representation of f(n) = O(g(n)) relation:
3. BCE/UNIT II Truba College of Science & Technology,
Bhopal
By: Ms. Nandini Sharma [CSE Deptt.] Page 3
Examples:
1 = O(n)
n = O(n2)
log(n) = O(n)
2 n + 1 = O(n)
The "big-O" notation is not symmetric: n = O(n2) but n2 ≠ O(n).
Exercise. Let us prove n2 + 2 n + 1 = O(n2). We must find such c and n0 that n 2 + 2 n + 1 ≤ c*n2.
Let n0=1, then for n ≥ 1
1 + 2 n + n2 ≤ n + 2 n + n2 ≤ n2 + 2 n2 + n 2 = 4 n2
Therefore, c = 4.
Constant Time: O(1)
An algorithm is said to run in constant time if it requires the same amount of time regardless of
the input size. Examples:
array: accessing any element
fixed-size stack: push and pop methods
fixed-size queue: enqueue and dequeue methods
4. BCE/UNIT II Truba College of Science & Technology,
Bhopal
By: Ms. Nandini Sharma [CSE Deptt.] Page 4
Linear Time: O(n)
An algorithm is said to run in linear time if its time execution is directly proportional to the
input size, i.e. time grows linearly as input size increases. Examples:
array: linear search, traversing, find minimum
ArrayList: contains method
queue: contains method
Logarithmic Time: O(log n)
An algorithm is said to run in logarithmic time if its time execution is proportional to the
logarithm of the input size. Example:
binary search
Recall the "twenty questions" game - the task is to guess the value of a hidden number in an
interval. Each time you make a guess, you are told whether your guess iss too high or too low.
Twenty questions game implies a strategy that uses your guess number to halve the interval
size. This is an example of the general problem-solving method known as binary search:
locate the element a in a sorted (in ascending order) array by first comparing a with the
middle element and then (if they are not equal) dividing the array into two subarrays; if
a is less than the middle element you repeat the whole procedure in the left subarray,
otherwise - in the right subarray. The procedure repeats until a is found or subarray is a
zero dimension.
Note, log(n) < n, when n→∞. Algorithms that run in O(log n) does not use the whole input.
Quadratic Time: O(n2)
An algorithm is said to run in logarithmic time if its time execution is proportional to the square
of the input size. Examples:
bubble sort, selection sort, insertion sort
Definition of "big Omega"
We need the notation for the lower bound. A capital omega Ω notation is used in this case. We
say that f(n) = Ω(g(n)) when there exist constant c that f(n) ≥ c*g(n) for all sufficiently large n.
Examples
n = Ω(1)
5. BCE/UNIT II Truba College of Science & Technology,
Bhopal
By: Ms. Nandini Sharma [CSE Deptt.] Page 5
n2 = Ω(n)
n2 = Ω(n log(n))
2 n + 1 = O(n)
Definition of "big Theta"
To measure the complexity of a particular algorithm, means to find the upper and lower
bounds. A new notation is used in this case. We say that f(n) = Θ(g(n)) if and only f(n) = O(g(n))
and f(n) = Ω(g(n)). Examples
2 n = Θ(n)
n2 + 2 n + 1 = Θ( n2)
Analysis of Algorithms
The term analysis of algorithms is used to describe approaches to the study of the performance
of algorithms. In this course we will perform the following types of analysis:
the worst-case runtime complexity of the algorithm is the function defined by the
maximum number of steps taken on any instance of size a.
the best-case runtime complexity of the algorithm is the function defined by the
minimum number of steps taken on any instance of size a.
the average case runtime complexity of the algorithm is the function defined by an
average number of steps taken on any instance of size a.
the amortized runtime complexity of the algorithm is the function defined by a sequence
of operations applied to the input of size a and averaged over time.
Example. Let us consider an algorithm of sequential searching in an array of size n.
Its worst-case runtime complexity is O(n)
Its best-case runtime complexity is O(1)
Its average case runtime complexity is O(n/2)=O(n)
3. Flowchart
A flowchartis a graphical or symbolicrepresentationof aprocess.Each stepin the processis
representedbyadifferentsymbolandcontainsashort descriptionof the processstep.The flow
chart symbolsare linkedtogetherwith arrowsshowingthe processflow direction.
Process/ OperationSymbols
6. BCE/UNIT II Truba College of Science & Technology,
Bhopal
By: Ms. Nandini Sharma [CSE Deptt.] Page 6
SYMBOL
NAME DESCRIPTION
Process
Show a Processor action step.Thisisthe most
commonsymbol inbothprocessflowchartsand
processmaps.
Predefined
Process
(Subroutine)
A PredefinedProcesssymbol isamarkerforanother
processstepor seriesof processflow stepsthatare
formallydefinedelsewhere.Thisshape commonly
depictssub-processes(orsubroutinesinprogramming
flowcharts).If the sub-processisconsidered"known"
but notactuallydefinedinaprocessprocedure,work
instruction,orsome otherprocessflowchartor
documentation,thenitisbestnottouse thissymbol
since itimpliesaformallydefinedprocess.
Alternate
Process
As the shape name suggests, thisflowchartsymbolis
usedwhenthe processflow stepisanalternate tothe
normal processstep.Flow linesintoanalternate
processflow stepare typicallydashed.
Delay
The Delayflowchartsymbol depictsanywaitingperiod
that ispart of a process.Delayshapesare commonin
processmapping.
Preparation
As the namesstates,anyprocessstepthat isa
Preparationprocessflow step,suchasa set-up
operation.
Manual
Operation
Manual Operationsflowchartshapesshowwhich
processstepsare not automated.Indata processing
flowcharts,thisdataflow shape indicatesalooping
7. BCE/UNIT II Truba College of Science & Technology,
Bhopal
By: Ms. Nandini Sharma [CSE Deptt.] Page 7
SYMBOL
NAME DESCRIPTION
operationalongwithalooplimitsymbol (whichisnot
supportedbyMicrosoftOffice,butaManual
Operationsymbol rotated180° will dothe trick.)
Branching and Control of Flow Symbols
SYMBOL
NAME
(ALIAS)
DESCRIPTION
FlowLine
(Arrow,
Connector)
Flow line connectorsshow the directionthat
the processflows.
Terminator
(Terminal Point,
Oval)
Terminatorsshow the startand stop pointsina
process.Whenusedas a Start symbol,
terminatorsdepictatrigger action that setsthe
processflow intomotion.
Decision
Indicatesaquestionorbranch inthe process
flow.Typically,aDecision flowchartshape is
usedwhenthere are 2 options(Yes/No,No/No-
Go, etc.)
Connector
(Inspection)
Ad byNew Saver. More Info | Hide These Ads
Flowchart: In flowcharts,thissymbol istypically
small andis usedas a Connectortoshowa
jumpfromone pointin the processflowto
another.Connectorsare usuallylabelledwith
capital letters(A,B,AA) to show matchingjump
points.Theyare handyfor avoidingflowlines
that cross othershapesandflow lines.Theyare
8. BCE/UNIT II Truba College of Science & Technology,
Bhopal
By: Ms. Nandini Sharma [CSE Deptt.] Page 8
SYMBOL
NAME
(ALIAS)
DESCRIPTION
alsohandyfor jumpingtoand froma sub-
processesdefinedinaseparate areathanthe
mainflowchart.
ProcessMapping: In processmaps,thissymbol
isfull sizedandshowsanInspectionpointinthe
processflow.
[Justto confusethingsfurther,somepeoplewill
use a circle to indicatean operation and a
squareto indicate an inspection.That's why it's
importantto include a symbolkey in the
flowchart.]
Off-Page
Connector
Off-Page Connectorshowscontinuationof a
processflowchartontoanotherpage.When
usingtheminconjunctionwithConnectors,it's
bestto differentiatethe labels,e.g. use
numbersforOff-Page Connectorsandcapital
lettersforConnectors.Inactual practice,most
flowchartsjustuse the Connectshape forboth
on-page andoff-page references.
Merge
(Storage)
Flowchart: Showsthe mergingof multiple
processesorinformationintoone.
ProcessMapping: commonlyindicatesstorage
of raw materials.
Extract
(Measurement)
Flowchart: Showswhena processsplitsinto
parallel paths.Alsocommonlyindicatesa
Measurement,withacapital 'M' inside the
symbol.
ProcessMapping: commonlyindicatesstorage
9. BCE/UNIT II Truba College of Science & Technology,
Bhopal
By: Ms. Nandini Sharma [CSE Deptt.] Page 9
SYMBOL
NAME
(ALIAS)
DESCRIPTION
of finishedgoods.
Or
The logical Or symbol showswhenaprocess
diverges - usuallyformore than2 branches.
Whenusingthissymbol,itisimportanttolabel
the out-goingflow linestoindicate the criteria
to follow eachbranch.
Summing
Junction
The logical SummingJunctionflowchartshape is
showswhenmultiple branchesconverge intoa
single process.The merge symbol ismore
commonfor thisuse,though.Thissymbol and
the Or symbol are reallymore relevantindata
processingflow diagramsthaninprocess
flowcharts.
Inputand OutputSymbols
SYMBOL
NAME
(ALIAS)
DESCRIPTION
Data
(I/O)
The Data flowchartshape indicatesinputstoandoutputsfroma process.As
such,the shape ismore often referredtoasan I/O shape thana Data shape.
Document
Prettyself explanatory - the Documentflowchartsymbol isforaprocess
stepthat producesa document.
10. BCE/UNIT II Truba College of Science & Technology,
Bhopal
By: Ms. Nandini Sharma [CSE Deptt.] Page 10
SYMBOL
NAME
(ALIAS)
DESCRIPTION
Multi-
Document
Same as Document,except,well,multiple documents.Thisshape isnotas
commonlyusedasthe Documentflowchartshape,evenwhenmultiple
documentsare implied.
Display
Indicatesaprocessstepwhere informationisdisplayedtoaperson(e.g.,PC
user,machine operator).
Manual
Input
Manual Inputflowchartshapesshow processstepswherethe operator/
useris promptedforinformationthatmustbe manuallyinputintoasystem.
Card
Thisis the companiontothe punchedtape flowchartshapes.Thisshape is
seldomused.
Punched
Tape
If you're verygoodat stretching all the life outof a machine,youmaystill
have use for the PunchedTape symbol - usedforinputintooldcomputers
and CNCmachines.
File andInformationStorage Symbols
SYMBOL
NAME
(ALIAS)
DESCRIPTION
StoredData
A general DataStorage flowchart shape usedforany processstepthat
storesdata (asopposedtothe more specificshapestofollownextinthis
table).
11. BCE/UNIT II Truba College of Science & Technology,
Bhopal
By: Ms. Nandini Sharma [CSE Deptt.] Page 11
SYMBOL
NAME
(ALIAS)
DESCRIPTION
MagneticDisk
(Database)
The most universallyrecognizable symbolforadata storage location,this
flowchartshape depictsa database.
DirectAccess
Storage
DirectAccessStorage is a fancyway of sayingHard Drive.
Internal Storage
Usedin programmingflowchartstomeaninformationstoredinmemory,as
opposedtoon a file.
Sequential
AccessStorage
(MagneticTape)
Althoughitlookslike a'Q', the symbol issupposedtolooklike areel of tape.
Data ProcessingSymbols
SYMBOL
NAME
DESCRIPTION
Collate
The Collate flowchartshape indicatesaprocessstepthatrequiresorganizingdata,
information,ormaterials accordingintoastandardformator arrangement.
Sort Indicatesthe sortingof data,information,materialsintosome pre-definedorder.
12. BCE/UNIT II Truba College of Science & Technology,
Bhopal
By: Ms. Nandini Sharma [CSE Deptt.] Page 12
Introduction ofProgramming
An organized list of instructions that, when executed, causes the computer to behave in a
predetermined manner. Without programs, computers are useless.
A program is like a recipe. It contains a list of ingredients (called variables) and a list of
directions (called statements) that tell the computer what to do with the variables. The
variables can represent numeric data, text, or graphical images.
There are many programming languages -- C, C++, Pascal, BASIC, FORTRAN, COBOL, and LISP are
just a few. These are all high-level languages. One can also write programs in low-level
languages called assembly languages, although this is more difficult. Low-level languages are
closer to the language used by a computer, while high-level languages are closer to human
languages.
Eventually, every program must be translated into a machine language that the computer can
understand. This translation is performed by compilers, interpreters, and assemblers.
When you buy software, you normally buy an executable version of a program. This means that
the program is already in machine language -- it has already been compiled and assembled and
is ready to execute.
Categories of Programming Language
Programming languages fall into two fundamental categories low and high-level languages.
Low-level languages are machine-dependent; that is, they are designed to be run on a
particular computer. In contrast, high-level languages (for example, COBOL and BASIC) are
machine-independent and can be run on a variety of computers.
The hierarchy of programming languages in the Figure summarizes the relationships between
the various types of programming languages. Through the first four decades of computing,
programming languages evolved in generations. The first two generations were low-level and
the next two high-level generations of programming languages.
The higher-level languages do not provide us a greater programming capabilities, but they do
provide a more sophisticated programmer/computer interaction. In short, the higher the level
of the language, the easier it is to understand and use. For example, in a fourth-generation
language you need only instruct the computer system what to do, not necessarily how to do it.
Characteristics of Programming language
13. BCE/UNIT II Truba College of Science & Technology,
Bhopal
By: Ms. Nandini Sharma [CSE Deptt.] Page 13
The following are the characteristics of a programming language
1. Readability: A good high-level language will allow programs to be written in some ways that
resemble a quite-English description of the underlying algorithms. If care is taken, the coding
may be done in a way that is essentially self-documenting.
2. Portability: High-level languages, being essentially machine independent, should be able to
develop portable software.
3. Generality: Most high-level languages allow the writing of a wide variety of programs, thus
relieving the programmer of the need to become expert in many diverse languages.
4. Brevity: Language should have the ability to implement the algorithm with less amount of
code. Programs expressed in high-level languages are often considerably shorter than their low-
level equivalents.
5. Error checking: Being human, a programmer is likely to make many mistakes in the
development of a computer program. Many high-level languages enforce a great deal of error
checking both at compile-time and at run-time.
6. Cost: The ultimate cost of a programming language is a function of many of its
characteristics.
7. Familiar notation: A language should have familiar notation, so it can be understood by most
of the programmers.
8. Quick translation: It should admit quick translation.
9. Efficiency: It should permit the generation of efficient object code.
10. Modularity: It is desirable that programs can be developed in the language as a collection of
separately compiled modules, with appropriate mechanisms for ensuring self-consistency
between these modules.
11. Widely available: Language should be widely available and it should be possible to provide
translators for all the major machines and for all the major operating systems.
Procedure Oriented Programming:- Procedure oriented programming is the conventional way
of programming where an application problem is viewed as a sequence of steps. In procedure
oriented programming the problem is broken down into various modules such as data entry
reporting querying module etc. There are two types of data, which are associated with these
modules, one is global and another is local data.
Global data items are mainly defined in main program, where local data is defined with the
associated functions.
Many of the functions in the programming language share global data, which is available to all
the functions. The procedural-oriented programming is the traditional approach of
14. BCE/UNIT II Truba College of Science & Technology,
Bhopal
By: Ms. Nandini Sharma [CSE Deptt.] Page 14
programming for developing application software. High level languages like FORTRAN, COBOL,
PASCAL, BASIC and C are based on the procedure oriented approach and consequently are
called procedural languages.
Object-oriented programming (OOP) is a programming language model organized around
"objects" rather than "actions" and data rather than logic. Historically, a program has been
viewed as a logical procedure that takes input data, processes it, and produces output data.
The programming challenge was seen as how to write the logic, not how to define the data.
Object-oriented programming takes the view that what we really care about are the objects we
want to manipulate rather than the logic required to manipulate them. Examples of objects
range from human beings (described by name, address, and so forth) to buildings and floors
(whose properties can be described and managed) down to the little widgets on your computer
desktop (such as buttons and scroll bars).
The concepts and rules used in object-oriented programming provide these important benefits:
The concept of a data class makes it possible to define subclasses of data objects that
share some or all of the main class characteristics. Called inheritance, this property of
OOP forces a more thorough data analysis, reduces development time, and ensures
more accurate coding.
Since a class defines only the data it needs to be concerned with, when an instance of
that class (an object) is run, the code will not be able to accidentally access other
program data. This characteristic of data hiding provides greater systemsecurity and
avoids unintended data corruption.
15. BCE/UNIT II Truba College of Science & Technology,
Bhopal
By: Ms. Nandini Sharma [CSE Deptt.] Page 15
The definition of a class is reusable not only by the program for which it is initially
created but also by other object-oriented programs (and, for this reason, can be more
easily distributed for use in networks).
The concept of data classes allows a programmer to create any new data type that is not
already defined in the language itself.
Featuresof OOPs:-
Objects:- Objectsare the basic run-time entitiesinanobject-orientedsystem.Programming
problemisanalyzedintermsof objectsandnature of communicationbetweenthem.Whena
program isexecuted,objectsinteractwitheachotherbysendingmessages.Differentobjects
can alsointeractwitheach otherwithoutknowingthe detailsof theirdataorcode.
Classes:- A class isa collectionof objectsof similartype.Once aclassisdefined,anynumberof
objectscan be createdwhichbelongtothat class.
Data Abstraction and Encapsulation:- Abstractionreferstothe act of representingessential
featureswithoutincludingthe backgrounddetails orexplanations.Classesuse the conceptof
abstractionand are definedasa listof abstract attributes.Storingdataandfunctionsina single
unit(class) isencapsulation.Datacannotbe accessible tothe outside worldandonlythose
functionswhichare storedinthe classcan accessit.
Inheritance:- Inheritance isthe processbywhichobjectscanacquire the propertiesof objectsof
otherclass.In OOP,inheritance providesreusability,like,addingadditional featurestoan
existingclasswithoutmodifyingit.Thisisachievedbyderivinganew classfromthe existingone.
The newclass will have combinedfeaturesof boththe classes.
Polymorphism:- Polymorphismmeansthe abilitytotake more thanone form.Anoperationmay
exhibitdifferentbehaviors indifferentinstances.The behaviordependsonthe datatypesused
inthe operation.PolymorphismisextensivelyusedinimplementingInheritance.
Meritsof OOPs:-
Simplicity:software objectsmodel real worldobjects,sothe complexityisreducedandthe
program structure isveryclear;
Modularity:eachobjectformsa separate entitywhose internal workingsare decoupledfrom
otherparts of the system;
16. BCE/UNIT II Truba College of Science & Technology,
Bhopal
By: Ms. Nandini Sharma [CSE Deptt.] Page 16
Modifiability:itiseasyto make minorchangesinthe data representationorthe proceduresin
an OO program.Changesinside aclassdo notaffectany otherpart of a program, since the only
publicinterface thatthe external worldhastoa classisthroughthe use of methods;
Extensibility:addingnewfeaturesorrespondingtochangingoperating environmentscanbe
solvedbyintroducingafewnew objectsandmodifyingsome existingones;
Maintainability:objectscanbe maintainedseparately,makinglocatingandfixingproblems
easier;
Re-usability:objectscanbe reusedindifferentprograms.
History
The C++ programminglanguagesisanextensionof Cthatwas developedbyBjarne Stroustrupinthe
early1980s at Bell Laboratories.C++providesanumberof featuresthat"spruce up"the C language,but
more importantly,itprovidescapabilitiesforobject-orientedprogramming.A computercannot
understandourlanguage thatwe use in ourday to day conversations,andlikewise,we cannot
understandthe binarylanguage thatthe computerusestodo it’stasks.It istherefore necessaryforus
to write instructionsinsome speciallydefinedlanguagelikeC++whichislike natural language andafter
convertingwiththe helpof compilerthe computercanunderstandit.
SignificantLanguage Features
Object-orientedprogramsare easiertounderstand,correctand modify.Manyotherobject-oriented
languageshave beendeveloped,includingmostnotably,Smalltalk.The bestfeaturesof C++are:
C++ isa hybrid language-itispossible to program in eithera C-like style,anobject-oriented
style,or both.
C++ programs consist of piecescalledclassesand functions.You can program each piece you
may needto form a C++ program. The advantage of creating your own functions and classesis
that you will know exactlyhow they work. You will be able to examine the C++ code.
Areas of Application
C++ providesacollectionof predefinedclasses,alongwiththe capabilityof user-definedclasses.The
classesof C++ are data types,whichcanbe instantiatedanynumberof times.Classdefinitionsspecify
data objects(calleddatamembers) andfunctions(calledmemberfunction).Classescanname one or
more parentclasses,providinginheritance andmultiple inheritance,respectively.Classesinheritthe
data membersandmemberfunctionsof the parentclassthatare specifiedtobe inheritable.Therefore
it ismainlyusedfor:
Software Engineering
17. BCE/UNIT II Truba College of Science & Technology,
Bhopal
By: Ms. Nandini Sharma [CSE Deptt.] Page 17
Graphics
C++ COMPILER
A C++ compilerisitselfacomputerprogramwhich’sonlyjobisto convertthe C++ programfrom our
formto a formthe computercan read and execute.The original C++programis calledthe “source
code”,andthe resultingcompiledcode producedbythe compilerisusuallycalledan “objectfile”.
Before compilationthe preprocessorperformspreliminaryoperationsonC++ source files.Preprocessed
formof the source code issentto compiler.
Aftercompilationstage objectfilesare combinedwithpredefinedlibrariesbya linker,sometimescalled
a binder,toproduce the final complete file thatcanbe executedbythe computer.A libraryisa
collectionof pre-compiled“objectcode”thatprovidesoperationsthatare done repeatedlybymany
computerprograms.
UsingTurbo C++ Compiler
18. BCE/UNIT II Truba College of Science & Technology,
Bhopal
By: Ms. Nandini Sharma [CSE Deptt.] Page 18
The firstand frequentlyusedmethodforcreatingprogramisTurboC++'s IntegratedDevelopment
Environment(IDE).TostartIDE type TC at DOS prompt.Or searchthe file TC.EXEinyourcomputerand
Run it.Your IDE will looklike this.
1. Nowtype sample programon Editor
2. Clickon Compile menuchoose CompileoptionorpressAlt+F9
3. Clickon Run menuchoose Runoptionor pressCtrl+F9
4. If there isno error outputwill be displayedonUserScreen
Before we begintolearntowrite meaningful programsinC++language,letushave a lookat the various
buildingblockof C++language,alsocalledelementsof C++language....
C++ BASICS
C++ CHARACTER SET
Character setisa setof validcharacters thata language canrecognize.
Letters A-Z,a-z
Digits 0-9
Special Characters
Space + - * / ^ () [] {} = != <> ‘ “ $ , ; : % ! & ? _ #
<= >= @
Formatting
characters
backspace,horizontal tab,vertical tab,formfeed,andcarriage
return
TOKENS
A tokenisa group of characters that logicallybelongtogether.The programmercanwrite aprogram by
usingtokens.C++ usesthe followingtypesof tokens.
Keywords,Identifiers,Literals,Punctuators,Operators.
1. Keywords
19. BCE/UNIT II Truba College of Science & Technology,
Bhopal
By: Ms. Nandini Sharma [CSE Deptt.] Page 19
These are some reservedwordsinC++ whichhave predefinedmeaningtocompilercalledkeywords.
Some commonlyusedKeywordare givenbelow:
asm auto break case catch
char class const continue default
delete do double else enum
extern inline int float for
friend goto if long new
operator private protected public register
return short signed sizeof static
struct switch template this Try
typedef union unsigned virtual void
volatile while
2. Identifiers
Symbolicnamescanbe usedinC++ for variousdataitemsusedbya programmerinhisprogram.A
symbolicname isgenerally knownasanidentifier.The identifierisasequence of characterstakenfrom
C++ character set.The rule for the formationof an identifierare:
An identifiercanconsistof alphabets,digitsand/orunderscores.
It mustnot start witha digit
C++ iscase sensitivethatisuppercase and lowercase lettersare considereddifferentfromeach
other.
It shouldnotbe a reservedword.
3. Literals
Literals(oftenreferredtoasconstants) are data itemsthat neverchange theirvalue duringthe
executionof the program.The followingtypesof literalsare available inC++.
Integer-Constants
Character-constants
20. BCE/UNIT II Truba College of Science & Technology,
Bhopal
By: Ms. Nandini Sharma [CSE Deptt.] Page 20
Floating-constants
Strings-constants
Integer Constants:Integerconstantsare whole numberwithoutanyfractional part.C++allowsthree
typesof integerconstants.
Decimal integer constants : It consistsof sequence of digitsandshouldnotbeginwith0(zero).For
example 124, - 179, +108.
Octal integer constants:It consistsof sequence of digitsstartingwith0(zero).Forexample.014,012.
Hexadecimal integer constant:It consistsof sequence of digitsprecededbyox orOX.
Character constants
A character constantinC++ must containone or more characters andmust be enclosedinsingle
quotationmarks.Forexample 'A','9', etc. C++ allowsnongraphiccharacterswhichcannotbe typed
directlyfromkeyboard,e.g.,backspace,tab,carriage returnetc.These characterscan be representedby
usingan escape sequence.Anescape sequence representsasingle character.The followingtablegivesa
listingof commonescape sequences.
Escape Sequence Nongraphic Character
a Bell (beep)
n Newline
r Carriage Return
t Horizontal tab
0 Null Character
Floatingconstants
Theyare alsocalledreal constants.Theyare numbershavingfractional parts.Theymaybe writtenin
fractional formor exponentform.A real constantinfractional formconsistsof signedorunsigneddigits
includingadecimal pointbetweendigits.Forexample 3.0, -17.0, -0.627 etc.
String Literals
A sequence of characterenclosedwithindouble quotesiscalledastringliteral.Stringliteral isbydefault
(automatically) addedwithaspecial character‘0'whichdenotesthe endof the string.Therefore the
size of the stringis increasedbyone character.For example "COMPUTER"will re representedas
"COMPUTER0" inthe memoryand itssize is9 characters.
4. Punctuators
21. BCE/UNIT II Truba College of Science & Technology,
Bhopal
By: Ms. Nandini Sharma [CSE Deptt.] Page 21
The followingcharacters are usedaspunctuatorsinC++.
Brackets[ ]
Openingandclosingbracketsindicate singleandmultidimensional
array subscript.
Parentheses(
)
Openingandclosingbracketsindicate functionscalls,;function
parametersforgroupingexpressionsetc.
Braces { }
Openingandclosingbracesindicate the startandendof a
compoundstatement.
Comma, It isusedas a separatorina functionargumentlist.
Semicolon; It isusedas a statementterminator.
Colon: It indicatesalabeledstatementor conditionaloperatorsymbol.
Asterisk* It isusedin pointerdeclarationoras multiplicationoperator.
Equal sign= It isusedas an assignmentoperator.
Poundsign# It isusedas pre-processordirective.
5. Operators: Operatorsare special symbolsusedforspecificpurposes.C++providessix typesof
operators.Arithmetical operators,Relational operators, Logical operators,Unaryoperators,Assignment
operators,Conditional operators,Commaoperator
DATA HANDLING
BASIC DATA TYPES
C++ supportsa large numberof data types.The builtinor basicdata typessupportedbyC++ are integer,
floatingpointandcharacter.These are summarizedintable alongwithdescriptionandmemory
requirement
Type Byte Range Description
int 2 -32768 to +32767 Small whole number
longint 4 -2147483648 to +2147483647 Large whole number
float 4 3.4x10-38 to 3.4x10+38 Small real number
double 8 1.7x10-308 to 1.7x10+308 Large real number
22. BCE/UNIT II Truba College of Science & Technology,
Bhopal
By: Ms. Nandini Sharma [CSE Deptt.] Page 22
longdouble 10 3.4x10-4932 to 3.4x10+4932 VeryLarge real number
char 1 0 to 255 A Single Character
VARIABLES
It isa locationinthe computermemorywhichcanstore data and isgivena symbolicname foreasy
reference.The variablescanbe usedtoholddifferentvaluesatdifferenttimesduringthe executionof a
program.
To understandmore clearlywe shouldstudythe followingstatements:
Total = 20.00; In thisstatementavalue 20.00 has beenstoredina memorylocationTotal.
Declaration of a variable
Before a variable isusedinaprogram, we mustdeclare it.Thisactivityenablesthe compilertomake
available the appropriatetype of locationinthe memory.
floatTotal;
You can declare more thanone variable of same type ina single single statement
intx,y;
Initializationofvariable
Whenwe declare a variable it'sdefaultvalue isundetermined.We candeclare avariable withsome
initial value.
inta = 20;
INPUT/OUTPUT (I/O)
C++ supportsinput/outputstatementswhichcanbe usedtofeednew dataintothe computeror obtain
outputon an outputdevice suchas:VDU, printeretc.The followingC++streamobjectscan be usedfor
the input/outputpurpose.
cin console input
cout console output
cout isusedinconjuctionwith<< operator,knownas insertionorputto operator.
cin isusedinconjuctionwith>> operator,knownasextractionor getfromoperator.
cout << “My firstcomputer";Once the above statementiscarriedoutby the computer,the message
"My firstcomputer"will appearonthe screen.
23. BCE/UNIT II Truba College of Science & Technology,
Bhopal
By: Ms. Nandini Sharma [CSE Deptt.] Page 23
cin can be usedto inputa value enteredbythe userfromthe keyboard.However,the getfrom
operator>> isalsorequiredtogetthe typedvalue fromcinandstore it inthe memorylocation.
Let usconsiderthe followingprogramsegment:
intmarks;
cin >> marks;In the above segment,the userhasdefinedavariable marksof integertype inthe first
statementandinthe secondstatementhe istryingto reada value fromthe keyboard.
TYPE CONVERSION
The processin whichone pre-definedtype of expressionisconvertedintoanothertype iscalled
conversion.There are twotypesof conversioninC++.
1. Wideningconversion(Expansion)
2. Narrowingconversion(Compression)
STRUCTURE OF C++ PROGRAM
#include<headerfile>
main()
{
...........
...........
...........
}
A C++ programstarts withfunctioncalledmain( ).The bodyof the functionisenclosedbetweencurly
braces.The programstatementsare writtenwithinthe braces.Eachstatementmustendbya
semicolon;(statementterminator).A C++program maycontainas manyfunctionsasrequired.However,
whenthe programis loadedinthe memory,the control ishandedovertofunctionmain( ) and itis the
firstfunctiontobe executed.
// Thisismy firstprogram isC++
/* thisprogram will illustrate differentcomponentsof
a simple programinC++ */
# include <iostream.h>
intmain( )
{
cout <<"HelloWorld!";
return0;
}
24. BCE/UNIT II Truba College of Science & Technology,
Bhopal
By: Ms. Nandini Sharma [CSE Deptt.] Page 24
Whenthe above program iscompiled,linkedandexecuted,the followingoutputisdisplayedonthe
VDU screen.
HelloWorld!
Variouscomponentsof thisprogramare discussedbelow:
Comments
Firstthree linesof the above programare commentsandare ignoredbythe compiler.Commentsare
includedinaprogram to make itmore readable.If acommentisshort andcan be accommodatedina
single line,thenitisstartedwithdouble slashsequence inthe firstline of the program.However,if
there are multiple linesinacomment,itisenclosedbetweenthe twosymbols/*and*/
#include <iostream.h>
The line inthe above program thatstart with# symbol are calleddirectivesandare instructionstothe
compiler.The wordinclude with'#'tellsthe compilertoinclude the file iostream.hintothe file of the
above program.File iostream.hisaheaderfile neededforinput/outputrequirementsof the program.
Therefore,thisfile hasbeenincludedatthe topof the program.
int main ( )
The word mainisa functionname.The brackets( ) withmaintellsthatmain( ) is a function.The word
intbefore main( ) indicatesthatintegervalue isbeingreturnedbythe functionmain().Whenprogram
isloadedinthe memory,the control ishandedoverto functionmain( ) andit isthe firstfunctiontobe
executed.
Curly bracket and body of the functionmain ( )
A C++ programstarts withfunctioncalledmain().The bodyof the functionisenclosedbetweencurly
braces.The programstatementsare writtenwithinthe brackets.Eachstatementmustendbya
semicolon,withoutwhichanerrormessage ingenerated.
cout<<"HelloWorld!";
Thisstatementprintsour"HelloWorld!"message onthe screen.coutunderstandsthatanythingsentto
it viathe << operatorshouldbe printedonthe screen.
return 0;
Thisis a newtype of statement,calledareturnstatement.Whenaprogramfinishesrunning,itsends a
value tothe operatingsystem.Thisparticularreturnstatementreturnsthe valueof 0 to the operating
system,whichmeans“everythingwentokay!”.
25. BCE/UNIT II Truba College of Science & Technology,
Bhopal
By: Ms. Nandini Sharma [CSE Deptt.] Page 25
/* This programillustrateshowto
declare variable,readdataanddisplaydata.*/
#include <iostream.h>
intmain()
{
introllno;//declare the variablerollnoof type int
floatmarks;//declare the variable marksof type float
cout << "Enterroll numberandmarks :";
cin >> rollno>> marks;//store data intovariable rollno&marks
cout << "Rollno:"<< rollno<<"n";
cout << "Marks: " << marks;
return0;
}
Sample Run: Inthissample run,the user inputisshaded.
Enter roll numberandmarks:102 87.5
Rollno:102
Marks: 87.5
OPERATORS
Operatorsare special symbolsusedforspecificpurposes.C++providessix typesof operators.
Arithmetical operators,Relationaloperators, Logical operators,Unaryoperators,Assignmentoperators,
Conditional operators,Commaoperator
Arithmetical operators
Arithmetical operators+, -,*, /,and % are usedtoperformsan arithmetic(numeric) operation.Youcan
use the operators+, -, *, and / withbothintegral andfloating-pointdatatypes.Modulusorremainder%
operatorisusedonlywiththe integral datatype.
Operatorsthat have twooperandsare calledbinaryoperators.
Relational operators
The relational operatorsare usedtotestthe relationbetweentwovalues.All relationaloperatorsare
binaryoperatorsandtherefore require twooperands.A relational expressionreturnszerowhenthe
relationisfalse anda non-zerowhenitistrue.The followingtable showsthe relational operators.
Relational Operators Meaning
< Lessthan
26. BCE/UNIT II Truba College of Science & Technology,
Bhopal
By: Ms. Nandini Sharma [CSE Deptt.] Page 26
<= Lessthan or equal to
== Equal to
> Greaterthan
>= Greaterthan or equal to
! = Notequal to
Logical operators
The logical operatorsare usedto combine one ormore relational expression.The logical operatorsare
Operators Meaning
|| OR
&& AND
! NOT
Unaryoperators
C++ providestwounaryoperatorsforwhichonlyone variable isrequired.
For Example a = - 50;
a = + 50; Here plussign(+) and minussign(-) are unary because theyare notusedbetweentwo
variables.
Assignmentoperator
The assignmentoperator'=' isusedfor assigningavariable toa value.Thisoperatortakesthe
expressionon itsright-hand-side andplacesitintothe variable onitsleft-hand-side.Forexample:m= 5;
The operatortakesthe expressiononthe right, 5,and storesit inthe variable onthe left, m.x = y = z =
32; Thiscode storesthe value 32 in eachof the three variablesx,y,andz.
inadditiontostandard assignmentoperatorshownabove,C++alsosupportcompoundassignment
operators.
CompoundAssignmentOperators
Operator Example Equivalentto
+ = A + = 2 A = A + 2
27. BCE/UNIT II Truba College of Science & Technology,
Bhopal
By: Ms. Nandini Sharma [CSE Deptt.] Page 27
- = A - = 2 A = A - 2
% = A % = 2 A = A % 2
/= A/= 2 A = A / 2
*= A * = 2 A = A * 2
Increment and Decrement Operators
C++ providestwospecial operatorsviz'++' and '--' forincrementinganddecrementingthe value of a
variable by1. The increment/decrementoperatorcanbe usedwithany type of variable butitcannot be
usedwithanyconstant.Incrementanddecrementoperatorseachhave twoforms,pre andpost.
The syntax of the incrementoperator is:
Pre-increment:++variable
Post-increment:variable++
The syntax of the decrementoperator is:
Pre-decrement:––variable
Post-decrement:variable––
In Prefix formfirstvariableisfirstincremented/decremented,thenevaluated
In Postfix formfirstvariableisfirstevaluated,thenincremented/decremented
intx,y;
inti=10,j=10;
x = ++i; //addone to i,store the resultbackinx
y= j++; //store the value of j to y thenadd one to j
cout<<x; //11
cout<<y; //10
Conditional operator
The conditional operator?:iscalledternaryoperatoras itrequiresthree operands.The formatof the
conditional operatoris:
Conditional_expression?expression1:expression2;
If the value of conditional expressionistrue thenthe expression1isevaluated,otherwiseexpression2is
evaluated.inta= 5, b = 6;
big= (a > b) ? a : b;The conditionevaluatestofalse,therefore biggetsthe value frombandit becomes
6.
The commaoperator
The comma operatorgiveslefttorightevaluationof expressions.Whenthe setof expressionshastobe
evaluatedforavalue,onlythe rightmostexpressionis considered.
28. BCE/UNIT II Truba College of Science & Technology,
Bhopal
By: Ms. Nandini Sharma [CSE Deptt.] Page 28
inta=1, b=2, c=3, i; // commaacts as separator,notas an operator
i = (a, b);// storesb intoi Wouldfirstassignthe value of a to i,and thenassign value of b to variable i.
So,at the end,variable i wouldcontainthe value 2.
The order of Precedence
The order inwhichthe Arithmeticoperators(+,-,*,/,%)are usedina.givenexpressioniscalledthe order
of precedence.The followingtable showsthe orderof precedence.
Order Operators
First
Second
Third
()
*, /, %
+, -
The followingtable showsthe precedence of operators.
++, --(postincrement/decrement)
Highest
To
Lowest
++ (Pre increment) -- (Pre decrement),sizeof( ),!(not), -(unary),
+(unary)
*,/, %
+, -
<, <=, >, >=
==,!=
&&
? :
=
Commaoperator
FLOW OF CONTROL
Statements
Statementsare the instructionsgiventothe computertoperformany kindof action.Actionmaybe in
the form of data movement,decisionmakingetc.Statementsformthe smallestexecutable unitwithina
C++ program.Statements are alwaysterminatedbysemicolon.
29. BCE/UNIT II Truba College of Science & Technology,
Bhopal
By: Ms. Nandini Sharma [CSE Deptt.] Page 29
CompoundStatement
A compoundstatementisagroupingof statementsinwhicheachindividual statementendswitha
semi-colon.The groupof statementsiscalledblock.Compoundstatementsare enclosedbetweenthe
pair of braces({}.).The openingbrace ({) signifiesthe beginningandclosingbrace (}) signifiesthe endof
the block.
Null Statement
Writingonlya semicolonindicatesanull statement.Thus';'is a null or emptystatement.Thisisquite
useful whenthe syntax of the language needstospecifyastatementbutthe logicof the programdoes
not needanystatement.Thisstatementisgenerallyusedinforandwhile loopingstatements.
Conditional Statements
Sometimesthe programneedstobe executeddepending uponaparticularcondition.C++providesthe
followingstatementsforimplementingthe selectioncontrol structure.
if statement
if else statement
nestedif statement
switchstatement
if statement
syntax of the if statement
if (condition)
{
statement(s);
}
From the flowchartitisclear thatif the if conditionistrue,statementisexecuted;otherwise itis
skipped.The statementmayeitherbe asingle orcompoundstatement.
30. BCE/UNIT II Truba College of Science & Technology,
Bhopal
By: Ms. Nandini Sharma [CSE Deptt.] Page 30
if else statement
syntax of the if - else statement
if (condition)
statement1;
else
statement2;
From the above flowchartitisclearthat the givenconditionisevaluatedfirst.If the conditionistrue,
statement1 isexecuted.If the conditionisfalse,statement2isexecuted.Itshouldbe keptinmindthat
statementandstatement2canbe single orcompoundstatement.
if example if else example
if (x == 100)
cout << "x is100";
if (x == 100)
cout << "x is100";
else
cout << "x isnot 100";
Nestedifstatement
The if blockmaybe nestedinanotherif orelse block.Thisiscallednestingof if orelse block.
syntax of the nestedif statement
if(condition1)
{
if(condition2)
{
statement(s);
31. BCE/UNIT II Truba College of Science & Technology,
Bhopal
By: Ms. Nandini Sharma [CSE Deptt.] Page 31
}
}
if(condition1)
statement1;
else if (condition2)
statement2;
else
statement3;
if-else-if example
if(percentage>=60)
cout<<"Istdivision";
else if(percentage>=50)
cout<<"IInddivision";
else if(percentage>=40)
cout<<"IIIrddivision";
else
cout<<"Fail";
switch statement
The if andif-else statementspermittwowaybranchingwhereasswitchstatementpermitsmultiple
branching.The syntax of switchstatementis:
switch(var/ expression)
{
case constant1: statement1;
break;
case constant2: statement2;
break;
.
.
default:statement3;
break;
}
The executionof switchstatementbeginswiththe evaluationof expression.If the value of expression
matcheswiththe constantthenthe statementsfollowingthisstatementexecute sequentiallytill it
32. BCE/UNIT II Truba College of Science & Technology,
Bhopal
By: Ms. Nandini Sharma [CSE Deptt.] Page 32
executesbreak.The breakstatementtransferscontrol tothe endof the switchstatement.If the value of
expressiondoesnotmatchwithanyconstant,the statementwithdefaultisexecuted.
Some importantpointsaboutswitchstatement
The expressionof switchstatementmustbe of type integerorcharactertype.
The defaultcase neednotto be usedat last case.It can be placedat any place.
The case valuesneednottobe in specificorder.
FLOW OF CONTROL
Looping statement
It isalso calledaRepetitivecontrol structure.Sometimeswe require asetof statementstobe executed
a numberof timesbychangingthe value of one or more variableseachtime toobtaina differentresult.
Thistype of programexecutioniscalledlooping.C++ providesthe followingconstruct
while loop
do-whileloop
for loop
While loop
Syntax of while loop
while(condition)
{
statement(s);
}
The flowdiagramindicatesthata conditionisfirstevaluated.If the conditionistrue,the loopbodyis
executedandthe conditionisre-evaluated.Hence,the loopbodyisexecutedrepeatedlyaslongas the
conditionremainstrue.Assoonasthe conditionbecomesfalse,itcomesoutof the loopand goesto the
statementnexttothe ‘while’loop.
do-while loop
Syntax of do-while loop
do
{statements;
} while (condition);
33. BCE/UNIT II Truba College of Science & Technology,
Bhopal
By: Ms. Nandini Sharma [CSE Deptt.] Page 33
Note : That the loopbodyisalwaysexecutedatleastonce.One importantdifference betweenthe while
loopand the do-whileloopthe relative orderingof the conditional testandloopbodyexecution.Inthe
while loop,the looprepetitiontestisperformedbefore eachexecutionthe loopbody;the loopbodyis
not executedatall if the initial testfail.Inthe do-while loop,the loopterminationtestisPerformed
aftereach executionof the loopbody.hence,the loopbodyisalwaysexecutedleastonce.
for loop
It isa countcontrolledloopinthe sense that
the program knowsinadvance howmany times
the loopis to be executed.
syntax of for loopfor(initialization;decision;
increment/decrement)
{
statement(s);
}
The flowdiagramindicatesthatinfor loopthree operationstake place:
Initializationof loopcontrol variable
34. BCE/UNIT II Truba College of Science & Technology,
Bhopal
By: Ms. Nandini Sharma [CSE Deptt.] Page 34
Testingof loopcontrol variable
Update the loopcontrol variable eitherbyincrementingordecrementing.
Operation(i) isusedtoinitialize the value.Onthe otherhand,operation(ii) isusedtotestwhetherthe
conditionistrue or false.If the conditionistrue,the programexecutesthe bodyof the loopandthen
the value of loopcontrol variable isupdated.Againitchecksthe conditionandsoon.If the conditionis
false,itgetsoutof the loop
35. BCE/UNIT II Truba College of Science & Technology, Bhopal
By: Ms. Nandini Sharma [CSE Deptt.] Page 35
Jump Statements
The jumpstatementsunconditionallytransferprogramcontrol withinafunction.
goto statement
breakstatement
continue statement
The goto statement
goto allowstomake jumpto anotherpointinthe program.goto pqr;
pqr: pqr is knownaslabel.Itisa userdefinedidentifier.Afterthe executionof gotostatement,the control
transferstothe line afterlabel pqr.
The break statement
The break statement,whenexecutedinaswitchstructure,providesanimmediate
exitfromthe switchstructure.Similarly,youcanuse the breakstatementin
any of the loop.Whenthe break statementexecutesinaloop,itimmediatelyexitsfromthe loop.
ARRAY
An array isa collectionof dataelementsof same datatype.Itis describedbyasingle name andeach
elementof anarray isreferencedbyusingarrayname and itssubscriptno.
Declaration of Array
Type arrayName[numberOfElements];
For example, intAge[5] ;
floatcost[30];
InitializationofOne Dimensional Array
An array can be initializedalongwithdeclaration.Forarray initializationitisrequiredtoplace the elements
separatedbycommasenclosedwithinbraces.intA[5] ={11,2,23,4,15}; It is possible toleave the arraysize
open.The compilerwill countthe arraysize.intB[] = {6,7,8,9,15,12};
Referringto Array Elements
36. BCE/UNIT II Truba College of Science & Technology, Bhopal
By: Ms. Nandini Sharma [CSE Deptt.] Page 36
In anypointof a program inwhichan array is visible,we canaccessthe value of any of its elements
individuallyasif itwas a normal variable,thusbeingable tobothreadand modifyitsvalue.The formatis
as simple as:
name[index]
Examples:cout<<age[4]; //printanarray element
age[4]=55; //assignvalue toan array element
cin>>age[4]; //inputelement4
UsingLoop to inputan Array from user
intage [10], i ;
for (i=0 ; i<10; i++)
{
cin>>age[i];
}
Arrays as Parameters
At some momentwe mayneedtopass an array to a functionasa parameter.InC++ itis notpossible to
pass a complete blockof memorybyvalue asa parameterto a function,butwe are allowedtopassits
address.
For example,the followingfunction: voidprint(intA[])acceptsaparameterof type "array of int"
calledA.
In orderto pass tothis functionanarray declaredas: intarr[20]; we needtowrite a call like this:
print(arr);
STRUCTURE
A structure isa collectionof variablewhichcanbe same or differenttypes.Youcanreferto a structure as a
single variable,andtoitsparts as membersof that variable byusingthe dot(.) operator. The powerof
structuresliesinthe factthat once defined,the structure name becomesa user-defineddatatype and
may be usedthe same way as otherbuilt-indatatypes,suchasint,double,char.
struct STUDENT
{
introllno,age;
char name[80];
floatmarks;
} ;
intmain()
{
// declare twovariablesof the newtype
STUDENT s1, s3;
//accessingof data members
37. BCE/UNIT II Truba College of Science & Technology, Bhopal
By: Ms. Nandini Sharma [CSE Deptt.] Page 37
cin>>s1.rollno>>s1.age>>s1.name>>s1.marks;
cout<<s1.rollno<<s1.age<<s1.name<<s1.marks;
//initializationof structure variable
STUDENT s2 = {100,17,”Aniket”,92};
cout<<s2.rollno<<s2.age<<s2.name<<s2.marks;
//structure variable inassignmentstatement
s3=s2;
cout<<s3.rollno<<s3.age<<s3.name<<s3.marks;
return0;
}
Defininga structure
Whendealingwiththe studentsinaschool,manyvariables of differenttypesare needed. Itmay be
necessarytokeeptrack of name, age,Rollno,andmarks pointforexample.structSTUDENT
{
introllno,age;
char name[80];
floatmarks;
}; STUDENT iscalledthe structure tag, and isyour brandnew data type,like int,double orchar.
rollno,name, age, and marks are structure members.
Declaring VariablesofType struct
The most efficientmethodof dealingwithstructure variablesistodefine the structure globally. Thistells
"the whole world",namelymainandanyfunctionsinthe program, that a new data type exists. Todeclare
a structure globally,place it BEFORE voidmain(). The structure variablescanthenbe definedlocallyin
main,forexample…