THE C++ LECTURE 2 ON DATA STRUCTURES OF C++

sanatahiratoz0to9 15 views 44 slides Feb 27, 2025
Slide 1
Slide 1 of 44
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44

About This Presentation

IT IS SLIDE CONTAINING BASIC DATA TYPES OF C++


Slide Content

Variables, Data types
and Input/output
constructs
Lecture # 2
Course Instructor:
Dr. Afshan Jamil

Outline
Layout of
simple ++
program
Variables Identifiers
Assignment
statements
Uninitialized
variables
Output
using cout
Input using
cin
Escape
sequences
Data types Integers
Floating
point
Type char
Class stringType bool
Arithmetic
operators and
expressions
Comments
Naming
constants

Layout of a simple C++ program

Sample Program
•// This is a simple C++ program.
#include <iostream>
using namespace std;
int main()
{
cout<<“Welcome to Computer Programming
course”;
return 0;
}

CONTD…
#include<iostream>
•Aprogramincludesvariousprogrammingelements
thatarealreadydefinedinthestandardC++library.
•Inordertousesuchpre-definedelementsina
program,anappropriateheader/directivesmustbe
includedintheprogram.
•Directivesalwaysbeginwiththesymbol#.
•<iostream>isthenameofalibrarythatcontainsthe
definitionsoftheroutinesthathandleinputfromthe
keyboardandoutputtothescreen.
•Donotincludeextraspacebetweenthe<andthe
iostreamfilenameorbetweentheendofthefile
nameandtheclosing>.

•usingnamespacestd;
–Thislinesaysthatthenamesdefinedin
iostreamaretobeinterpretedinthe
“standardway”.
•intmain()
–Ittellsthatyourmainpartofaprogram
startshere.
•{}
–Bracesmarkbeginningandendofthe
mainfunction.
•return0;
–Thelastlineintheprogram.Itmarks
endoftheprogram.

Variables
•Variableisthebasicstorageunitinaprogram.Itis
anamegiventoamemorylocation.
•Thecompilerassignsamemorylocationtoeach
variablenameintheprogram.Thevalueofthe
variable,inacodedform,iskeptinthememory
locationassignedtothatvariable.
•Wedonotknowwhataddressesthecompilerwill
chooseforthevariablesinourprogram.
•Dataheldinavariableiscalleditsvalueoraliteral;
Number/dataheldbyaC++variablecanbe
changed.
•AC++variableisguaranteedtohavesomevaluein
it,ifonlyagarbagenumberleftinthecomputer’s
memorybysomepreviouslyrunprogram.

Names: Identifiers
•Identifiersareusedasnamesforvariablesand
otheritemsinaC++program.
•Tomakeyourprogrameasytounderstand,you
shouldalwaysusemeaningfulnamesforvariables.
•Rulesfornamingvariables:
–You cannot use a C++ keyword (reserved word)
as a variable name.
–Variable names in C++ can range from 1 to 255
characters.
–All variable names must begin with a letter of
the alphabet (a-z, A-Z) or an underscore( _ ).

CONTD…
•After the first initial letter, variable names
can also contain letters and numbers.
•No spaces or special characters allowed.
•C++ is case Sensitive. Uppercase characters
are distinct from lowercase characters.
•Examples:
–A,a_1,x123(legal)
–1ab,da%,1-2,(notacceptable)
–Test,test,TEST(case-sensitive)

Variable declarations
•EveryvariableinaC++programmustbedeclared
beforethevariablecanbeused.
•Whenyoudeclareavariable,youaretellingthe
compiler—and,ultimately,thecomputer—what
kindofdatayouwillbestoringinthevariable,and
whatsizeofmemorylocationtouseforthe
variable.
•Eachdeclarationendswithasemicolon(;).
•Whenthereismorethanonevariableina
declaration,thevariablesareseparatedby
commas.
•Thekindofdatathatisheldinavariableiscalled
itstypeandthenameforthetype,suchasintor
double,iscalledatypename.

Syntax
•Thesyntaxforaprogramminglanguagesistheset
ofgrammarrulesforthatlanguage.
•Thesyntaxforvariabledeclarationsisasfollows:
•Syntax
–Type_NameVar_Name_1, Var_Name_2, ...;
•Examples
–intcount,sum,number_of_person;
–doubledistance;

Assignment statements
•Inanassignmentstatement,firsttheexpression
ontheright-handsideoftheequalsignis
evaluated,andthenthevariableontheleft-hand
sideoftheequalsignissetequaltothisvalue.
•Inanassignmentstatement,theexpressionon
theright-handsideoftheequalsigncansimply
beanothervariableoraconstant.
•Syntax
–Variable=Expression;
•Examples
–sum=a;//variable
–distance=rate*time;//expression
–count=12;//constant

