Professional Documents
Culture Documents
Introduction to the
C++ language
LECTURE 3
1
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
2
//Written by: Rosmiza Wahida
Comments
/*This program is to calculate the area
of a cylinder*/
Preprocessor directive
#include <iostream>
#define pi 3.142
Global declaration
float A_cyl;
A_cyl = 2*pi*radius*height;
return 0;
}
4
Structure of a C++ Program
• In Figure 1, the program is to calculate the area of
a cylinder.
• This program consist of :
– Comments
– Preprocessor directive
– Standard namespace
– Global declaration
– main() function
• Function header
• Local declaration
• Statements 5
Structure of a C++ Program
• Preprocessor directives
- also known as pre-compiler directives - special
instructions to the preprocessor that tell it how to prepare
your program for compilation
- #include
•A command that tells the preprocessor, it need
information from selected libraries known as header
files
6
Structure of a C++ Program
• In Figure 1, the preprocessor directive start with a
pound sign (# is a syntax in C++)
– #include <iostream>
• include tells the preprocessor that you want the library
in the < >
• Tells the compiler to include input/output stream
header file in the program
• The program need this header file because it will print
a message to the console (monitor)
• All preprocessor directive starts with pound sign (#)
• Format or syntax of this directive must be exact
• No space between # and include
7
Structure of a C++ Program
– using namespace std;
•Tells the compiler where to look for names in the
libraries.
•These names have been organized into areas
known as namespaces.
•The namespaces for standard system libraries is
standard, std.
8
Structure of a C++ Program
- int main( )
• The word int says that the function will return an integer value to the
operating system (main function)
• Statements in main function are to print message and to terminate
the program
• << sign (insertion operator) places the text string that follows it into
an output stream that is written to the console
• The output string contains what you want to displayed enclosed in
double quote marks ( “ )
•“endl” at the end of the message tells the computer to advance to
the next line in the output.
• return 0 terminates the program
•The body of the function starts with an open brace and terminates
with a closed brace. { }
9
Comments
• Is a program documentation which is ignored by the compiler
when it translates the program into executable codes
• Two format
– Block comment
• Uses opening and closing comment token ( one or more
symbols that compiler understood when it interpret codes
• Opening token (/* ) and closing token (*/)
• Use for long comment
– Line comment
• Uses two slashes (//)
• Does not require an end-of-comment token
• Use for short comment
10
Example of comments
11
Comments
• Comments cannot be nested (comments inside
comments)
• Once the compiler sees an opening block-
comment token, it ignores everything it sees until it
finds the closing token
– Therefore, the opening token of nested comment is not
recognized and the ending token that matches the first
opening token is left standing on its own
12
Figure 2 Example of nested comments
13
Character Set And Token
Character set consist of :
1. Number : 0 to 9
2. Alphabetical : a to z and A to Z
3. Spacing
4. Special Character :
, . : ; ? ! ( ) {} “ ‘ + - * / = > < # % & ^ ~ | / _
Token : combination of the characters , consist of
1. Reserved words/keywords 4. Literal String
2. Identifiers 5. Punctuators
3. Constants 6. Operators
14
Reserved word/ Keyword
A word that has special meaning in C++. Used only
for their intended purpose.Keywords cannot be
used to name identifiers.
All reserves word appear in lowercase.
C and C++ Reserved Words
auto do goto signed union
break double if sizeof unsigned
case else int static void
char enum long struct volatile
const extern register switch while
continue float return typedef
default for short
C++ Reserved Words
asm delete mutable register true
bool dynamic_ namespac reinterpret_cast try
catch cast e static_cast typeid
class explicit new string typename
cin false operator template using
const_cas friend private this virtual
t inline protected throw wchar_t
cout interrupt public 15
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 a
through z, digits 0 through 9 and also underscore ( _ )
• Rules for identifier
– The first character must be alphabetic character or
underscore
– It must consists only of alphabetic characters, digits and
underscores, 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.
16
Identifiers
– A – $sum // $ is illegal
– student_name – 2names // can’t start
– _aSystemName with 2
– pi – stdnt Nmbr // can’t have
– al space
– – int // reserved word
stdntNm
– _anthrSysNm
– PI
Examples of valid and invalid names 17
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 in double
quotes (“)
– Symbolic constant
• Define constant and memory constant
18
Constants
• Three different ways
– Literal constants
• An unnamed constant used to specify data
• If the data cannot be changed, we can simply
code the data value itself in a statement
• E.g
‘A’ // a char literal
5 // a numeric literal 5
21
Punctuator
Use for completing program structure
Including [ ] ( ) { } , ; : * # symbols
Operator
C++ uses a set of built in operators ( Eg : +, -, *, /
etc).
There are several classes of operators : Arithmetic,
relational, logical and assignment.
22
//Written by: Rosmiza Wahida
/*This program is to calculate the area of a
cylinder*/
Constant
#include <iostream>
int main()
{
float radius, height;
Punctuator
cout<<”Please enter radius: “;
Operator
cin>>radius;
cout<<”Please enter height: “;
cin>>height;
A_cyl = 2*pi*radius*height;
return 0;
}
24
Data Type Standard
25
Data types
• C++ contains five standard types
– void
– int (short for integer)
– char (short for character)
– float ( short for floating point)
– bool (short for boolean)
char
– Any value that can be represented in the
computer’s alphabet
– A char is stored in a computer’s memory as an
integer representing the ASCII code
– A character in C++ can be interpreted as a small
integer(between 0 and 255). For this reason, C++
treats a character like integer.
27
Data types
– integer
– A number without a fraction part
– C++ supports three different sizes of integer
• short int
• int
• long int
Type Byte Size Minimum Maximum Value
Value
short int 2 -32,768 32,767
unsigned short int 2 0 65,535
int 2 -32,768 32,767
unsigned int 2 0 65,535
long int 4 -2,147,483,648 2,147,483,647
• Float
– A number with fractional part such as 43.32
– C++ supports three types of float
• float
• double
• long double
Type Byte Precision Range
Size
float 4 6 10-37 ..1038
30
Variables
• Named memory locations that have a type, such as
integer or character and a size which is inherited from
their type
• Each variables in programs must be declared and
initialize
• variables, the declaration gives them a symbolic
name and initialization reserves memory for them
• Once initialize, variables are used to hold the data
that are required by the program from its operation
• When a new value is assigned to a variable, the old
value is destroyed
31
Variables
33
Variable initialization
• Initializer establishes the first value that the variable will
contain
34
Operators
• Few symbols in assignment (umpukan) statements
which have been used in programs
Assume int a=4, b= 5, d;
C++ Arithmetic C++ Value of d
Operation Operator Expression after
assignment
Addition + d=a+b 9
Substraction - d=b-2 3
Multiplication * d=a*b 20
Division / d = a/2 2
Modulus % d = b%3 2
35
Assignment Operator
Assume int x = 4, y=5, z=8;
Assignment Sample Similar Value of variable
Operator Expression Expression after assignment
+= x += 5 x=x+5 x=9
-= y -= x y=y-x y=1
*= x *= z x = x*z x=32
36
Relational And Equality Operator
int y=6, x=5;
Relational Sample Expression Value
Operators
> y>x T
< y<2 F
>= x>=3 T
<= y<=x F
!= y!=6 F
37
Logical Operator
Logical Operators Called Sample Operation
|| OR expression1 | | expression2
! NOT ! expression
F T !(x = = 60)
T F !(x ! = 60)
38
Logical Operator
F T F ( z < = y) && ( x = = 4)
T F F ( y ! = z) && ( z < x )
T T T ( z > = y ) && ( x ! =
3)
39
Logical Operator
Example : Assume int x = 4, y=5, z=8;
F T T ( z <= y) | | ( x == 4)
T F T ( y != z) | | ( z < x )
T T T ( z >= y ) | | ( x != 3 )
40
Increment and decrement Operator
Operator Called Sample Similar Explanation
Expression Expression
42
Operator Precedence
Example 1: Example 2:
int a=10, b=20, c=15, d=8; int a=15, b=6, c=5, d=4;
a*b/(-c*31%13)*d d *= ++b – a/3 + c
1. a*b/(-15*31%13)*d 1. d *= ++b – a/3+ c
2. a*b/(-465%13)*d 2. d*=7- a/3+c
3. a*b/(-10)*d 3. d*=7- 5+c
4. 200/(-10)*d 4. d*=2 + c
5. -20*d 5. d*= 7
6. -160 6. d = d*7
7. d = 28
43
Example 1
// operating with variables
#include <iostream>
Output :
using namespace std;
Enter two integral numbers : 10 6
int main()
10 / 6 is 1 with a remainder of 4
{
//declare variables
int num1;
int num2;
int calc;
Output :
int age;
float a , b;
cin >> age;
cin >> a >> b;
48
Output Manipulators
The lists of functions in the <iomanip> library file:
Manipulators Use
49
//demonstrate the output manipulator
#include <iostream>
#include <iomanip>
using namespace std;
int main( )
{
char aChar;
int integer;
float dlrAmnt;