BITG 1233 - WordPress.com...cout is defined in the header file iostream, to place data to standard...

51
BITG 1233: Introduction to C++ 1

Transcript of BITG 1233 - WordPress.com...cout is defined in the header file iostream, to place data to standard...

Page 1: BITG 1233 - WordPress.com...cout is defined in the header file iostream, to place data to standard output device (the display) We use the insertion operator

BITG 1233:

Introduction to C++

1

Page 2: BITG 1233 - WordPress.com...cout is defined in the header file iostream, to place data to standard output device (the display) We use the insertion operator

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

Page 3: BITG 1233 - WordPress.com...cout is defined in the header file iostream, to place data to standard output device (the display) We use the insertion operator

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; // Tells 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

6

Page 4: BITG 1233 - WordPress.com...cout is defined in the header file iostream, to place data to standard output device (the display) We use the insertion operator

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

Page 5: BITG 1233 - WordPress.com...cout is defined in the header file iostream, to place data to standard output device (the display) We use the insertion operator

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

Page 6: BITG 1233 - WordPress.com...cout is defined in the header file iostream, to place data to standard output device (the display) We use the insertion operator

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

Page 7: BITG 1233 - WordPress.com...cout is defined in the header file iostream, to place data to standard output device (the display) We use the insertion operator

• 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

Page 8: BITG 1233 - WordPress.com...cout is defined in the header file iostream, to place data to standard output device (the display) We use the insertion operator

• 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

Page 9: BITG 1233 - WordPress.com...cout is defined in the header file iostream, to place data to standard output device (the display) We use the insertion operator

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

Structure of a C++ Program : Function

9 LECTURE 3

Page 10: BITG 1233 - WordPress.com...cout is defined in the header file iostream, to place data to standard output device (the display) We use the insertion operator

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

Page 11: BITG 1233 - WordPress.com...cout is defined in the header file iostream, to place data to standard output device (the display) We use the insertion operator

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

Page 12: BITG 1233 - WordPress.com...cout is defined in the header file iostream, to place data to standard output device (the display) We use the insertion operator

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

Page 13: BITG 1233 - WordPress.com...cout is defined in the header file iostream, to place data to standard output device (the display) We use the insertion operator

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

Page 14: BITG 1233 - WordPress.com...cout is defined in the header file iostream, to place data to standard output device (the display) We use the insertion operator

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

Page 15: BITG 1233 - WordPress.com...cout is defined in the header file iostream, to place data to standard output device (the display) We use the insertion operator

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

Page 16: BITG 1233 - WordPress.com...cout is defined in the header file iostream, to place data to standard output device (the display) We use the insertion operator

Valid names

A

student_name

_aSystemName

pi

al

stdntNm

_anthrSysNm

PI

Invalid names

sum$ // $ is illegal

2names // can’t start with 2

stdnt Nmbr // can’t have

space

int // can’t use reserved

word

16

Identifiers

LECTURE 3

Page 17: BITG 1233 - WordPress.com...cout is defined in the header file iostream, to place data to standard output device (the display) We use the insertion operator

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

Page 18: BITG 1233 - WordPress.com...cout is defined in the header file iostream, to place data to standard output device (the display) We use the insertion operator

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;

const int NUM_STATES = 50;

18 LECTURE 3

Page 19: BITG 1233 - WordPress.com...cout is defined in the header file iostream, to place data to standard output device (the display) We use the insertion operator

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

Page 20: BITG 1233 - WordPress.com...cout is defined in the header file iostream, to place data to standard output device (the display) We use the insertion operator

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

Page 21: BITG 1233 - WordPress.com...cout is defined in the header file iostream, to place data to standard output device (the display) We use the insertion operator

Figure 3.4 Variables in memory

21

Variables

LECTURE 3

Page 22: BITG 1233 - WordPress.com...cout is defined in the header file iostream, to place data to standard output device (the display) We use the insertion operator

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

Page 23: BITG 1233 - WordPress.com...cout is defined in the header file iostream, to place data to standard output device (the display) We use the insertion operator

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

Page 24: BITG 1233 - WordPress.com...cout is defined in the header file iostream, to place data to standard output device (the display) We use the insertion operator

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

Page 25: BITG 1233 - WordPress.com...cout is defined in the header file iostream, to place data to standard output device (the display) We use the insertion operator

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

Page 26: BITG 1233 - WordPress.com...cout is defined in the header file iostream, to place data to standard output device (the display) We use the insertion operator