Uninitialized variables
•Variablethathasnotbeengivenavalueis
saidtobeuninitialized.
•Onewaytoavoidanuninitializedvariable
istoinitializevariablesatthesametime
theyaredeclared.
•Youcaninitializesome,all,ornoneofthe
variablesinadeclarationthatlistsmore
thanonevariable.
•Examples:
•intcount=0;doubleavg=99.9;inta=10,b,
c=0;

C++ Keywords/Reserved words

Output using cout
•Thevaluesofvariablesaswellasstringsoftext
maybeoutputtothescreenusingcout.
•Thearrownotation<<isoftencalledtheinsertion
operator.
•Youcansimplylistalltheitemstobeoutput
precedingeachitemtobeoutputwiththearrow
symbols<<.
•Stringsmustbeincludedindoublequotes.
•Examples:
–cout<<“Thisisourfirstc++program”;
–cout<<“Thesumis”<<sum;
–cout<<“distanceis”<<(time*speed);

Input using cin
•Acinstatementsetsvariablesequaltovalues
typedinatthekeyboard.
•cinisapredefinedvariablethatreadsdatafrom
thekeyboardwiththeextractionoperator(>>).
•Syntax
•cin>>Variable_1>>Variable_2>>...;
•Example
•cin>>number>>size;
•cin>>time;

Escape sequences
•Thebackslash,\,precedingacharacter
tellsthecompilerthatthecharacter
followingthe\doesnothavethesame
meaningasthecharacterappearingby
itself.
•Suchasequenceiscalledanescape
sequence.

CONTD…
Name Escape
sequence
Description
New line
\n
Cursor moves to next line
Horizontal tab
\t
Cursor moves to next tab stop
Beep
\a
Computer generates a beep
Backslash
\\
Backslash is printed
Single quote
\’
Single quotation mark is printed
Double quote
\”
Double quotation mark is printed
Return
\r
Cursor moves to beginning of
current line
Backspace
\b
Cursor moves one position left

Data Types
•Datatypesareusedtotellthevariablesthetype
ofdataitcanstore.
•WheneveravariableisdefinedinC++,the
compilerallocatessomememoryforthatvariable
basedonthedata-typewithwhichitisdeclared.
•Everydatatyperequiresadifferentamountof
memory.

Integertypes
•Theintegerdatatypebasicallyrepresentswhole
numbers(nofractionalparts).
•Thereasonisthreefold.
–First,somethingsintherealworldarenot
fractional.
–Second,theintegerdatatypeisoftenusedto
controlprogramflowbycounting.
–Third,integerprocessingissignificantlyfaster
withintheCPUthanisfloatingpointprocessing.

CONTD…

Floating point types
•The floating-point family of data types represents
number values with fractional parts.
•They are technically stored as two integer values:
amantissaand anexponent.
•They are always signed.
•A floating_pointnumber can also be a scientific
number with an "e" to indicate the power of 10:

Type char
•Valuesofthetypechararesinglesymbolssuch
asaletter,digit,orpunctuationmark.
•Avariableoftypecharcanholdanysingle
characteronthekeyboarde.g.,’A'or'+'oran
'a’.
•Notethatuppercaseandlowercaseversionsof
aletterareconsidereddifferentcharacters.
•Thetextindoublequotesthatareoutputusing
coutarecalledstringvalues.
•Besuretonoticethatstringconstantsare
placedinsideofdoublequotes,whileconstants
oftypecharareplacedinsideofsinglequotes.

Class string
•stringclassisusedtoprocessstringsinamanner
similartotheotherdatatypes.
•Tousethestringclasswemustfirstincludethe
stringlibrary:
•#include<string>
•Youdeclarevariablesoftypestringjustasyou
declarevariablesoftypesintordouble.
•stringday;
•day="Monday";

CONTD…
•Youmayusecinandcouttoreaddatainto
strings.
•Youcanuse‘+’operatorbetweentwostringsto
concatenatethem.
•Whenyouusecintoreadinputintoastring
variable,thecomputeronlyreadsuntilit
encountersawhitespacecharacter.Whitespace
charactersareallthecharactersthatare
displayedasblankspacesonthescreen,including
theblankorspacecharacter,thetabcharacter,
andthenew-linecharacter'\n’.Thismeansthat
sofaryoucannotinputastringthatcontains
spaces.

Type bool
•ExpressionsoftypeboolarecalledBoolean
aftertheEnglishmathematicianGeorgeBoole,
whoformulatedrulesformathematicallogic.
•Booleanexpressionsevaluatetooneofthetwo
values,trueorfalse.
•Booleanexpressionsareusedinbranchingand
loopingstatements.

Example
#include <iostream>
using namespace std;
intmain() {
bool isCodingFun= true;
int i=100;
float f=23.6;
char ch=‘h’;
doubled =12E4;
strings=“Hello”;
cout << isCodingFun<< endl;
cout << “value of int=“<<i<<endl;

CONTD…
cout << “value of float=“<<f<<endl;
cout << “value of double=“<<d<<endl;
cout << “value of char=“<<ch<<endl;
cout << “value of string=“<<s<<endl;
cout<<“ASCII value of
char=“<<int(ch)<<endl;
cout<<“Integer to char=<<“char(i)<<endl;
return0;
}

