56
1 II Unit Tokens, Expressions and Control Structures

c++ II unit

Embed Size (px)

Citation preview

Page 1: c++ II unit

1

II UnitTokens, Expressions and Control

Structures

Page 2: c++ II unit

2

Tokens A token is the smallest element of a C++ program that is meaningful to the compiler. The C++ parser recognizes these kinds of tokens: identifiers, keywords, literals, operators, and other separators. A stream of these tokens makes up a translation unit. Tokens are usuallyseparated by "white space." White space can be one or more:

•Blanks

•Horizontal or vertical tabs

•New lines

•Comments

Page 3: c++ II unit

3

C++ Identifiers

An identifier is a sequence of characters used to denote one of the following:

•Object or variable name•Class, structure, or union name•Enumerated type name•Member of a class, structure, union, or enumeration•Function or class-member function•typedef name•Label name•Macro name•Macro parameter

Page 4: c++ II unit

4

The following characters are legal as the first character of an identifier, or any subsequent character:a b c d e f g h i j k l mn o p q r s t u v w x y zA B C D E F G H I J K L MN O P Q R S T U V W X Y Z

The following characters are legal as any character in an identifier except the first:0 1 2 3 4 5 6 7 8 9

Page 5: c++ II unit

5

KEYWORDS

Keywords are the reserved words that have predefined meanings in C++. They cannot be used as programmer defined identifiers. Since keywords are all lower case, it is possible to utilize an uppercase keyword as an identifier. The table lists some of the C++ keywords.

  

Page 6: c++ II unit

6

KEYWORDS

asm double new switchauto else operator template

break enum private thiscase extern protected throwcatch float public trychar for register typedefclass rand return unionconst goto short unsigned

continue if signed virtualdefault inline sizeof voiddelete int static volatile

do long struct while

Page 7: c++ II unit

7

Constant

Constants are used in a C++ program to store information that will not change while the program is running. They can be one of two general types:

•literal •symbolic

These are defined by:

•using the #define key word in the preprocessor •using the const key word •creating enumerators

Page 8: c++ II unit

8

Literals Invariant program elements are called "literals" or "constants." The terms "literal" and "constant“ are used interchangeably here. Literals fall into four major categories: integer, character, floating-point, and string literals.

A literal may be any of the following:integer-constantcharacter-constantfloating-constantstring-literal

Examples 57 // integer constant0xFE // integer constant'c' // character constant0.2 // floating constant0.2eֿº¹// floating constant"dog" // string literal

Page 9: c++ II unit

9

Defining C++ Constants with the Preprocessor