Standard Data Type

26 LECTURE 3

Page 27: BITG 1233 - WordPress.com...cout is defined in the header file iostream, to place data to standard output device (the display) We use the insertion operator

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

Page 28: BITG 1233 - WordPress.com...cout is defined in the header file iostream, to place data to standard output device (the display) We use the insertion operator

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 computer’s memory as an integer representing the ASCII code.

– Usually use 1 byte of memory

LECTURE 3

Page 29: BITG 1233 - WordPress.com...cout is defined in the header file iostream, to place data to standard output device (the display) We use the insertion operator

int

– A number without a fraction part (round or integer)

– C++ supports three different sizes of integer

• short int

• int

• long int

Data types

Typical integer size 29 LECTURE 3

Page 30: BITG 1233 - WordPress.com...cout is defined in the header file iostream, to place data to standard output device (the display) We use the insertion operator

float

A number with fractional part such as 43.32

C++ supports three types of float

float

double

long double

30

Data types

Typical float size LECTURE 3

Page 31: BITG 1233 - WordPress.com...cout is defined in the header file iostream, to place data to standard output device (the display) We use the insertion operator

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

Page 32: BITG 1233 - WordPress.com...cout is defined in the header file iostream, to place data to standard output device (the display) We use the insertion operator

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";

Page 33: BITG 1233 - WordPress.com...cout is defined in the header file iostream, to place data to standard output device (the display) We use the insertion operator

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

Page 34: BITG 1233 - WordPress.com...cout is defined in the header file iostream, to place data to standard output device (the display) We use the insertion operator

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

34

Page 35: BITG 1233 - WordPress.com...cout is defined in the header file iostream, to place data to standard output device (the display) We use the insertion operator

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 35

Page 36: BITG 1233 - WordPress.com...cout is defined in the header file iostream, to place data to standard output device (the display) We use the insertion operator

Figure 3.5 Library functions and the linker 36

Input / output function

LECTURE 3

Page 37: BITG 1233 - WordPress.com...cout is defined in the header file iostream, to place data to standard output device (the display) We use the insertion operator

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

Page 38: BITG 1233 - WordPress.com...cout is defined in the header file iostream, to place data to standard output device (the display) We use the insertion operator

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

Page 39: BITG 1233 - WordPress.com...cout is defined in the header file iostream, to place data to standard output device (the display) We use the insertion operator

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

Page 40: BITG 1233 - WordPress.com...cout is defined in the header file iostream, to place data to standard output device (the display) We use the insertion operator

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

Page 41: BITG 1233 - WordPress.com...cout is defined in the header file iostream, to place data to standard output device (the display) We use the insertion operator

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

Page 42: BITG 1233 - WordPress.com...cout is defined in the header file iostream, to place data to standard output device (the display) We use the insertion operator

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

Page 43: BITG 1233 - WordPress.com...cout is defined in the header file iostream, to place data to standard output device (the display) We use the insertion operator

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

Page 44: BITG 1233 - WordPress.com...cout is defined in the header file iostream, to place data to standard output device (the display) We use the insertion operator

Example 1

44

// 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;

}

LECTURE 3

Output :

Enter two integral numbers : 10 6

10 / 6 is 1 with a remainder of 4

Page 45: BITG 1233 - WordPress.com...cout is defined in the header file iostream, to place data to standard output device (the display) We use the insertion operator

/*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;

}

Example 2

45

LECTURE 3

Page 46: BITG 1233 - WordPress.com...cout is defined in the header file iostream, to place data to standard output device (the display) We use the insertion operator

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

Page 47: BITG 1233 - WordPress.com...cout is defined in the header file iostream, to place data to standard output device (the display) We use the insertion operator

Formatting Output

We can identify functions to perform special task.

For the input and output objects, these functions have been given 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

Page 48: BITG 1233 - WordPress.com...cout is defined in the header file iostream, to place data to standard output device (the display) We use the insertion operator

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

48 LECTURE 3

Page 49: BITG 1233 - WordPress.com...cout is defined in the header file iostream, to place data to standard output device (the display) We use the insertion operator

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

49 LECTURE 3

Page 50: BITG 1233 - WordPress.com...cout is defined in the header file iostream, to place data to standard output device (the display) We use the insertion operator

//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;

}

Example:

50

LECTURE 3

Page 51: BITG 1233 - WordPress.com...cout is defined in the header file iostream, to place data to standard output device (the display) We use the insertion operator

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