C++ Introduction to C++ Programming
-
Upload
paancute8982 -
Category
Documents
-
view
236 -
download
0
Transcript of C++ Introduction to C++ Programming
-
8/6/2019 C++ Introduction to C++ Programming
1/50
1
BITG 1113:Introduction to theIntroduction to the
C++ languageC++ language
LECTURE 3
-
8/6/2019 C++ Introduction to C++ Programming
2/50
2
Learning outcomes :Learning outcomes :
To know basic structure of C++programming
1. To introduce the concepts of
- data types
- constants
- variables- C++ operators
2. To introduce output manipulators
-
8/6/2019 C++ Introduction to C++ Programming
3/50
3
main() function
//Written by: Rosmiza Wahida
/*This program is to calculate the area
of a cylinder*/
#define pi 3.142
float A_cyl;
int main()
{
float radius, height;
coutradius;
coutheight;
A_cyl = 2*pi*radius*height;
cout
-
8/6/2019 C++ Introduction to C++ Programming
4/50
4
C++ program is made up of a global declaration section andone or more functions
Preprocessor directive & global declaration section comeat the beginning of the program
Function contains two types of codes
Declaration (local declaration)
Data that youll be using in the function
Also called local declaration because only visible
to the function that contain them Statement
Instructions to the computer to do something
Structure ofa C++ Program
-
8/6/2019 C++ Introduction to C++ Programming
5/50
5
In Figure 1, the program is to calculate the area ofa cylinder.
This program consist of :
Comments Preprocessor directive
Standard namespace
Global declaration
main() function
Function header
Local declaration
Statements
Structure ofa C++ Program
-
8/6/2019 C++ Introduction to C++ Programming
6/50
6
Structure ofa C++ Program
Preprocessor directives
- also known as pre-compiler directives - specialinstructions to the preprocessor that tell it how to prepareyour program for compilation
- #includeA command that tells the preprocessor, it needinformation from selected libraries known as headerfiles
-
8/6/2019 C++ Introduction to C++ Programming
7/50
7
In Figure 1, the preprocessor directive start with apound sign (# is a syntax in C++) #include
include tells the preprocessor that you want the libraryin the < >
Tells the compiler to include input/output streamheader file in the program
The program need this header file because it will print
a message to the console (monitor) All preprocessor directive starts withpound sign (#)
Format or syntax of this directive must be exact
No space between # and include
Structure ofa C++ Program
-
8/6/2019 C++ Introduction to C++ Programming
8/50
8
using namespace std;
Tells the compiler where to look for names in thelibraries.
These names have been organized into areasknown as namespaces.
The namespaces for standard system libraries isstandard, std.
Structure ofa C++ Program
-
8/6/2019 C++ Introduction to C++ Programming
9/50
9
- intmain( )
The word intsays that the function will return an integer value to theoperating system (main function)
Statements in main function are to print message and to terminate
the program
-
8/6/2019 C++ Introduction to C++ Programming
10/50
-
8/6/2019 C++ Introduction to C++ Programming
11/50
11
Example of comments
-
8/6/2019 C++ Introduction to C++ Programming
12/50
12
Comments cannot be nested (comments insidecomments)
Once the compiler sees an opening block-
comment token, it ignores everything it sees until itfinds the closing token Therefore, the opening token of nested comment is not
recognized and the ending token that matches the firstopening token is left standing on its own
Comments
-
8/6/2019 C++ Introduction to C++ Programming
13/50
13
Figure 2 Example of nested comments
-
8/6/2019 C++ Introduction to C++ Programming
14/50
-
8/6/2019 C++ Introduction to C++ Programming
15/50
15
Reserved word/ Keyword
C and C++ Reserved Words
auto
breakcasecharconst
continuedefault
do
doubleelseenumexternfloatfor
goto
ifintlong
registerreturnshort
signedsizeofstaticstructswitchtypedef
unionunsigned
voidvolatilewhile
C++ Reserved Words
asmboolcatchclasscin
const_cast
cout
deletedynamic_
castexplicitfalsefriendinline
interrupt
mutablenamespac
enew
operatorprivate
protectedpublic
registerreinterpret_cast
static_caststring
templatethisthrow
truetry
typeidtypenameusingvirtualwchar_t
A word that has special meaning in C++. Used only
for their intended purpose.Keywords cannot beused to name identifiers.
All reserves word appear in lowercase.
-
8/6/2019 C++ Introduction to C++ Programming
16/50
16
Identifiers Allows programmers to name data and other objects in the
program-variable, constant, function etc.
Can use any capital letter A through Z, lowercase letters athrough z, digits 0 through 9 and also underscore ( _ )
Rules for identifier
The first character must be alphabetic character orunderscore
It must consists only of alphabetic characters, digits andunderscores, cannot contain spaces
It cannot duplicate any reserved word
C++ is case-sensitive; this means that NUM1, Num1, num1,and NuM1 are four completely different words.
-
8/6/2019 C++ Introduction to C++ Programming
17/50
17
Examples of valid and invalid names
Validnames
A
student_name _aSystemName
pi
al
stdntNm
_anthrSysNm
PI
Invalidnames
$sum // $ is illegal
2names // cant startwith 2
stdnt Nmbr // cant havespace
int // reserved word
Identifiers
-
8/6/2019 C++ Introduction to C++ Programming
18/50
18
Constants Data values that cannot be changed during the
execution of a program
Types of constant Integer constant
Float constant
Numbers with decimal part
Character constant
Enclosed between two single quotes ()
String constant
A sequence of zero or more characters enclosed indouble quotes ()
Symbolic constant
Define constant and memory constant
-
8/6/2019 C++ Introduction to C++ Programming
19/50
19
Constants
Three different ways
Literal constants An unnamed constant used to specify data
If the data cannot be changed, we can simplycode the data value itself in a statement
E.g
A // a char literal
5 // a numeric literal 5
a + 5 // numeric literal
3.1435 // a float literal
Hello // a string literal
-
8/6/2019 C++ Introduction to C++ Programming
20/50
2
0
Defined constant Another way to designate a constant is to use the
preprocessor command define
Like other preprocessor commands, it is also
prefaced with the pound sign (#)
Placed at the beginning of a program to make it easyto find and change
E.g #define pi 3.142
The way define work is that the expressions thatfollows the name (3.142) replaces the namewherever it is found in the program (like search and
replace command)
Constants
-
8/6/2019 C++ Introduction to C++ Programming
21/50
2
1
Memory constant Use a type qualifier to indicate that data cannot be
changed and to fix the contents of the memory location
C++ provides the capability to define a named constantwhere we can add the type qualifier, constbefore thedefinition
E.g
const float pi = 3.142;
Constants
-
8/6/2019 C++ Introduction to C++ Programming
22/50
-
8/6/2019 C++ Introduction to C++ Programming
23/50
2
3
//Written by: Rosmiza Wahida
/*This program is to calculate the area of a
cylinder*/
#define pi 3.142
float A_cyl;
int main()
{
float radius, height;
coutradius;
coutheight;
A_cyl = 2*pi*radius*height;
cout
-
8/6/2019 C++ Introduction to C++ Programming
24/50
24
Data types
Type defines a set of value and operations thatcan be applied on those values
Set of values for each type is known as thedomain for the type
Functions also have types which is determined
by the data it returns
-
8/6/2019 C++ Introduction to C++ Programming
25/50
25
Data Type
Standard
-
8/6/2019 C++ Introduction to C++ Programming
26/50
26
C++ contains five standard types void
int (short for integer)
char (short for character)
float ( short for floating point)
bool (short for boolean)
They serves as the basic building blocks forderivedtypes (complex structures that are built using thestandard types
Derived types arepointer, enumerated type, union,array,structure and class
Data types
-
8/6/2019 C++ Introduction to C++ Programming
27/50
27
Data types
void Has no values and operations
Both set of values are empty
char Any value that can be represented in the
computers alphabet
A char is stored in a computers memory as aninteger representing the ASCII code
A character in C++ can be interpreted as a smallinteger(between 0 and 255). For this reason, C++treats a character like integer.
-
8/6/2019 C++ Introduction to C++ Programming
28/50
-
8/6/2019 C++ Introduction to C++ Programming
29/50
29
Float A number with fractional part such as 43.32
C++ supports three types of float
float
double long double
Data types
Type Byte
Size
Precision Range
float 4 6 10-37 ..1038
double 8 15 10-307 ..10308
long double 16 19 10-4931 ..104932
Typical float size
-
8/6/2019 C++ Introduction to C++ Programming
30/50
30
Boolean (logical data)
C++ support bool type
C++ provides two constant to be used
True False
Is an integral which is when used with otherintegral type such as integer values, it converted
the values to 1 (true) and 0 (false)
Data types
-
8/6/2019 C++ Introduction to C++ Programming
31/50
-
8/6/2019 C++ Introduction to C++ Programming
32/50
32
Figure 4: Variables in memory
Variables
-
8/6/2019 C++ Introduction to C++ Programming
33/50
-
8/6/2019 C++ Introduction to C++ Programming
34/50
34
Variableinitialization
Initializer establishes the first value that the variable willcontain
To initialize a variable when it is defined, the identifier is
followed by the assignment operator (=) and then theinitializer which is the value the variable is to have when thefunctions starts
int count = 0;
int count , sum = 0;
Only sum is initialize.
int count=0 , sum = 0; OR int count =0; int sum = 0;
-
8/6/2019 C++ Introduction to C++ Programming
35/50
-
8/6/2019 C++ Introduction to C++ Programming
36/50
36
Assignment Operator
Assignment
Operator
Sample
Expression
Similar
Expression
Value of variable
after assignment
+= x += 5 x = x + 5 x=9
-= y -= x y = y - x y=1
*= x *= z x = x*z x=32
/= z /=2 z = z/2 z = 4
%= y %=x y = y%x y=1
Assume int x = 4, y=5, z=8;
-
8/6/2019 C++ Introduction to C++ Programming
37/50
37
RelationalOperators
Sample Expression Value
> y > x T
< y < 2 F
> = x > = 3 T
< = y < = x F
EqualityOperators
Sample Expression Value
= = x = = 5 T
! = y ! = 6 F
Relational AndEqualityOperator
int y=6, x=5;
-
8/6/2019 C++ Introduction to C++ Programming
38/50
38
Logical Operators Called Sample Operation
&& AND expression1 && expression 2
| | OR expression1 | | expression2
! NOT ! expression
Logical Operator
expression !expression Sample
Expression
F T !(x = = 60)
T F !(x ! = 60)
Example : Assume int x = 50
-
8/6/2019 C++ Introduction to C++ Programming
39/50
-
8/6/2019 C++ Introduction to C++ Programming
40/50
40
expression1 expression2 expression1 | |
expression2
Sample Expression
F F F ( y > 10) | | ( z
-
8/6/2019 C++ Introduction to C++ Programming
41/50
Operator Called Sample
Expression
Similar
Expression
Explanation
++ preincrement ++a a = a +1
a += 1
Increment a by 1, then use
the new value of a in
expression in which a reside
++ postincrement a++ a = a +1
a += 1
Use the current value of a in
the expression which a
reside, then increment a by 1
- - predecrement - - a a = a -1
a -= 1
Decrement a by 1, then use
the new value of a in
expression in which a reside
- - postdecrement a - - a = a -1
a -= 1
Use the current value of a in
the expression which a
reside, then decrement a by
1
Increment anddecrement Operator
-
8/6/2019 C++ Introduction to C++ Programming
42/50
42
Operators Associative
( ) Left to right
++ - - + - ! Right to left
* / % Left to right
+ - Left to right
< >= Left to right
= = != Left to right
&& Left to right
| | Left to right
= *= += - = /= %= Right to left
OperatorPrecedence
-
8/6/2019 C++ Introduction to C++ Programming
43/50
43
Example 1:
int a=10, b=20, c=15, d=8;
a*b/(-c*31%13)*d
1. a*b/(-15*31%13)*d
2. a*b/(-465%13)*d
3. a*b/(-10)*d
4. 200/(-10)*d
5. -20*d
6. -160
Example 2:
int a=15, b=6, c=5, d=4;
d *= ++b a/3 + c
1. d *= ++b a/3+ c
2. d*=7- a/3+c
3. d*=7- 5+c
4. d*=2 + c
5. d*= 7
6. d = d*7
7. d = 28
OperatorPrecedence
-
8/6/2019 C++ Introduction to C++ Programming
44/50
-
8/6/2019 C++ Introduction to C++ Programming
45/50
/*Evaluate two complex expression*/
#include using namespace std;
void main ( )
{
int a =3, b=4, c = 5, x, y;
cout
-
8/6/2019 C++ Introduction to C++ Programming
46/50
46
Input / output function
Output Symbol use is (
-
8/6/2019 C++ Introduction to C++ Programming
47/50
-
8/6/2019 C++ Introduction to C++ Programming
48/50
48
FormattingOutput
We can identify functions to perform special task.
For the input and output objects, these functionshave been giving a special name: manipulator.
The manipulator functions format output so that it ispresented in a more readable fashion for the user.
Must includeheader file.
#include header file contains
function prototypes for the stream manipulatorsthat enable formatting of streams of data.
-
8/6/2019 C++ Introduction to C++ Programming
49/50
49
Output Manipulators
The lists of functions in thelibrary file:
Manipulators Use
endl
dec
oct
hex
fixed
showpoint
setw()
setprecision
setfill()
New line
Formats output asdecimal
Formats output as octal
Formats output as
hexadecimal
Set floating-point decimals
Showsdecimal in floating-
point values
Sets width of output fields
Specifiesnumberofdecimalsforfloating point
Specifies fill character
-
8/6/2019 C++ Introduction to C++ Programming
50/50
//demonstrate the output manipulator
#include
#include
using namespace std;
int main( )
{
char aChar;
int integer;
float dlrAmnt;
cout integer>>dlrAmnt >> aChar;
cout