•The preprocessor is run before the program is compiled. It will look for any lines starting with a hash (#) and will then modify the code according to what it finds. An example of a constant defined in the preprocessor is: •#define pi_val 3.1416•When the preprocessor runs it will search the code for all instances of pi_val and replace it with the number 3.1416.

Page 10: c++ II unit

10

Defining C++ Constants with the const Key Word

• C++ constants can also be defined in the same way as C++ variables. The only difference is that the const key word is required:

• const float pi_val = 3.1416;• One important advantage of using the const key

word to define constants is that the data type will always be enforced.

Page 11: c++ II unit

11

Defining Enumerated Constants

An enumerated type is a series of named integer values created by using the enum key word,

for example: enum DAY {SUNDAY, MONDAY, TUESDAY,

WEDNESDAY, THURSDAY, FRIDAY, SATURDAY}; In this example SUNDAY will have the value 0 and

SATURDAY will be 6. However, the values can be initialized: enum DAY {MONDAY = 1, TUESDAY, WEDNESDAY,

THURSDAY, FRIDAY, SATURDAY, SUNDAY}; This time MONDAY will be 1 and SUNDAY will be 7.

The use of enumerators is clarified by seeing a working example given in next slide:

Page 12: c++ II unit

12

#include

enum DAY {MONDAY = 1, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY};int main () {int day;cout << "Enter day number: ";cin >> day;if ((day == SATURDAY) || (day == SUNDAY)) {cout << "Weekend"; }else if ((day >= MONDAY) && (day <= FRIDAY)) {cout << "Working Day";} else {cout << "Invalid Number";}return 0;}If 1 - 5 are input as the day number then the program will output "Working Day" or "Weekend" for 6 or 7.

Page 14: c++ II unit

14

Right shift assignment: >>= Subtraction Assignment: –= Bitwise

Logical

 

Miscellaneous

Multiplicative

Postfix

Bitwise AND: & Bitwise exclusive OR: ^ Bitwise inclusive OR: |

Logical AND: && Logical OR: ||

Comma: , Conditional: ? : Pointer-to-member: .* or –>*

Reference: & Scope resolution: ::

Division: / Modulus: % Multiplication: *

Subscript: [ ] Function call: ( ) Member access: . and –> Postfix decrement: –– Postfix increment: ++

Page 16: c++ II unit

16

String

A string is an array of characters whose last character is \0. A typical string, such as Pacifique, is graphically represented as follows: 

The last character \0 is called the null-terminating character. For this reason, a string is said to be null-terminated.

P A C I F I Q U E \0

Page 17: c++ II unit

17

Output statementscout << variable-name;

Meaning: print the value of variable <variable-name> to the user cout << “any message ”;

Meaning: print the message within quotes to the usercout << endl; Meaning: print a new line

Example:cout << a; cout << b << c;cout << “This is my character: “ << my-character << endl;

Cout << My-character

Screen

Object Insertion Operator/Put-to Operator

String

Page 18: c++ II unit

18

Input statementscin >> variable-name;Meaning: read the value of the variable called <variable-name> from the

user

Example: cin >> a; cin >> b >> c;cin >> my-character;

cin >> My-character

Object Extraction Operator/Get-from Operator

String

Keyboard

Page 19: c++ II unit

19

Variable declarationtype variable-name;Meaning: variable <variable-name> will be a variable of type

<type>

Where type can be: – int //integer– double //real number– char //character

Example: int a, b, c; double x;int sum;char my-character;

Page 20: c++ II unit

20

int main(){

long aCount;double theTotal;

...}

Page 21: c++ II unit

21

Variables will be declared in three basic places: inside functions, in the definition of function parameters, and outside of all functions. These are local variables and global variables.

Local VariablesVariables that are declared inside a function are called local variables.

Local variables may be referenced only by statements that are inside the block in which the variables are declared. In other words, local variables are not known outside their own code block. Remember, a block of codebegins with an opening curly brace and terminates with a closing curly brace.

Local variables exist only while the block of code in which they are declared is executing. That is, a local variable is created upon entry into its block and destroyed upon exit.

Page 22: c++ II unit

22

void func1(void){int x;x = 10;}

Page 23: c++ II unit

23

Global Variables

Unlike local variables, global variables are known throughout the program and may be used by any piece of code. Also, they will hold their value throughout the program's execution. You create global variables by declaring them outside of any function.

Page 24: c++ II unit

24

#include <iostream.h>int count; /* count is global */void func1(void);void func2(void);int main(void){count = 100;func1();return 0;}

Page 25: c++ II unit

Dynamic Initialization of variables

C++, permits initialization of the variables at run time. This referred to as dynamic initialization. In C++, a variable can be initialized at run time using expressions at the place of declaration.

float area = 3.1416 * rad *rad;

The initialization of a variable can be done simultaneously at the place where the variable is used for the first time.

float average;//declare where it is necessary

Average = sum/i;

Can be combined into a single statement:

float average =sum/i; // initialize dynamically at run time.25

Page 26: c++ II unit

Reference VariablesReference variable provides an alias(alternative name) for a previously defined variable.

data-type & reference-name =variable-name

Example:

float total =100;float sum =total;

A reference variable must be initialized at the time of declaration.

& is not an address operator. The notation float & means reference to float.

int n[10];

int & x=n[10]; //x is alias for n[10]

char & a =‘\n’; //initialize reference to a literal26

Page 27: c++ II unit

A major application of reference variables is in passing arguments to functions.

void f(int & x) //uses references

{

x=x+10; //x is incremented; so also m

}

int main()

{

int m =10;

f(m); //function call

….

}

When the function call f(m) is executed, the initialization occurs: int & x =m;

Thus x becomes an alias of m after executing the statement f(m);27

Page 28: c++ II unit

Such function calls are known as call by reference.

The call by reference mechanism is useful in object-oriented programming because it permits the manipulation of objects by reference, and eliminates the copying of object parameters back and forth. References can be created not only for built-in data types but also for user defined data types like structures and classes.

28

10

m

f(m) x

int m=10;

call

int & x=m;

Page 29: c++ II unit

Operator Precedence

29

Page 30: c++ II unit

Scope resolution OperatorThe scope resolution operator can allow access to a name in an

enclosing scope

that is "hidden" by a local declaration of the same name. For example,

int i; // global i

void f()

{

int i; // local i

i = 10; // uses local i

.

}

the assignment i = 10 refers to the local i. But what if

function f() needs to access the global version of i?30

Page 31: c++ II unit

It may do so by preceding the i with the :: operator, as shown here.

int i; // global i

void f()

{

int i; // local i

::i = 10; // now refers to global i

.

}

31

Page 32: c++ II unit

Memory Management operatorC++ provides two dynamic allocation operators: new and delete. These operators are used to allocate and free memory at run time. The new operator allocates memory and returns a pointer to the start of it. The delete operator frees memory previously allocated using new. The general forms of new and delete are shown here:

pointer_variable = new data-type.

Here, pointer variable is a pointer of type data-type. The new operator allocates sufficient memory to hold a data object of type data-type and returns the address of the object.

P = new int;

int *p = new int;

float *q = new float;

delete pointer-variable; like: delete p; delete q;

32

Page 33: c++ II unit

Type Cast OperatorC++ permits explicit type conversion of variables or

expressions using the type cast operator.

Type-name (expression)

Examples

average = sum/float(i);

A type-name behaves as if it is a function for converting values to a designated type. The function call notation usually leads to simplest expressions. But, it can be used only if the type is an identifier.

p = int * (q);

is illegal.

p = (int *)q; 33

Page 34: c++ II unit

34

We can use typedef to create an identifier of the required type and use it in the functional notation.

typedef int * int_pt;p= int_pt(q);

Page 35: c++ II unit

35

Basic Data TypeC++ Data Type

User Defined data Types

StructureClass

Enumeration

Derived Type

ArrayFunctionPointer

Built-in type

Integral type Void Floating type

doubleint char float

Page 36: c++ II unit

36

Page 37: c++ II unit

37

Modifying the Basic Types

Except for type void, the basic data types may have various modifiers preceding them.You use a modifier to alter the meaning of the base type to fit various situations more precisely. The list of modifiers is shown here:

Signed

Unsigned

Long

short

Page 38: c++ II unit

38

Derived Data TypeArray

An array is a collection of variables of the same type that are referred to through a common name. A specific element in an array is accessed by an index. In C/C++, all arrays consist of contiguous memory locations.

The lowest address corresponds to the first element and the highest address to the last element.

Arrays may have from one to several dimensions. The most common array is the null-terminated string, which is simply an array of characters terminated by a null.

Page 39: c++ II unit

39

PointerA pointer is a variable that holds a memory address. This address is the location of another object (typically another variable) in memory. For example, if one variable contains the address of another variable, the first variable is said to point to the second.

Page 40: c++ II unit

40

Pointer VariablesThe pointer declaration consists of a base type, an *, and the variable name. The general form for declaring a pointer variable is

type *name;

where type is the base type of the pointer and may be any valid type. The name of the pointer variable is specified by name.

The base type of the pointer defines what type of variables the pointer can point to.

Technically, any type of pointer can point anywhere in memory. However, all pointer arithmetic is done relative to its base type, so it is important to declare the pointer correctly.

Page 41: c++ II unit

41

FunctionFunction is defined as a procedure that returns a value.

The General Form of a Function is

ret-type function-name(parameter list)

{

body of the function

}

The ret-type specifies the type of data that the function returns. A function may return any type of data except an array. The parameter list is a comma-separated list of variable names and their associated types that receive the values of the arguments when the function is called. A function may be without parameters, in which case the parameter list is empty. However, even if there are no parameters, the parentheses are still required.

Page 42: c++ II unit

42

User defined data types• Structure

A structure contains a no. of data types grouped together. These data type may or may not be of the same type.

• General form of structurestruct<structure name>

{

structure element1;

structure element2;

.

.

};

struct book{char name;float price;int pages;};struct book b1,b1,b3;

Page 43: c++ II unit

43

• ClassA group of objects that share common properties and relationships. Iin C++ a class is a new data type that contains member variables and member functions that operate on the variables. A class is defined with the keyword class. Or we can say that Class is a collection of similar objects.

Class class_name{

Private:variable declarations;function declarations;

public:variable declarations;function declarations;

};

Page 44: c++ II unit

44

Compiler Directives

includeCompiler directiveProcessed at compilation timeInstructs compiler on what you want in the program

#include <iostream>Adds library files to programUsed with < >

Also “ ”user defined

Page 45: c++ II unit

45

Compiler Directives

Stream data typeObject that is a stream of charactersDefined in iostreamEntered on the keyboard (cin)Displayed on monitor (cout)

Page 46: c++ II unit

ExpressionsAn expression is a combination of operators, constants

and variables arranged as per rules of the language. It may also include function calls.

46

Page 47: c++ II unit

47

A C++ program //include headers; these are modules that include functions that you

may use in your //program; we will almost always need to include the header that// defines cin and cout; the header is called iostream.h#include <iostream.h>

int main() {//variable declaration//read values input from user//computation and print output to userreturn 0;}

After you write a C++ program you compile it; that is, you run a program called compiler that checks whether the program follows the C++ syntax – if it finds errors, it lists them – If there are no errors, it translates the C++ program into a program in machine

language which you can execute

Page 48: c++ II unit

48

Notes

• what follows after // on the same line is considered comment

• indentation is for the convenience of the reader; compiler ignores all spaces and new line ; the delimiter for the compiler is the semicolon

• all statements ended by semicolon

• Lower vs. upper case matters!! – Void is different than void– Main is different that main

Page 49: c++ II unit

49

Hello world program

When learning a new language, the first program people usually write is one that salutes the world :)

Here is the Hello world program in C++.

#include <iostream.h>int main() {

cout << “Hello world!”;

return 0;

}

