0 ratings0% found this document useful (0 votes) 140 views11 pagesFundamentals of C
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
FUNDAMENTALS OF C++
HISTORY OF C+4
There are two ways in
approach like © or Begin language: the
Spjectoriented approach OOP in Gat, Ce or Jove, mee
oriented programming (OOP) is a programmin, prada ed
uses "objects" and their interactions to design a sllcatore a
computer programs. While procedures, also known 23 routines
subroutines, methods, or functions simply contain a series of
computational steps to be carried out. Any given rocedt a
might be called at any point during a program's execution,
‘including other procedures. Procedural programming is often
better choice than simple sequential or unstructured
programming in many situations which involve moderate
complexity or which require significant ease of maintainability.
C++ is an object-oriented version of C that has been
widely used to develop enterprise and commercial applications.
C++ has become a popular programming language because it
combines traditional C programming with object-oriented
programming (OOP) features. :
C++ Is an extension of C language. C Language was
developed in 1974 by Dennis Ritchie and Kernighan of Bell
Laboratories. It was designed to run on PDP-11 running on
UNIX operating system. The language was the successor of a
programming language named BCPL, which in turn succeeded
an even earlier language, B.
C++ was written by Bjarne Stroustrup at Bell Lab In
the early 80’s. It was first known as “C with Classes”. Later,
Stroustrup added more features, and the resulting language
became known as C++. It was named C++ only in ean
Stroustrup also points out that the language is not calleProgramming (20ST SE
othe
ther It Is
features of C, but rat
remove any
h C and C++ languages,
rabilty of BOMr te (ANSI) developed
o maintain potablty Of te
tne american National Or end C++ programming In 1990.
of cons
a several versions of the C++ language. These
‘There ae severe Get, and Code Warrior for Mac
are visual Ci to c+. Al of these software, packages
ines and Tore computer programs with C++, but they all
enable Yor gne crt guage In 2 sight afferent manner,
ine
CH Is also case sensitive;
ret tt Gy wows sich 5c, cout and the other
therefor, reser sno be wren in ower case letters,
re
This module would be dealing primarily with Microsoft
Visual CH.
MECHANICS OF A C++ PROGRAM
‘The figure below shows the steps Involved in using the
computer to run C++ programs.
EDITOR
‘source FILE |[ HEADER FILE
tL
PREPROCESSOR
COMPILER,
JE
OBJECT FILE
ig
Liane cope [|e
DEaITARLE CODE
rovedures before executing a C++ code
ar Programming
eaere 9° Catortay Meas
+ Accepts the
Eattor (ernest YONG of te source cde
The le that onan the
Srepere In the editor. ‘after you aa
ourceta ; Re epurtette errant
Textual language that a ‘pony 8,2
more Casi read as oppocey St
= Machine language,“ °PP05€d to
eader file eader fl ostrea
K Performs remeare
preprocessor fles before they are °oea
. compiler,” * he
Translates the source
compiler language, nme
+ The fle containing the
Object file ‘source code. Gobi) ‘ansated
ae + Unks the object le wih action!
Code, such as the library codes,
4 The file containing the final product
Executablecode * (1S) Lite
cH
Fig. .6 Environment of Visual
The Parts of the Screenfe programing language (Laboratory Mochlg)
esriton
Pine
oat
‘eo (Standard Too! 8?)
me
Moietestre
Coe
fence
eg Woden
Sut wan
Soca
geevennunnk
overview ofthe Menu bar
z
ea vw art Bott QA Tooke Wreow tela
Fig. 7. Menu Bar
Mena Description
Fie related commands that operate on your
rogram fe, sh as loading 8 program from
Fle Gk saving program-you entered to disk, and
breing the progam,
Incudes options that sid In adding, changing,
eae Sercing for, and deleting text from the current
rogram:
ations for moving around the edltor and
lew contoting the dsp.
Tie gt des the Bung command, wher
uns the compiler and inker, andthe Exec
role command, whch enables "You to. test yout
‘rogram without leaving the workbench.
Used for examining C++ clases,
‘TRS ul-down menu inudes the command that
Debug
Faun YouD amine the code as If runs to REP
YoU get erors out of your program.
cores Poem ae ay may
Special features that can
Tools vertbench S'S "ME Be ated to he
Option for seta up he
Options suit the way a progam woe toe beer
Standard. Windows men
arronging the wingers,
Visual C++ proves a
heb. insted‘ having
Help Cet reference manny you cn sagnfal
Various heprelte tps to ts rae
need about he wobec ot go
Window (or selecting ang
1 assorted of ntne
10 lookin 2 bay Va
Creating your frst Visual C++ Program
41. On your Task Bar dick START, then chose Program,
lick Mierosot Visual Stodo 66, Mereson Wisco Coy
(Figure 3.| ‘ programing Lang02ge 1 (Laboratory Hodis
1 Meno Bar cick Fle | New 2 dlalog Box similar
ure below will apPedT.
2, On you
tothe f
Figure 9. Dialog Box for Visual C++ Source File
3. Click on the TAB BAR File, and then choose C++ Source
Fie.
4. On your work area type the following commands
Tinea
11 rrints “Welcore to Visual C++ Programming” on
‘
couteerWeteoge to Visual Co4™
5. Preparing to save your program,
* Te save your rogram, on your Menu Bar Click File |
» ida
Programming ty
PIT (abrery Madey
{THE STRUCTURE OF A C++ PROGRAM
This is your rst C++ tnguage
display the message “Welcome a” 7esoouan
will
CH
Programming”.
7 Finelide ostream a>
2 //erints "Welcome to Visual civ pr
3 ine main)
on
‘ cout<
‘The #include directive is a spectal type of instruction
called @ preprocessor directive. This \s an instruction to the }
compiler to take the entire fle lostream.h and pace It Inthe
program.
The preprocessor Isa program that modifies your source
file prior to compilation. Common preprocessor directives art
‘include which Is used to include additonal code ito your
Source Mle; #define, which Is used to define a constant; and
4) endif, which can be used to conditionally determine which
parts of your code will be compiled. i
2. // Prints "Welcome to Visual C++ Programming” on
‘Screen
The nex nen our program is 3 comment, Canmens
are explanations or anottion tat ate ncused i a ore |
for documentation and oteation pose.
‘The "compler does not generate machin, cde fr
comments. any ine of text laced ate te smb
between Slash AstershAsterisiash/**/ 1 ard by
comple.
cv
‘are are two nays to spect aconment ta Cr,
Te mstanded cory we an
surround conmenseye Programming \AnDwene aberetery Hoey,
pera eee
see ttt Sno cme in unm or
povottis
———
Fc seccomicone to Visual €¥¥ Programing
11 te main, tunetson,
3 tatamalo()
unaertns wregured n every -* ProAraM, USL, when
ree peo a ce er pea
Seam ea. Tat met hee nk man
2 a Fa the program labeled int main () and
“0
‘tis endoses the Body ofthe program. Usually the cury
races enoe more program tins, such 95 this
[ire ii to vise e+ tronanming™ on
int) // Te main function.
te a statement terminator. Each action in C44 iS 8
Satenet, and» semisian must end each one.
emTT nH ae tay pay
a
op ne CS EO emt noe
wasn sens
eee
arenas cae eae
ur th sean pero ce hae Ue ene
ns al
SE SS ae ne
eis eS aa
Beers, ent Se
Sele Meese Se arge
TRIRTRTIR
Weriote © © C8 Programing.
Seay oe roremen )
6 return 0;
‘This causes main to retum 2 zero value Indeating to the
operating system thatthe program terminated normaty
Indentation
Indentation Is another feature tat makes your rogram
cexsy tread. Indentation Is 9 technique of groupe es ot
fence by category. For example, we sow Ut the tay of 2
fndion starts with an opening cry bracket "(and eds with
2 closing curly bracket =)". To dei the ems hat ar de
‘of function, you should indent them by tee emp soaces oF
fone tb. By default, Mlcroso Visual Stuso sts 2 TaD pes 2
A eharacters.
Using indentation, the program could be wrten:
nt maint)
> coutcctwetcone to iss
Progeanming\a"t
aeae
‘programming Language 3 (Laboratory
My
should be incremental. That Is, wher
rndentatlon na
ltd ofthe previous line, the neg It
toppers t2 DE ee
Sse einer
ESCAPE SEQUENCES
onprinung characters are 21S0 called es
choracers. Tese oi
erocters are fot printed but are use et
format text cSPaY-
cot Craracter | —__Meantng
Form feed
New Line ~ Unefeed
[yf een et
_— ee 7 |
iE
1
Horizontal Tab
Vertical Tab
Backspace
Meaning —
To
Single quote
[== fount quate
z ‘Question Mark
‘Backslash
How to complle and execute your program.
“These are the following steps In compiling and executing
your program:
1. On your Menu Bar cick Bulld | comple.
P
10. Screen Layout after compiling your program.
Wot: Vs und ne yy
Ut you fa he tor eno" ey
I When fds a eros ght Bebe
found the error. To view where the crt, 8S Where
Gn the actual ear eemreeset
ne Fa z
to highlight the following ting ress
Indeator pointing where ash
fe He tes
the er Is an
care
Figure 12, Compiled Mle with enor message
You ‘fix the rer m
5 can fx the ee By moving he evs
end of the line where the statement beginni be
COUT does not have semicon ten te he mee
Ser eyping the smile repeat step Iga i
aed aro oneetee renner UNE Haag,
ane that thee BO WHC), O Warn
mene anae ea asta
innate atthe ry
&
Ms
OLTNT |, , ial
Figure 13, Output of the Program
DAANPLE 21-1: Using coute< amd \
‘rhe peigram disslays the stn Inside the eoutce
command and escape character \Al as shown In the ‘sample
‘extout Below:
LOWCHART PROGRAM
(-]
FF} erctatecsotrean n>
p / | Treeee mesons ung cok
hamaal ng
=,
remang,
Ht
7 |< xt Tectrlageal Universty
Parmsnny / | ver
y / | execs Aree, Maaeng Cty
‘coxt<<"Coblege of Engineering
/ Tore 7) Sigh ae eae
weve / |?
[+]
Te ne ny
Using 0 1t<< and \q
The program ales the stig nade
cayman ahd encape craters, Ye eye ee
seit blow se
FLOWCHART PRoGKAM
ncaa n>
ran
ac HOMER 25 Wt
'
enteel Suh
Wed ha Eon
wwe . t
Catec WWE 1N2¥I VAS Yt, i
GoRceUENTVAVOVIDET:
lavisyisyary
1 |
BRD we, i
coaced 350
eccd UBER LW:
7Programming Language 1 (Laboratory Moxduje,
8
Pz 6 Prograr
{ea ne re tent ay
co “mn
‘Te Keywords of @ programming i
'
puit-n. vocabulary for the programmer Raz, consthute
buteal, Ad2, most Notably, COBOL, these words mumes, 35 In
rasgned’ THe, MONS Cat. hey we ae ace
programmer, who May Not use them to denote present
roped words. A Keyword cannot be used acs apes
lable name,
‘tere are 32 words defined as ke
nave presetined uses and cannot be eed ees CA: Thee
nave c++ program. They are used by the complies ne eet
‘mmaling the program. They are always writen in execs
Pempete st follows; ae
auto double int
break else tong struct
case enum ree each
char extem a ed
const joat sare va
continue for signed vastned
default goto Seeot vd
° " stat wile
IDENTIFIERS.
‘An Identifier is a name given to an entity within 2
program. Tt can be used as variables and constant names,
procedures and function names and names of user-defined data
types.
‘Also, Identifiers are words that provide access to
program and data entities. An example of a program-level
Identifier Is @ procedure name. An example of @ data-level
Identifier is a Varlable name. A programmer supplies some
identifiers, and some are keywords that have been bult into
the language. The maximum length of an Identifer i up to 255
characters.
VARIABLE NAMES:
Variable names identity the locaton n which data wd
by te executing program stored. arabes 2 Ike
hntsners In your computers memory you can tore vv
them and retrieve or modiy them when necessaryprograming L89V098 Laborato
7 Met
le means to store a v
fo INTIALZE 2 variad alu in
ve rages emch fs ane wna the ASST
tre
Ie TOR, hike tis: = 2+
9 variable names
‘rules In givins
1 wget SM I et
mo
een vata COTS ATE OE Slomg
tr ate ay vara neat
ptable. However, student ane"?
» ere
2 a ee as Soca ne
ence, cannot be used in the migale
weasenth aot ans
ames °
aaa names are case-sensitive; ence count ang
art are two diferent variables.
5, feo short and eypHe Mames Such 25 X OF WE Use
Ayo Shiy. descriptive names Such 8S average,
‘gross_pay, net_amount.
eerie
cra re green
sitferent.
‘Examples of valid Identifiers/variable names
sum resistori
umd student_name
Examples of invalid identifiers variable names
student age distance*time
Anum itemsi
|\eare Powe nas ay rey
cet STATEMENTS
so
Se
ws ee lac gt, Meo sod pes
Expression Statements
Selection Statements
Repetition Statements
Jump Statements
Labeled Statements
Compound Statements
[ASSIGNMENT STATEMENTS
fan assignment statement instructs
saluate the expression on the rightshand deat
Sdlue of the variable equal to that value of the eee
ssignment statement consists of a vanabe om he ee,
‘ide of the assignment operator and an expression oe tee na
hand side. The assignment operator is representa oy
‘equality sign (=) used to assign a value to a variable, =
‘the computer to
Examples:
The value 5 is assigned tx
“The value of xis stored In
“The sum of x and y is stored
Introduction to Namespaces
‘A namespace is a technique of grouping some functions
and/or classes to create an entity. Ths has the main goal of
eliminating the probabilty of having two functions or two
classes with the same name. For example, i diferent people
work on the same project, each one can create his of her own
classes but put them In only his or her namespace. Ths way,
even if they happen to have a class each with the same name,
there is no risk of having a name confi.
(One of the ways you can use a namespace Is with the
using keyword. To do this, before accessing the namespace,
on‘ roemmnng LANUA08 Laboratory
type using flowed bY U8 FAME OF ING MBH,
Hee 1s exer
‘ou can aso postion the using namespace expression
on the top section ofthe fie orn header le.
‘he C#+ Stanford provides @ namespace called at
sme atd Namespace Includes 8 sees of lbvaries that you wi
Mosely and. regulary use I yOUr programs. Therefor,
Taser You need to use a Nbrary that Is part of the etd
caeccrace insted of typing a brary with fle extension, as
PRgetenm.h, you con lus ype the name ofthe Hbrary 36 In
Tostream: Then, on the secone ine, type using namespace
1g; Aeon example, Instead of typing
[Gee Pome ne. ete hy
iia Toa nee
Tiigg nanepace atc)
nt aun?
cout < "Welcome to Visual C44 Programming qe)
DATA TYPES AND TYPE DECLARATIONS
ve ins Sa ea ohne
sr a area et abc
Ie roe oh nent eeen tena
Su ces Savas a ad
we
Data type Is the type of value or category ot dat»
wit be entered Inthe program, “
Below Is 8 Ist ofthe exiting fundomertal data yes in
cs os wel os the range of vals that con be epee op
Sone of them:
c++ Data types:
Name [Description [Sha Tange.
ied “a8 7
exam:
Tecra aT aa be
ine — [ger fod — fis
stontreun> Hort THE lsortinener ew ine UE IT
mensch sh ‘ome : re. 214 a8
aint Lingieaee fone tensity
ins, etn header, sacause te regent, 0067
scone ecg conms tothe C+ standard, we wl se I pian va
ner we fad on ts aes. oot esntaie testo fone frcerase
is ro Jales:truwo alse pe
Ines ranesace ovis the mens of dling 9 ak — sing pt sanser fogs — an aL
save we sean inetd ramespace hess tho es aie” aible recon Je 0 5 8)
relia ent use cuk oheed ye ee eee cd
loned tthe abe até et i semaan Ree 28 Tong ano se pease papas fresno (ene)
duit fate pasar
[Wide character bytes fi wide carat‘programming Lang.298 1taboratry
Medi
‘The int Data Type
-1234, -25, 0, 4567, 89, +910
ne tot oat T¢
aes ere
ax Sd ea elope nese
ecu osta T°
9 fry key on your Keyboard. When using chev
ere oe to ene a
Fe er taus we Sen
Ho
oe
PON
~,
Note that a blank space Is a character and is written as +
+, with 9 space between the single quotation marks. Thus, the
Trae "ode Is not of a type char. Furthermore, even though
the symbol “e=' greater than or equal and similar special
Symbols are considered to be one symbol, they are not
egarded a5 possible values of the data type char. All the
Indwidsal syrnbols located on the keyboard that are printable
may be considered as possible values of the char data types,
Different character data sets are currently in use. The
most common are American Standard Code for Information
Interctange (ASCH) and Extended Binary-Coded Decimal
Interchange Code (EBCIDE|IC). The ASCII set has 128 values;
each character sets a different character. For Example the
value 65 represents ‘A’, and the value 64 represents *=". See
‘Appendix A
405
PTT L808 Hite,
“pe oating Point Data Types
‘To represent real tumbers, C++ uses
yn called floating point notation, 7yo™ of Sdentiic
1th gus the example of Real Numb erzanying
‘able point Notation. inte Co
‘me String Data Types
pelea fas eee ys bao
oe
‘yan DelaCruz™
ssohnny”
«This Is an empty space
Every character in a string has a relative position with
the string. The position of the first character is 0, the postion
of the second IS 1, and so on, The length of a’ string is the
fnumber of characters init,
[7 String] Position of Character in | Length of the —]
a String String.
jan Dec Sin the 0 postion | “13 fneudng sos]
‘is nthe 3 positon
= (pace) i in the 5 postion
‘is in the 1 postion
This inthe 2 postion
Poa Jis in the O postion —
iis in the 3 position
‘nisin the 4 position
yyisin the 5 postion
106