Introduction To C++
Introduction To C++
Introduction To C++
1
LECTURE 3
Learning Outcomes
At the end of this lecture, you should be able to:
Identify basic structure of C++ program
Describe the concepts of :
Character set.
Token: keyword, identifiers, operator, punctuation,
input & output
Data type
Input/output function
Operator : arithmetic operators & assignment operators
Formatting the Output
2
LECTURE 3
Figure 3.1 Structure of a C++ Program
Basic Structure of a C++ Program
3
/* This program computes the distance between two
points. */
#include <iostream> // Required for cout, endl.
#include <cmath> // Required for sqrt()
using namespace std; // Which namespace to use
// Define and initialize global variables.
double x1=1, y1=5, x2=4, y2=7;
int main()
{
// Define local variables.
double side1, side2, distance;
// Compute sides of a right triangle.
side1 = x2 - x1;
side2 = y2 - y1;
distance = sqrt(side1*side1 + side2*side2);
// Print distance.
cout << "The distance between the two points is "
<< distance << endl;
// Exit program.
return 0;
}
send 0 to operating system
beginning of block for main
end of block for main
function named main
comment
comments
string literal
LECTURE 3
Structure of a C++ Program : Comments
Use to write document parts (notes) of the
program.
Comments help people read programs:
Indicate the purpose of the program
Describe the use of variables
Explain complex sections of code
Are ignored by the compiler.
In C++ there are two types of comments.
Single-Line comments : Begin with // through to
the end of the line.
Multi-Line comments : Begin with /* and end with
*/
4
LECTURE 3
Single-Line Comments
Use to write just one line of comment :
Example :
int length = 12; // length in inches
int width = 15; // width in inches
int area; // calculated area
// calculate rectangle area
area = length * width;
5
LECTURE 3
Multi-Line Comments
Could span multiple lines:
/* this is a multi-line
comment
*/
Could begin and end on the same line:
int area; /* calculated area */
6
LECTURE 3
Provide instructions to the compiler that are performed
before the program is translated.
Begin with a pound sign (#)
Do NOT place a semicolon (;) at the end of a
preprocessor directive line.
Example:
#include <iostream>
The #include directive instructs the compiler to include the
statements from file iostream into the program.
The program needs <iostream> header file because it
might need to do input and/or output operations.
7
Structure of a C++ Program : Preprocessor
Directives
LECTURE 3
Instructs the compiler to use files defined in
a specified area. The area is known as
namespace.
Example :
using namespace std;
The namespaces of the standard C++
system libraries is std.
Structure of a C++ Program : using Directive
8
LECTURE 3
A function is defined between a set of braces { }.
Example:
int main()
{ //Block defines body of main function
double x1 = 1, x2 = 4, side1;
side1 = x2 x1;
cout << side1 << endl;
return 0; //Function main returns 0 to the OS
} //end definition of main
Every C++ program MUST contains only one
function named as main(), and could consist of
other function/s.
C++ program always begins execution in main() .
9
Structure of a C++ Program : Function
9
LECTURE 3
10
Structure of a C++ Program : Global/Local
Declarations Area
An identifier cannot be used before it is defined.
The areas where identifiers in a program are declared
determines the scope of the identifiers.
The scope of an identifier: the part of the program in
which the identifier can be accessed.
Local scope - a local identifier is defined or declared in
a function or a block, and can be accessed only within
the function or block that defines it.
Global scope - a global identifier is defined or declared
outside the main function, and can be accessed within
the program after the identifier is defined or declared.
10
LECTURE 3
Character Set
Consist of :
1. Number : 0 to 9
2. Alphabet : a to z and A to Z
3. Spacing
4. Special Character :
, . : ; ? ! ( ) {} + - * / = > < # % & ^ ~ | / _
11
LECTURE 3
Special Characters
Character Name Meaning
//
Double slash Beginning of a comment
#
Pound sign Beginning of preprocessor
directive
< >
Open and close
brackets
Enclose header file name in
#include
( )
Open and close
parentheses
Used when naming a
function
{ }
Open and close
brace
Encloses a group of
statements
" "
Open and close
quotation marks
Encloses string of
characters
;
Semicolon End of a programming
statement
Token
Combination of characters, that consist of :
1. Reserved words/keywords
2. Identifiers (variable, constant, function name)
3. Punctuators
4. Operators
5. String Literal
13
LECTURE 3
Reserved word/ Keyword
C and C++ Reserved Words
auto
break
case
char
const
continue
default
do
double
else
enum
extern
float
for
goto
if
int
long
register
return
short
signed
sizeof
static
struct
switch
typedef
union
unsigned
void
volatile
while
C++ Reserved Words
asm
bool
catch
class
cin
const_cast
cout
delete
dynamic_cast
explicit
false
friend
inline
interrupt
mutable
namespace
new
operator
private
protected
public
register
reinterpret_cast
static_cast
string
template
this
throw
true
try
typeid
typename
using
virtual
wchar_t
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.
14
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 CASE, Case,
case, and CaSe are four completely different words.
15
LECTURE 3
Valid names
A
student_name
_aSystemName
pi
al
stdntNm
_anthrSysNm
PI
Invalid names
sum$ // $ is illegal
2names // cant start with
2
stdnt Nmbr // cant have
space
int // cant use reserved
word
16
Identifiers
LECTURE 3
Identifiers : Constant
Constant is memory location/s that store a specific value
that CANNOT be modified during the execution of a
program.
Types of constant:
Integer constant
Float constant
Numbers with decimal part
Character constant
A character enclosed between a set of single quotes (
)
String constant
A sequence of zero or more characters enclosed in a
set of double quotes ( ) 17
LECTURE 3
Constant: How to Define
How a constant is defined is reflected as Defined
constant and Memory constant
Defined constant
Placed at the preprocessor directive area.
Using the preprocessor command define prefaced with
the pound sign (#)
E.g #define SALES_TAXES_RATE .0825
The expression that follows the name (.0825) replaces
the name wherever it is found in the program.
Memory constant
Placed at global/local declaration area, depending on
constants scope. Add the type qualifier, const before
the definition.
E.g. const double TAX_RATE = 0.0675;
const int NUM_STATES = 50;
18
LECTURE 3
Constant : How to use
Constant can be used in two ways.
Literal constant : by writing the value directly in
the program.
E.g
10 is an integer literal constant
4.5 is a floating point literal constant
"Side1" is a string literal constant
'a' is a character literal constant
Named constant : by using a name to represent
the value in the program. Often the name is written
in uppercase letters.
19
LECTURE 3
Identifiers : Variables
Variable is memory location/s that store values that can be
modified.
Has a name and a type of data it can hold.
Must be defined before it can be used.
A variable name should reflect the purpose of the variable.
For example: itemsOrdered
The purpose of this variable is to hold the number of
items ordered.
Once defined, variables are used to hold the data that are
required by the program from its operation.
Example:
double x1=1.0, x2=4.5, side1;
side1 = x2-x1;
x1, x2 and side1 are examples of variables that can be
modified.
20
LECTURE 3
Figure 3.4 Variables in memory
21
Variables
LECTURE 3
Examples of variable definition
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;
22
Variables
LECTURE 3
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 that part of the program executes.
Eg:
int count = 0;
int count , sum = 0; // Only sum is initialize.
int count=0 , sum = 0; OR int count =0; int sum = 0;
23
LECTURE 3
Punctuator
Operator
Special character use for completing program
structure
Includes the symbols [ ] ( ) { } , ; : * #
C++ uses a set of built in operators ( Eg : +, -, *, /
etc).
There are several types of operators : arithmetic,
assignment, relational and logical.
24
LECTURE 3
Data types
Type that 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
25
LECTURE 3
Standard Data Type
26
LECTURE 3
Data types
C++ contains five standard data types
void
int (short for integers)
char (short for characters)
float ( short for floating points)
bool (short for boolean)
They serves as the basic structure for derived data types
Derived types are pointer, enumerated type, union,
array, structure and class.
27
LECTURE 3
Data types
28
void
Has no values and operations
Both set of values are empty
char
A value that can be represented by an
alphabet, digit or symbol
A char is stored in a computers memory as an
integer representing the ASCII code.
Usually use 1 byte of memory
LECTURE 3
int
A number without a fraction part (round or integer)
C++ supports three different sizes of integer
short int
int
long int
Data types
Type
Byte Size
Minimum
Value
Maximum 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
29
LECTURE 3
float
A number with fractional part such as 43.32
C++ supports three types of float
float
double
long float
30
Data types
Type
Byte
Size
Precision
Range
float
4
6
10
-37
..10
38
double
8
15
10
-307
..10
308
long double
16
19
10
-4931
..10
4932
Typical float size
LECTURE 3
bool
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)
Data types
31
LECTURE 3
Input / output function
Input function cin
cin is used to read input from standard input
device (the keyboard)
Input retrieved from cin with the extraction operator >>
cin, requires iostream header file
Input is stored in one or more variables. Data entered
from the keyboard must be compatible with the data type
of the variable.
E.g of program:
int age;
float a , b;
cin >> age; // input must be an integer number
cin >> a >> b; // input must be two real numbers
32
LECTURE 3
Input / output function
Output function - cout
cout is defined in the header file iostream, to place
data to standard output device (the display)
We use the insertion operator << with cout to output
string literals, or the value of an expression.
String literals contains text of what you want to display.
Enclosed in double quote marks ( ). An expression
is a C++ constant, identifier, formula, or function call.
E.g of program : Assume the age input is 22 and name
is Abu.
cout << " I am " << age;
cout << " years old and my name is ";
cout << name;
Output :
I am 22 years old and my name is Abu
33
Displaying a Prompt
A prompt is a message that instructs the user
to enter data.
You should always use cout to display a
prompt before each cin statement.
Example:
cout << "How tall is the room? ";
cin >> height;
LECTURE 3
34
Figure 3.5 Library functions and the linker
35
Input / output function
LECTURE 3
Example
36
// input output example
#include <iostream>
using namespace std;
int number();
int main()
{
int x;
x = number();
cout<<"The number is" <<x;
return 0;
}
int number()
{
int num;
cout<<"Please enter an integer";
cin>>num;
return num;
}
LECTURE 3
Arithmetic Operators
Assume int a=4, b=5, d;
37
C++
Operation
Arithmetic
Operator
C++
Expression
Value of d
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
LECTURE 3
Assignment Operators
38
Assignmen
t 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;
LECTURE 3
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 to evaluate the
expression in which a reside
++
postincrement
a++
a = a +1
a += 1
Use the current value of a to
evaluate the expression in
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 to evaluate
the expression in which a
reside
- -
postdecrement
a - -
a = a -1
a -= 1
Use the current value of a to
evaluate the expression in which
a reside, then decrement a by 1
Increment and decrement Operators
39
For example: assume k=5 prior to executing each of the
following statement.
m = ++k; both m and k become 6
n = k--; n becomes 5, k becomes 4
LECTURE 3
40
Precedence of Arithmetic and
Assignment Operators
Precedence Operator Associativity
1 Parentheses: () Innermost first
2 Unary operators
+ - ++ - -
Right to left
3 Binary operators
* / %
Left ot right
4 Binary operators
+ -
Left ot right
5 Assignment operators
= += -= *= /= %=
Right to left
A Closer Look at the / Operator
/ (division) operator performs integer division if
both operands are integers
cout << 13 / 5; // displays 2
cout << 91 / 7; // displays 13
If either operand is floating point, the result is
floating point
cout << 13 / 5.0; // displays 2.6
cout << 91.0 / 7; // displays 13.0
41
LECTURE 3
A Closer Look at the % Operator
% (modulus) operator computes the remainder
resulting from integer division
cout << 13 % 5; // displays 3
% requires integers for both operands
cout << 13 % 5.0; // error
42
LECTURE 3
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 - 15 / 3 + c
3. d* = 7- 5 + c
4. d*= 2 + 5
5. d*= 7
6. d = d * 7
7. d = 28
Operator Precedence
43
LECTURE 3
Example 1
44
// operating with variables
#include <iostream>
using namespace std;
void input_number();
void calculate(int number1, int number2);
void display(int answer, int num1, int num2, int value_mod);
int main()
{
input_number();
return 0;
}
LECTURE 3
void input_number()
{
int num1;
int num2;
cout << "Enter two integral numbers:";
cin >> num1 >> num2;
calculate(num1,num2);
}
void calculate(int number1, int number2)
{
int value_div,value_mod ;
value_div = number1/number2;
value_mod = number1 % number2;
display(value_div, number1, number2, value_mod);
}
45
LECTURE 3
void display(int answer, int num1, int num2, int value_mod)
{
cout << num1 << " / " << num2 << "is "<< answer;
cout<<" with remainder of " << value_mod;
}
Output :
Enter two integral numbers : 10 6
10 / 6 is 1 with a remainder of 4
46
LECTURE 3
/*Evaluate complex expression*/
#include <iostream>
using namespace std;
void main()
{
int a = 3; b = 4, c = 5;
int x, y = 7;
x = --a * (3 + b) / 2 c++ * b;
cout << " Value of x is " << x << endl;
y %= 2;
cout << " Value of y is " << y << endl;
}
Example 2
47
LECTURE 3
Output :
Value of x is -13
Value of y is 1
48
Formatting Output
We can identify functions to perform special task.
For the input and output objects, these functions have been giv 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.
Eg: #include <iomanip>
<iomanip> header file contains function prototypes for the stream
manipulators that enable formatting of streams of data.
49
LECTURE 3
Output Manipulators
The lists of functions in the <iomanip> library file:
Manipulators
Use
endl
dec
oct
hex
fixed
showpoint
setw()
setprecision
setfill()
New line
Formats output as decimal
Formats output as octal
Formats output as hexadecimal
Set floating-point decimals
Shows decimal in floating-point
values
Sets width of output fields
Specifies number of decimals for
floating point
Specifies fill character
50
LECTURE 3
Escape
Sequence
Name Description
\t
Horizontal Tab Takes the cursor to the next tab stop
\n or endl New line
Takes the cursor to the beginning of the next
line
\v
Vertical Tab Takes the cursor to the next tab stop vertically.
\"
Double Quote Displays a quotation mark (")
\'
Apostrophe Displays an apostrophe (')
\?
Question mark Displays a question mark
\\
Backslash Displays a backslash (\)
\a
Audible alert sound
Basic Command of Output : Escape Sequence
51
LECTURE 3
//demonstrate the output manipulator
#include <iostream>
#include <iomanip>
using namespace std;
void input();
void output(int num, float amount, char letter);
int main( )
{
input();
return 0;
}
Example:
52
LECTURE 3
void input()
{
char aChar;
int integer;
float dlrAmnt;
cout << "Please enter an integer,";
cout << " a dollar amount and a character.\n";
cin >> integer>>dlrAmnt >> aChar;
output(integer,dlrAmnt,aChar);
}
void output(int num, float amount, char letter)
{
cout <<"\nThank you.You entered:\n";
cout << setw( 6 ) << num << " " ;
cout << setfill('*') << setprecision (2) << fixed;
cout << 'RM' << setw(10) << amount;
cout << setfill(' ') << setw( 3 ) << letter << endl;
}
53
LECTURE 3
Output :
Please enter an integer,a dollar amount and character.
12 123.45 G
Thank you. You entered:
12 RM****123.45 G
--- THE END ---
54
LECTURE 3