CONTD…
•OUTPUT:
1
value of int=100
value of float=23.6
value of ouble=1.2e+013
value of char=h
value of string=hello
ASCII value of char=104
Integer to char=d

sizeof() Function
•Thesizeofisakeyword,itisacompile-time
operatorthatdeterminesthesize,inbytes,ofa
variableordatatype.
•Thesizeofoperatorcanbeusedtogetthesize
primitiveaswellasuserdefineddatatypes.
•Thesyntaxofusingsizeofisasfollows:
•sizeof(datatype)

Example
#include<iostream>
usingnamespacestd;
intmain()
{
cout <<"Size of char : "<<sizeof(char)<<endl;
cout <<"Size of int : "<<sizeof(int)<<endl;
cout <<"Size of short "<<sizeof(shortint)<<endl;
cout <<"Size of long int : "<<sizeof(longint)<<endl;
cout <<"Size of long long: "<<sizeof(long long)<<endl;
cout <<"Size of float : "<<sizeof(float)<<endl;
cout <<"Size of double : "<<sizeof(double)<<endl;
return0;
}

Arithmetic operators and expressions
•InaC++program,youcancombinevariables
and/ornumbersusingthearithmeticoperators+
foraddition,–forsubtraction,*formultiplication,
and/fordivision.
•The%operationgivestheremainder.
•Thecomputerwillfollowrulescalledprecedence
rulesthatdeterminetheorderinwhichthe
operators,suchas+and*,areperformed.These
precedencerulesaresimilartorulesusedinalgebra
andothermathematicsclasses.

Precedence Rules

CONTD…

Comment
•InC++thesymbols//areusedtoindicatethestart
ofacomment.
•Allofthetextbetweenthe//andtheendofthe
lineisacomment.
•Thecompilersimplyignoresanythingthatfollows
//onaline.
•Anythingbetweenthesymbolpair/*andthe
symbolpair*/isconsideredacommentandis
ignoredbythecompiler.Unlikethe//comments,
/*to*/commentscanspanseverallines,

Naming constants
•Whenyouinitializeavariableinsideadeclaration,
youcanmarkthevariablesothattheprogramis
notallowedtochangeitsvalue.Todothis,place
thewordconstinfrontofthedeclaration,as
describedbelow:
•Syntax
•constType_NameVariable_Name=Constant;
•Examples
•constintMAX_TRIES=3;
•constdoublePI=3.14159;

setprecision()
•Thesetprecisionfunctionisusedtoformat
floating-pointvalues.
•Thisisabuiltfunctionandcanbeusedby
importingtheiomaniplibraryinaprogram.
•Byusingthesetprecisionfunction,wecan
getthedesiredprecisevalueofafloating-
pointoradoublevaluebyprovidingthe
exactnumberofdecimalplaces.

CONTD…
•Itcanbeusedtoformatonlythedecimal
placesinsteadofthewholefloating-point
ordoublevalue.
•Thiscanbedoneusingthefixedkeyword
beforethesetprecision()method.
•Syntax
•setprecision(number)

EXAMPLE
#include <iostream> Output:
#include<iomanip> 13.5634
using namespace std; 13.563400
int main ()
{
floatf = 13.5634;
cout<<setprecision(6)<<f<<endl;
cout<<fixed<<setprecision(6)<<f;
return0;
}

setw()
•setwfunctionisaC++manipulator
whichstandsforsetwidth.
•Themanipulatorspecifiesthe
minimumnumberofcharacter
positionsavariablewillconsume.
•Insimpleterms,ithelpssetthefield
widthusedforoutputoperations.
•Syntax
•setw(number)

CONTD…
#include <iostream> Output
#include <iomanip> Hello
using namespace std;
intmain ()
{
cout <<setw(10)<<"Hello"<<endl;
return0;
}

Class Task
•WriteaprogramthatplaysthegameofMadLib.
Yourprogramshouldprompttheusertoenterthe
followingstrings:
•Thefirstorlastnameofyourinstructor
•Yourname
•Afood
•Anumberbetween100and120
•Anadjective
•Acolor
•Ananimal

Contd…
•Afterthestringsareinput,theyshouldbe
substitutedintothestorybelowandoutputtothe
console.
DearInstructor[InstructorName],
IamsorrythatIamunabletoturninmyhomework
atthistime.First,Iatearotten[Food],whichmade
meturn[Color]andextremelyill.Icamedownwitha
feverof[Number100-120].Next,my[Adjective]pet
[Animal]musthavesmelledtheremainsofthe
[Food]onmyhomework,becauseheateit.Iam
currentlyrewritingmyhomeworkandhopeyouwill
acceptitlate.
Sincerely,
[YourName]

THE END