You are on page 1of 50

BITG 1113:

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>

using namespace std; Standard namespace

#define pi 3.142
Global declaration
float A_cyl;

int main() main() function


{
float radius, height; Local declaration

cout<<”Please enter radius: “; Statements


cin>>radius;
cout<<”Please enter height: “;
cin>>height;

A_cyl = 2*pi*radius*height;

cout<<”Area for the cylinder is “


<<A_cyl<<endl;

return 0;
}

Figure 1: Structure of a C++ Program


3
Structure of a C++ Program
• C++ program is made up of a global declaration section and
one or more functions
– Preprocessor directive & global declaration section come
at the beginning of the program
– Function contains two types of codes
• Declaration (local declaration)
– Data that you’ll 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

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

Valid names Invalid names

– 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

a+5 // numeric literal


3.1435 // a float literal
“Hello” // a string literal
19
Constants
– 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 easy
to find and change

• E.g #define pi 3.142

• The way define work is that the expressions that


follows the name (3.142) replaces the name
wherever it is found in the program (like search and
replace command) 20
Constants
– 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 constant
where we can add the type qualifier, const before the
definition
• E.g
const float pi = 3.142;

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>

Reserved words using namespace std;


Identifier
#define pi 3.142
float A_cyl;

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;

cout<<”Area for the cylinder is “


<<A_cyl<<endl;

return 0;
}

Figure 3: C++ Language Element 23


Data types
• Type defines a set of value and operations that
can be applied on those values

• Set of values for each type is known as the


domain for the type

• Functions also have types which is determined by


the data it returns

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)

• They serves as the basic building blocks for derived


types (complex structures that are built using the
standard types

• Derived types are pointer, enumerated type, union,


array,structure and class
26
Data types
 void
– Has no values and operations
– Both set of values are empty

 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

unsigned long int 4 0 4,294,967,295


Typical integer size 28
Data types

• 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

double 8 15 10-307 ..10308

long double 16 19 10-4931 ..104932

Typical float size 29


Data types

 Boolean (logical data)


– C++ support bool type
– C++ provides two constant to be used
• True
• False
– Is an integral which is when used with other
integral type such as integer values, it converted
the values to 1 (true) and 0 (false)

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

Figure 4: Variables in memory


32
Variables Declaration

• Variable declaration syntax :


<variable type> <variable name>
• Examples:
– short int maxItems; // word separator : capital
– long int national_debt; // word separator : _
– float payRate; // word separator : capital
– double tax;
– char code;
– bool valid;
– int a, b; // equivalent to int a; int b;

33
Variable initialization
• Initializer establishes the first value that the variable will
contain

• To initialize a variable when it is defined, the identifier is


followed by the assignment operator (=) and then the
initializer which is the value the variable is to have when
the functions starts
– int count = 0;
– int count , sum = 0;
• Only sum is initialize.
– int count=0 , sum = 0; OR int count =0; int sum = 0;

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

/= z /=2 z = z/2 z=4

%= y %=x y = y%x y=1

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

Equality Sample Expression Value


Operators
== x==5 T

!= y!=6 F
37
Logical Operator
Logical Operators Called Sample Operation

&& AND expression1 && expression 2

|| OR expression1 | | expression2

! NOT ! expression

Example : Assume int x = 50


expression !expression Sample
Expression

F T !(x = = 60)

T F !(x ! = 60)
38
Logical Operator

Example : Assume int x = 4, y=5, z=8;

expression1 expression2 expression1 && Sample Expression


expression2

F F F ( y > 10) && ( z < =x )

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;

expression1 expression2 expression1 | | Sample Expression


expression2

F F F ( y > 10) | | ( z <=x )

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

++ preincrement ++a a = a +1 Increment a by 1, then use


  the new value of a in
a += 1 expression in which a reside

++ postincrement a++ a = a +1 Use the current value of a in


  the expression which a
a += 1 reside, then increment a by 1

-- predecrement --a a = a -1 Decrement a by 1, then use


  the new value of a in
a -= 1 expression in which a reside

-- postdecrement a-- a = a -1 Use the current value of a in


  the expression which a
a -= 1 reside, then decrement a by
1
Operator Precedence
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

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;

cout << “Enter two integral numbers:”;


cin >> num1 >> num2;
calc = num1/num2;

cout << num1 << “ / ” << num2 << “is “


<< calc;

calc = num1 % num2;


cout << “with a remainder of: “ << calc
<< endl;
return 0; 44
}
Example 2
/*Evaluate two complex expression*/
#include <iostream>
using namespace std;
void main ( )
{
int a =3, b=4, c = 5, x, y;
cout << “Initial values of the variables:\n”;
cout << “a = “ << a<< “ b = “ << b
<<“ c = “ << c<< endl;
Output :
cout << endl;
Initial values of the variables :
x = a * 4 + b / 2 – c * b;
a=3 b=4 c= 5
cout << “Value of a * 4 + b/2-c * b is : “
<< x << endl; Value of a * 4 + b/2-c * b is : -6
y = - - a * (3 + b) / 2 – c++ * b; Value of - - a * (3 + b) / 2 – c++ * b is: -13

cout << “Value of - - a * (3 + b) / 2 – c++” Values of the variables are now :


<< “* b is: “ << y << endl;
a=2 b=4 c= 6
cout << “a = “ << a << “ b = “ << b << “ c = “
<< c << endl;
}
Input / output function
• Output
– Symbol use is (<<)
– Example:

int age = 22;


cout << “ I am “ << age
<< “ years old and my name is “
<< name;

Output :

I am 22 years old and my name is Abu


46
Input / output function
• Input
– Symbol used is (>>)
– Example:

int age;
float a , b;
cin >> age;
cin >> a >> b;

– cin can process inputs from keyboard when


pressed enter
47
Formatting Output
 We can identify functions to perform special task.
 For the input and output objects, these functions
have been giving a special name: manipulator.
 The manipulator functions format output so that it is
presented in a more readable fashion for the user.
 Must include <iomanip> header file.
 #include <iomanip> header file contains
function prototypes for the stream manipulators
that enable formatting of streams of data.

48
Output Manipulators
 The lists of functions in the <iomanip> library file:

Manipulators Use

endl New line


dec Formats output as decimal
oct Formats output as octal
hex Formats output as
  hexadecimal
fixed Set floating-point decimals
showpoint Shows decimal in floating-
  point values
setw(…) Sets width of output fields
setprecision Specifies number of decimals
  for floating point
setfill(…) Specifies fill character

49
//demonstrate the output manipulator
#include <iostream>
#include <iomanip>
using namespace std;
int main( )
{
char aChar;
int integer;
float dlrAmnt;

cout << “Please enter an integer ,\n”


<< “ a dollar amount and a character.\n”;
Output :
cin >> integer>>dlrAmnt >> aChar;
Please enter an integer,
a dollar amount and a
cout <<“\nThank you.You entered:\n”; character.
cout << setw( 6 ) << integer << “ “ 12 123.45 G
<< setfill(‘*’) << setprecision (2) << fixed

Thank you. You entered:


<< ‘$’ << setw(10) << dlrAmnt
12 $****123.45 G
<< setfill(‘ ‘) << setw( 3 ) <<aChar<< endl;
}

You might also like