Page 50: c++ II unit

50

If statements

if (condition) {

S1;

}

else {

S2;

}

S3;

condition

S1 S2

S3

True False

Page 51: c++ II unit

51

Boolean conditions..are built using

• Comparison operators

== equal

!= not equal

< less than

> greater than

<= less than or equal

>= greater than or equal

• Boolean operators

&& and

|| or

! not

Page 52: c++ II unit

52

Examples

Assume we declared the following variables:

int a = 2, b=5, c=10;

Here are some examples of boolean conditions we can use:

• if (a == b) …• if (a != b) …• if (a <= b+c) …• if(a <= b) && (b <= c) …• if !((a < b) && (b<c)) …

Page 53: c++ II unit

53

If example

#include <iostream.h>

void main() {int a,b,c;cin >> a >> b >> c;

if (a <=b) {cout << “min is “ << a << endl;}

else {cout << “ min is “ << b << endl;

}cout << “happy now?” << endl;}

Page 54: c++ II unit

54

While statements

while (condition) {

S1;

}

S2;

condition

S1

S2

True False

Page 55: c++ II unit

55

While example//read 100 numbers from the user and output their sum#include <iostream.h>

void main() {int i, sum, x;sum=0;i=1;while (i <= 100) {

cin >> x;sum = sum + x;i = i+1;

}cout << “sum is “ << sum << endl;}

Page 56: c++ II unit

56

C++ Comments A comment is text that the compiler ignores but that is useful for programmers. Comments are normally used to annotate code for future reference. The compiler treats them as white space. You can usecomments in testing to make certain lines of code inactive; however, #if/#endif preprocessor directives work better for this because you cansurround code that contains comments but you cannot nest comments.A C++ comment is written in one of the following ways: •The /* (slash, asterisk) characters, followed by any sequence ofCharacters (including new lines), followed by the */ characters. This syntax is the same as ANSI C.•The // (two slashes) characters, followed by any sequence of characters.A new line not immediately preceded by a backslash terminates this formof comment. Therefore, it is commonly called a "single-line comment."The comment characters (/*, */, and //) have no special meaningwithin a character constant, string literal, or comment. Comments usingthe first syntax, therefore, cannot be nested.