Sunteți pe pagina 1din 51

BITG 1233:

1233:
Introduction to C++
by: ZARITA (FTMK)

LECTURE 3
1 (Sem 2, 15/16)
Learning Outcomes
At the end of this lecture, you should be able to:
Identify basic structure of C++ program (pg 3)
Describe the concepts of :
Character set. (pg 11)
Token (pg 13): keyword, identifiers, operator,
punctuation, string literal
Data type (pg 25)
Input function, output function (pg 33)
Operator (pg 37) : arithmetic operators & assignment
operators
Formatting the Output (pg 49)
2 LECTURE 3
Basic Structure of a C++ Program
/* This program computes the distance between two
points. */ comment
#include <iostream> // Required for cout, endl.
#include <cmath> // Required for sqrt()
using namespace std; // Tells which namespace to use
comments
// Define and initialize global variables.
double x1=1, y1=5, x2=4, y2=7;

int main() function named main


{ beginning of block for 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. string literal
6
cout << "The distance between the two points is "
<< distance << endl;
// Exit program.
return 0; send 0 to operating system
}
end of block for main

3 LECTURE 3
Figure 3.1 Structure of a C++ Program
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
Structure of a C++ Program : Preprocessor
Directives
• 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
LECTURE 3
Structure of a C++ Program : using Directive

• 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.

8 LECTURE 3
Structure of a C++ Program : Function

 A function’s process 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 LECTURE 3
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 Enclose header file name in
brackets #include
( ) Open and close Used when naming a
parentheses function
{ } Open and close Encloses a group of
brace statements
" " Open and close Encloses string of
quotation marks 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
 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 & special characters except
underscore)
 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
Identifiers

Valid names Invalid names

A  sum$ // $ is illegal
 student_name  2names // can’t start with 2
 _aSystemName  stdnt Nmbr // can’t have
 pi space
 al  int // can’t use reserved
 stdntNm word
 _anthrSysNm
 PI

16 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
constant’s scope. Add the type qualifier, const before the definition.
 E.g. const double TAX_RATE = 0.0675;
18 const int NUM_STATES = 50; 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
Variables

Figure 3.4 Variables in memory


21 LECTURE 3
Variables

 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;

Examples of variable definition

22 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

 Special character use for completing program structure


 Includes the symbols [ ] ( ) { } , ; : * #

Operator
 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 data types are pointer, enumerated type, union, array,


structure and class.

27 LECTURE 3
Data types

 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 computer’s memory as an integer
representing the ASCII code.
– Usually use 1 byte of memory

28 LECTURE 3
Data types
 int
– A number without a fraction part (round or integer)
– C++ supports three different sizes of integer
• short int
• int
• long int

29 LECTURE 3 Typical integer size


Data types

 float
 A number with fractional part such as 43.32
 C++ supports three types of float
 float
 double
 long double

30 LECTURE 3 Typical float size


Data types

 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)

31 LECTURE 3
Determining the Size of a Data Type

The sizeof operator gives the size of any data type or


variable:
double amount;
cout << "A double is stored in "
<< sizeof(double) << "bytes\n";
cout << "Variable amount is stored in "
<< sizeof(amount)
<< "bytes\n";
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

33 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 :
34
I am 22 years old and my name is Abu
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;

35 LECTURE 3
Input / output function

36 LECTURE 3 Figure 3.5 Library functions and the linker


Arithmetic Operators
 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

37 LECTURE 3
Assignment Operators
• Assume int x=4, y=5, z=8;
Assignmen Sample Similar Value of variable
t 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

38 LECTURE 3
Increment and decrement Operators
Operator Called Sample Similar Explanation
Expression Expression

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


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

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


evaluate the expression in
a += 1 which a reside, then increment a
by 1
-- predecrement --a a = a -1 Decrement a by 1, then use
the new value of a to evaluate
a -= 1 the expression in which a
reside
-- postdecrement a-- a = a -1 Use the current value of a to
evaluate the expression in which
a -= 1 a reside, then decrement a by 1

For example: assume k=5 prior to executing each of the following statement.
m = ++k; both m and k become 6
39 n = k--; n becomes 5, k becomes 4
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


= += -= *= /= %=

40 LECTURE 3
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
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 - 15 / 3 + c
3. a * b / (-10) * d 3. d* = 7- 5 + c
4. 200 / (-10) * d 4. d*= 2 + 5
5. -20 * d 5. d*= 7
6. -160 6. d = d * 7
7. d = 28
43 LECTURE 3
Example 1
// operating with variables
#include <iostream>
using namespace std;

int main()
{
int num1, num2;
int value_div, value_mod ;

cout << "Enter two integral numbers:";


cin >> num1 >> num2;
value_div = num1/num2;
value_mod = num1 % num2;
cout << num1 << " / " << num2 << " is "<< value_div;
cout<<" with a remainder of " << value_mod <<endl;
return 0;
}
Output :
Enter two integral numbers : 10 6

LECTURE 3 10 / 6 is 1 with a remainder of 4


44
LECTURE 3
Example 2
/*Evaluate two complex expressions*/

#include <iostream>
using namespace std;

int 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;
cout << endl;
x = a * 4 + b / 2 - c * b;
cout << "Value of a * 4 + b / 2 - c * b is : "<< x <<endl;
y = --a * (3 + b) / 2 - c++ * b;
cout << "Value of --a * (3 + b) / 2 – c++ * b is: ";
cout << y << endl << endl;
cout << "Values of the variables now are :\n";
cout << "a = " << a << " b = " << b << " c = "<< c <<endl;
return 0;
}
45
Output :
Initial values of the variables :
a = 3 b = 4 c = 5

Value of a * 4 + b / 2 - c * b is : -6
Value of --a * (3 + b) / 2 – c++ * b is: -13

Values of the variables are now :


a = 2 b = 4 c = 6

46
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.
47 LECTURE 3
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

48 LECTURE 3
Basic Command of Output : Escape Sequence

Escape Name Description


Sequence

\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

49 LECTURE 3
Example: LECTURE 3

//demonstrate the output manipulator


#include <iostream>
#include <iomanip>
using namespace std;

int main( )
{
char letter;
int num;
float amount;

cout << "Please enter an integer,";


cout << " a dollar amount and a character.\n";
cin >> num >> amount >> 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;
return 0;
50 }
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 ---

51 LECTURE 3

S-ar putea să vă placă și