Sei sulla pagina 1di 86

Programming with C++ Enhanced Lecture Notes GC University Faisalabad. Resource Person: S. M. Alay-e-Abbas

1

Contents

INTRODUCTION:

3

How a Program is written in Turbo C++:

4

Structure of C++:

4

Preprocessor Directives:

4

Header File:

6

The main( ) Function:

6

C++ Statements:

6

Keywords and Tokens:

7

Variables:

7

Variable name:

7

Data Type in C++:

7

Declaration of Variables:

9

Constants:

9

Arithmetic operators:

10

Assignment Statement:

11

Order of precedence:

11

Cout object:

12

Cin object:

12

Escape Sequences:

13

Manipulators:

14

Increment Operator (++ ) :

17

Decrement Operator( - -):

17

Comment Statement:

18

Exercise:

19

Functions:

21

Built-in function:

21

Conio.h Console input output functions:

22

math.h Function:

23

complex.h Function:

27

Some other Function:

28

Conditional Statements:

32

The Nested if statement:

36

“if-else-if” statement:

37

Switch statement:

38

Conditional Operators:

39

Logical Operators:

39

“goto” control transfer statement:

41

Loops:

42

“while” Loop:

45

“do-while” Loop:

46

The Nested Loops:

48

The break and continue statements:

50

Programming with C++ Enhanced Lecture Notes GC University Faisalabad. Resource Person: S. M. Alay-e-Abbas

2

1-D array:

51

Multi-dimensional Arrays:

54

Pointers:

58

Reference operator ‘&’:

58

Dereference operator ‘*’:

59

Declaring variables of pointer type:

60

Pointers and arrays:

61

Pointer initialization

62

Pointer arithmetics

63

Pointers to functions

65

User Defined Functions:

67

The function declaration:

67

Calling the function:

68

Function definition:

68

Passing Arguments to a function:

69

Constants as argument:

70

Variables as argument:

71

Arrays as Arguments:

73

Returning values from function:

74

Overloaded function:

75

Inline Function:

77

(C programmers should note that inline functions largely take the place of #define macros in C.)

79

Local variables:

79

Global variables:

79

Static variables:

80

Local and Global Functions:

80

File System in C++:

80

Streams and files:

80

Opening files:

81

Testing file open operation:

82

Formatted input/output:

83

End-of-file:

85

Output to printer:

86

Programming with C++ Enhanced Lecture Notes GC University Faisalabad. Resource Person: S. M. Alay-e-Abbas

3

INTRODUCTION:

C++ program pronounced as “see plus plus” is an advanced version of C which was a

procedural or non object oriented language, while C++ is. Ken Thompson developed B

Language which was used to develop UNIX system B was developed at Bell Labs.

After B,C was developed at Bell Labs by Dannis Ritche which replaced B language in

1980`s. C was extended to C++ by Bjarne Stnoustuup .Which had improved quality and

was object-oriented .The C++ compilers available are Turbo C++ (ver 3.0 by Borlad)

works in MS-Dos environment whereas the Microsoft visual C++ compiler works in GUI

environment. We will use Turbo C++.

The executable file is located at

C:\TC\BIN\Tc.exe

In C drive, this will open the source code editor. The editor has following menu

File: It is used to Open, Quit, Save or produce new files for writing programs. To change

some directory of C++ where it is located. To print the program and to go back to Dos-

Prompt.

Edit: It contains undo, redo, copy, cut, paste, clear and show copied items

Search: To find or replaced words in the written program and locate errors or go to

specified lines

Run: To run a program, go to cursor position, etc.

Compile: All programs need to be compiled or collected together before running. The

built in checking system of the “software” compiles the source code which is written in

“English” to machine language. After making a program always compile it and then run

to avoid errors. Compile also links the written code to libraries and builds the object code

or machine code

Debug: It has options to inspect errors, faults in the code, not needed always because

compile can also detect errors in the source code

Project: Has options for projects, which are often used in Object-Oriented-programming.

Options: It has the preferences of the program also information on properties of libraries,

compilers, etc.

Windows: To change shape size and other options of the tc.exe window

Programming with C++ Enhanced Lecture Notes GC University Faisalabad. Resource Person: S. M. Alay-e-Abbas

4

Help: Provides help on all menu items we have discussed

How a Program is written in Turbo C++:

Source code that we write through keyboard in the editor is saved using (File Save )

in a file with extension CPP. It is a text file. The edition is used to write C++ source code.

After writing source code we compile it, it is translated into object code or machine code

which is in machine language (consisting of symbols rather than characters) and is stored

in file with extension .obj. This file is linked to libraries which contain info about the

functions or tokens used in the program. Afterwards an executable file with extension

.exe is created which is used to run or use the program. It is an MS-Dos command prompt

type environment which works on the basis of our source code or program.

which works on the basis of our source code or program. Schematic diagram of Program build
which works on the basis of our source code or program. Schematic diagram of Program build

Schematic diagram of Program build up in C++

Structure of C++:

Preprocessor Directives:

Programming with C++ Enhanced Lecture Notes GC University Faisalabad. Resource Person: S. M. Alay-e-Abbas

5

Instruction given to compiler before beginning a program are called preprocessor

directives also called compiler directives e.g. to include a file that contains info about

mathematical operations we write. SYNTAX

#include<header file name>

before the main function so that computer or the program knows how to calculate tan,

cos etc. of a given value

The preprocessor directives starts with a # sign and keywords include or define.

Ex:-

#include<iostream.h>

#include<conio.h>

main( )

{

 

cout <<”My First Program”; all statements end with “;”

getch( );

return 0;

}

Will give output when compiled and run

My First Program

The SYNTAX of define directive is

#define identifier value

e.g

#define pi 3.1417

Defines the value of identifier pi as 3.1417 that can be used in program where needed

Also the syntax can be

#define FNFH(X,Y)

Y*sin(X)

//

Which defines function FNFH of two variables X and Y as Y*sin(X). Using FNFH(2,1)

in a program will yield the result of 1*sin(2). There is also using identifier not supported

in Turbo C++.

Programming with C++ Enhanced Lecture Notes GC University Faisalabad. Resource Person: S. M. Alay-e-Abbas

6

Header File:

It is source file containing definition of library functions to be used in a program

The syntax to include header file is

#include<File Name>

where filename is iostrean.h, conio.h etc and is written inside angle brackets ‘< >’

The main( ) Function:

It indicates beginning of a program main( ) must be included in all programs .It is

followed by the program in curly brackets{}. The statements written in {} are called body

of the main function.

{ = start the mains body

} = ends the mains body

the SYNTAX is

main( )

{

program statements …….

}

C++ Statements:

These are written under the main( ) inside the curly brackets { }.These constitute the

body of the program each statement ends with a semicolon i.e. ;

Almost all statements are written in lower case

e.g.

main( )

{

statements come here

}

Programming with C++ Enhanced Lecture Notes GC University Faisalabad. Resource Person: S. M. Alay-e-Abbas

7

Keywords and Tokens:

Are used by C++ for special purposes and can not be used to give names to variables or

constants etc. e.g. cin, cout, return etc. tokens are , ; “ etc

Variables:

A quantity whose values may change during the execution of the program (actually it is

input during execution) is called a variable. It represents a storage location in memory of

computer and is reserved so that when needed it may be used e.g.

main( )

{

int a,b;

}

a and b are variables and are input during execution of program

Variable name:

first character must be alphabetic

underscore can be used first

blank space are not allowed

#,<,>,^ are not allowed in variables names

keywords not allowed

no two variables can have same name

Data Type in C++:

Data is the input is basically of 5 (5) types (note: float and double represent the same)

1-integer

int

3-double precision

double

2-floating

float

4-characters

char

Programming with C++ Enhanced Lecture Notes GC University Faisalabad. Resource Person: S. M. Alay-e-Abbas

8

5-boolean

bool

Int:

(requires 16 bits (2 bytes ) in memory )

It is integer type data with no decimal points

e.g 304,1,502,98

int can have value between -32768

Other classes are

32767

short int:

it is between -32768 to 32767

long int:

it is between-2147483648 to 2147483647

unsigned int:

it is between 0 to 65,535

Float:

(32 bits(4 bytes ) )

It is a real number like 0.56, 23.00 and 41.94

The range is between 3.4*10 -32 to 3.4*10 32

Long float:

It’s capacity in bytes stones double the data as of float.

Double:

(8 bytes )

It is used for very larg float values

Range 1.7*10 -308 to1.7*10 308

Long double:

Even larger 3.4*10 -4932 to 3.4*10 4932

(10 bytes(80 bits))

Char: ((8 bits ) 1 bytes )

Char stands for character type data it can store names, numeric or special characters.

Bool:

Stands for Boolean for logical type data true, false. Not available in the Turbo compiler.

Works only in visual C++.

Programming with C++ Enhanced Lecture Notes GC University Faisalabad. Resource Person: S. M. Alay-e-Abbas

9

Declaration of Variables:

Assigning name and type of variable in program is called declaration of variables

SYNTAX is

type list of variables;

declaration of variables SYNTAX is type list of variables ; variable type e.g. int, float etc.

variable type e.g. int, float etc.

Names of variables of same data type are separated by commas. e.g.

int

float xyz, temp, avg;

a, b;

A variable can also be given a value during declaration which is called initialing a

variable, example below declares, initializes and then prints the variable value on screen

Ex:

# include<iostneam.h>

# include<conio.h>

main( )

{

 

int abc=4, b=1997;

cout<< “Ali is in class” << abc<<endl;

cout<< “He was born in”<<b;

getch( );

}

Constants:

Constants types are

Ali is in class 4 He was born in 1997

1)

Integer constants: These can be positive or negative. e.g. cout<<254 and

cout<<-60

2)

Floating constants: these can be positive or negative. e.g. cout<<-5.9 and

cout<< 485.98e2.

Programming with C++ Enhanced Lecture Notes GC University Faisalabad. Resource Person: S. M. Alay-e-Abbas

10

4)

String constants or Literals: e.g. cout << “Pakistan”; etc

Constants can also be declared using const qualifier with SYNTAX

const type expression;

e.g. const float pi=3.1417;

Arithmetic operators:

To add, sub, etc numerical values following can be used in C++

+

add

*

multiply

% remainder

-

sub

/

devide

Ex:

#include<iostream.h>

#include<conio.h>

main( )

{

 

int a, b, p, s, m, r;

float d;

cout<< “Enter first value:”;

cin>> a;

cout<< “Enter second value:”;

cin>> b;

p = a + b; s = a - b; m = a * b; d = a / b; r = a % b; //remainder only for int data

cout<< “addition, subtraction, multiplication, division and remainder

are”<<p<<s<<m<<d “and”<<r << “respectively”;

getch( );

return 0;

}

addition, subtraction, multiplication, division and remainder are 7 3 10 2 and 1 respectively

Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas

11

Assignment Statement:

To input formulas or equations

SYNTAX is

Ex:

#include<lostream.h>

#include<conio.h>

var=expression;

void main( )

{

int a,b,c;

cin>>b>>c;

a=b*c;

is the assignment statement

cout<<a;

getch( );

}

Furthermore, the compound assignments are

a

and also

a = a + 2; is equivalent to a + = 2;

= b = 2+c;

2

4

8

Order of precedence:

The order or rule how arithmetic is done is called order of precedence one must use

correct order of precedence in an assignment statement for getting correct answers the

rules are

1.multiplications and divisions are done first

2.addition and subtraction afterwards

3.expression in parenthesis are evaluated first if used

4.compunted parenthesis starts evaluating from the inner most parenthesis

Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas

12

Cout object:

Stands for console output and is used to display or print the output of a program. Console

being the monitor

SYNTAX is

cout<<[const or var or statement];

Cout = output stream, object

<< = put to operator or insertion operation

cont or var or statement is the output

for multiple outputs of different type the example is

cout<< “one killo=”<<1000<< “grams”;

Ex:

#include<iostream.h>

#include<conio.h>

main( )

{

clrscr( );

cout<< “C++ is a powerful language”;

cout<<endl<< “OK”;

getch( );

return 0;

}

Cin object:

Stands for console input used to enter the data into the program

SYNTAX is

cin>> var or char;

cin = input stream, object

>> = get from or extraction operation

Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas

13

var or char is the input type

For multiple inputs example is: cin>>a>>b>>c;. Press enter after giving values of each Ex:

#include<iostream.h>

#include<conio.h>

void main()

{

clrscr();

int a, b;

cout<< “Enter two values \n”;

cin>> a >> b;

cout<< “\n Your entered values are a =”<<a<< “b=”<<b;

getch();

}

Escape Sequences:

\n

When used in output shifts the cursor to next line

e.g

cout<< “I \n am\n Pakistani”;

gives

I

am

Pakistani

\a

produces a beep in the computer speaker

Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas

14

\t

to give tabs between output

cout<< “A\t B \t C \t D”;

gives output as

A B

C

D

\”

to print double quotation mark

cout<<

“\“PAK”;

“PAK

some other escape sequences are:

\t

Horizontal Tab

\v

Vertical Tab

\b

Backspace

\f

Form feed

\\

Backslash

\?

Question mark

\'

Single quote

Manipulators:

There are numerous manipulators available in C++ we discuss a few important ones only.

end l:

To end line and print something in the next line

I am

The SYNTAX is endl

 

Pakistani

cout<<

“I am”<<end l<< “Pakistani”;

gives

setw(x):

This manipulator sets the minimum field width on output. The SYNTAX is:

setw(x)

Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas

15

Here setw causes the number or string that follows it to be printed within a field of x

characters wide and x is the argument set in setw(x) manipulator. The header file that

must be included while using setwmanipulator is <iomanip.h>

#include <iostream.h>

#include <iomanip.h>

void main( )

{

int x1=12345;

cout << setw(8) << ”Exforsys” << setw(20) << ”Values” << endl

<< setw(8) << “E1234567” << setw(20)<< x1 << endl;

}

The output is:

Exforsys Values

E1234567 12345

setfill(‘x’):

This is used after setw manipulator. If a value does not entirely fill a field, then

the character specified in the setfill(‘x’) argument of the manipulator is used for filling

the fields.

#include <iostream.h>

#include <iomanip.h>

void main( )

{

cout << setw(10) << setfill('$') << 50 << 33 << endl;

}

The output of the above program is

$$$$$$$$5033

setprecision(x):

The setprecision(x) Manipulator is used with floating point numbers. It is used to set the

number of digits printed to the right of the decimal point. Te following example explains

the use of setprecision manipulator.

Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas

16

#include <iostream.h>

#include <iomanip.h>

#include <conio.h>

void main( )

{

clrscr();

float x = 0.123456789;

cout<<x<<endl;

cout<<setiosflags(ios::fixed)<<setprecision(8)<<x << endl;

cout<<setiosflags(ios::scientific)<<setprecision(8)<<x << endl;

getch();

}

Output is:

0.123457

0.12345679

1.23456791 e-01

Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas

17

Increment Operator (++ ) :

It is used to add 1 to the value of an integer if used before a variable it is called prefix

increment and if after the variable it is called postfix increment

Ex:

Instead of using the assignment statement

xy =xy+1; o r xy+ = 1;

We may use

xy++;

or

++xy;

Ex:

when needed

#include<iostream.h>

#include<conio.h>

main( )

{

int a,b,c;sum;

a=1;

b=1;

c=3;

sum=a+b+( ++c);

cout<< “sum=”<<sum;

cout<< “c=”<<c;

getch( );

return 0;

}

for ++c

Sum = 6

c = 4

for c++

Sum = 5

c = 4

Decrement Operator( - -):

Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas

18

It is used to subtract 1 from the value of an integer if used before variable it is called

prefix decrement and if after then postfix decrement

Ex:

xy=xy-1

can be replace by

 

xy--;

or by

--xy;

Ex:

#include<conio.h>

#include<iostream.h>

main( )

{

int a, b, c, sum;

a=1;

b=1;

c=3;

sum=a+b+( --c);

cout<< “sum=”<<sum;

for --c

Sum=4

c=2

for c--

cout<< “c=”<<c;

Sum=5

getch( );

c=2

return 0;

}

Comment Statement:

For our references we can use the comment statement which is never executed

Syntax is

// [comments]

There’s a second comment style available in C++: /* this is an old-style comment */

Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas

19

Exercise:

#include<conio.h>

#include<iostream.h>

main( )

{

float c, f;

clrscr( );

cout<< “Enter temp in Fahrenheit”;

cin>>f;

c=(f-32)*5.0/9.0;

cout “Temp in Celsius=”<<c;

getch( );

return 0;

}

#include<conio.h>

#include<iostream.h>

main( )

{

float r, h, v

cluscn( );

cout<< “Enter Radius”;

cin>> r;

cout<< “Enter Height”;

cin>> h;

v=3.14*r*r*h

cout<< “Value of cylinder=”<<v;

getch( );

Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas

20

}

#include<iostream.h>

#include<conio.h>

main( )

{

int

cout<< “Enter Three Numbers”;

cin>>a>>b>>c;

avg=(a+b+c )/3

cout<< “Average is=”<<avg;

getch( );

return 0;

}

a, b, c, avg

Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas

21

Functions:

A function is a set of instructions that is designed to perform a specific task. In C++ there

are two basic types of functions

1. Built-in ( defined in the header files)

2. User defined

user defined is declared in C++ by declaring it separately inside the body of main( ) and

defining outside

Ex.

#include<iostream.h>

#include<conio.h>

main( )

{

int kg,gm;

int grams(int );

clrscr( );

cout<< “Enter value of Kg”;

cin>>kg;

gm=gram( kg);

cout<< “Answer is”<<gm;

getch( );

}

Int grams(int val )

“Answer is”<<gm; getch( ); } Int grams(int val ) function declared assigning gm to function. Function

function declared

getch( ); } Int grams(int val ) function declared assigning gm to function. Function calling Function

assigning gm to function. Function calling

function declared assigning gm to function. Function calling Function definition { return val*1000; } The function

Function definition

{

return val*1000;

}

The function already declared catches the value of the output and returns it using formula

val*1000. Where val is the output of the program under body of the main( )

Built-in function:

Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas

22

Are accessed through the header files each function is defined in its header file, so to use

a function we must include its header file in the program

Conio.h Console input output functions:

“clrscr()” function:

function stands for clear screen it is used to clear something already written on the screen

of the computer its syntax is

clrscr()

“goto()” function:

function positions the cursor on the screen at location (x,y ) syntax is

gotoxy( x,y)

where

x=0 to 79 i.e 80 columns of the screen

y=0 to 24 i.e 25 rows in screen

“getch()” function:

it is usually used to pause the program un till a key on the keyboard is pressed. The

pressed key is not displayed where paused and the control goes to the next statement

syntax is

getch( )

“getche()” function:

is the same but key pressed is shown on the screen

syntax is

getche( )

Ex:

#include<iostream.h>

#include<conio.h>

Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas

23

main( )

{

cout<<”To clear Screen Press Any Key”; getch( );

clrscr( ); cout<<”To End Program Press Any Key”; getch( ); return 0;

}

math.h Function:

Used for mathematical calculations defined in the math.h

“pow(x,y)” function:

used to calculate the power of a given integer

syntax is

e.g .

pow(x,y )

pow(2, 3)

means 2 3

“sqrt(x)” function:

used to calculate square root of a number

syntax is

e.g.

sqrt(x )

sqrt(9.0)

means9=3

“floor(x)” function:

To round off the real number to its largest integer its value is smaller than the real

number

syntax is

Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas

24

e.g.

floor(x )

floor(9.6 )

means 9

floor(-9.6)

means -10

“ceil(x)” function:

to round off real number to its greatest integer,greater than its actual value

syntax is

e.g.

ceil(x)

ceil(9.6 );

means 10

ceil(-9.6 );

means -9

“cos(x)” function:

to calculate cosine of a single value

syntax is

e.g

cos(0.0)

cos(x )

=1

“sin(x)” function:

to calculate sine of a single value

syntax is

e.g

sin(0.0)

sin(x )

=0

“tan(x)” function:

to calculate tangent of a single value

syntax is

Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas

25

e.g

tan(0.0)

tan(x )

=0

“log(x)” function:

to calculate natural logrithem of a single value

syntax is

e.g

log(0.0)

log(x )

=1

log10(x)” function:

to calculate log of a single value with base 10

syntax is

log10(x )

e.g

log10(0.0)

=1

“acos(x), asin(x) and atan(x)’

Prototype: double acos(double a_cos);

Explanation: Acos is used to find the arccosine of a number (give it a cosine value and it

will return the angle, in radians corresponding to that value). It must be passed an

argument between -1 and 1.

//Example gives the angle corresponding to cosine .5

#include <iostream.h>

#include <math.h>

int main()

{

cout<<acos(.5);

Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas

26

return 0;

}

“abs(x) and fabs(x)”

Prototype: int abs(int aNum); float fabs(float aVlue);

Explanation: The abs function returns the absolute value of a number integer (makes it

positive).

Example:

//Program asks for user input of an integer

//It will convert it to positive if it was negative

#include <math.h>

#include <iostream.h>

int main()

{

int aNum;

cout<<"Enter a positive or negative integer";

cin>>aNum;

cout<<abs(aNum);

return 0;

}

“exp(x)”

returns the exponential of a variable or constant.

“cosh(x), sinh(x) and tanh(x)”

Prototype: double cosh (double a);

Explanation: Returns the hyperbolic cosine of a.

//Example prints the hyperbolic cosine of .5

#include <math.h>

#include <iostream.h>

int main()

{

Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas

27

cout<<cosh(.5);

return 0;

}

“fmod()”

Prototype: double fmod(double numone, double numtwo);

Explanation: This function is the same as the modulus operator. It returns the remainder

of the division numone/numtwo. I include it to avoid it being confused with modf, a

previous function of the day.

//Example will output remainder of 12/5 (2)

#include <math.h>

#include <iostream.h>

int main()

{

cout<<"The remainder of 12/5: "<<fmod(12/5);

return 0;

}

complex.h Function:

The example explains the use of complex numbers in C++:

#include <stdlib.h>

#include <iostream.h>

#include <conio.h>

#include <complex.h>

main()

{

complex xx; //declares a complex number xx

complex yy = complex(1,2.718); //declares yy and assigns a complex value 1+ i

2.718 to yy

Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas

28

xx = (yy); //assigns the value of yy to xx

cout << complex(1,1)+xx; //adds 1 to real and imaginary parts of xx and prints

getch();

return 0;

}

Initializes yy as a complex number of the form (real+imag*i), evaluates the expressions

and prints the result: (0.96476,1.21825).

This facility for complex arithmetic provides the arithmetic operators +, /, , and , the

assignment operators =, +=, =, =, and /=, and the comparison operators == and != for

complex numbers.

Expressions such as(xx+1) log(yy log(3.2)) that involve a mixture of real and complex

numbers are handled correctly. The simplest complex operations, for example + and +=,

are implemented without function call overhead. Input and output can be done using the

operators >> (get from) and << (put to). The initialization functions and >> accept a

Cartesian representation of a complex.

The functions real() and imag() return the real and imaginary part of a complex,

respectively, and << prints a complex as (real, imaginary).

Polar coordinates can also be used. The function polar(double mag, double

angle) creates a complex given its polar representation, and abs(xx) and arg(xx) return

the polar magnitude and angle, respectively, of a complex. The

function norm(xx) returns the square of the magnitude of a complex. The following

complex functions are also provided: sqrt(), exp(), log(), sin(), cos(), sinh(), cosh(),

pow(), and conj(). No complex type is defined for float or long double types.

complex type is defined for float or long double types. Some other Function: “delay(x)” delays the

Some other Function:

“delay(x)”

delays the output by c mili seconds. Available in dos.h

“clock()”

Prototype: clock_t clock(void);

Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas

29

Header File: time.h

Explanation: This function returns the number of clock ticks (the CPU time taken) the

program has taken. To convert to the number of seconds, divide by CLOCKS_PER_SEC,

which is defined in time.h

//Example will run a loop, and then print the number of clock ticks and

//number of seconds used

#include <time.h>

#include <iostream.h>

int main()

{

for(int x=0; x<1000; x++)

cout<<endl;

cout<<"Clock ticks: "<<clock()<<" Seconds: "<<clock()/CLOCKS_PER_SEC;

return 0;

}

“exit(x)”

Prototype: void exit(int ExitCode);

Header File: stdlib.h and process.h

Explanation: Exit ends the program. The ExitCode is returned to the operating system,

similar to returning a value to int main.

//Program exits itself

//Note that the example would terminate anyway

#include <stdlib.h>

#include <iostream.h>

int main()

{

cout<<"Program will exit";

exit(0) //Return 0 is not needed, this takes its place

}

Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas

30

“rand()”

Prototype: void rand(void);

Header File: stdlib.h

Explanation: rand generates random numbers.

#include <stdlib.h>

#include <iostream.h>

int main()

{

int d=rand()%1000; //Should be between 0 and 1000

cout<<d;

return 0;

}

“srand()”

Prototype: void srand(unsigned int seed);

Header File: stdlib.h

Explanation: Srand will seed the random number generator to prevent random numbers

from being the same every time the program is executed and to allow more

pseudorandomness.

//Program uses time function to seed random number generator

//and then generates random number

#include <stdlib.h>

#include <time.h>

#include <iostream.h>

int main()

{

srand((unsigned)time(NULL)); //Casts time's return to unsigned

int d=rand()%12; //Should be more random now

cout<<d;

Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas

31

}

”time()”

Prototype: time_t time(time_t* timer);

Header File: time.h

ANSI: C and C++

Explanation: Returns and sets the passed in variable to the number of seconds that have

passed since 00:00:00 GMT January 1, 1970. If NULL is passed in, it will work as if it

accepted nothing and return the same value.

Example:

//Program will use time_t to store number of seconds since 00:00:00 GMT Jan.

//1, 1970

#include <time.h>

#include <iostream.h>

int main()

{

time_t hold_time;

hold_time=time(NULL);

cout<<"The number of elapsed seconds since Jan. 1, 1970 is "<<hold_time;

return 0;

}

}

Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas

32

Conditional Statements:

The statements of a program are executed one after another, this is called sequential

execution. To change or alter the sequence of execution we can use conditional

statements which execute or neglect the statements coming after a statement depending

upon the results of their condition .for doing this we need to test a relation .The relational

expression usually contains two variables or constants to be compared and a relational

operator e.g < , > if we require that the next statement executes after testing this

condition and finding it true and said will happen otherwise if the execution is not

performed. The relational operator in C++ are <, >=, <= , > , = = and !=

The “if” statement:

It is used to execute or ignore a single statement or a set of statements after testing a

condition. It evaluates a condition if condition is true the statement in the body of “if” is

executed if not the control shifts to the next statement ignoring statements after the “if”

its SYNTAX is

if (condition)

here ; is not required

statement1;

statement2;

the condition is tested only for statement1 not for statement2 to execute a set of

statements after testing a condition the set is enclosed in the curly brackets i.e. {} called

body of “if”.

its SYNTAX is

if (condition)

{

set of conditions;

}

statement-n;

(from 1 to m)

in above 1 to m statements are executed if “if” condition is satisfied otherwise only the

nth statement is executed

Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas

33

Flow Chart

condition false true
condition
false
true

Set of statements

Set of statements
33 Flow Chart condition false true Set of statements Statement after if Ex: #include<iostream.h>
33 Flow Chart condition false true Set of statements Statement after if Ex: #include<iostream.h>

Statement after if

Ex:

#include<iostream.h>

#include<conio.h>

main( )

{

int a,b;

cout<< “enter values of a and b”;

cin>>a>>b;

if(a>b)

cout<< “a is greater”<<endl;

if(b>a)

cout<< “b is greater”<<endl;

cout<< “ok” ;

getch( );

return 0;

}

enter values of a and b

5

2

a

is greater

ok

enter values of a and b

2

5

b

is greater

ok

Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas

34

Ex: Quadratic equation

#include<iostream.h>

#include<conio.h>

main( )

{

float a, b, c, r1, r2, disc, real, imag;

cout<< “enter value of a, b and c”<<endl;

cin>>a>>b>>c;

disc=b*b-4.0*a*c;

if(disc<0 )

{

real=-b/(2.0*a );

imag=sqrt(-disc ) / (2.0*a );

cout<< “roots are imagenry”<<endl;

cout<< “root1=”<<real<< “+i”<<imag<<endl;

cout<< “root2=”<<real<< “-i”<<imag<<endl;

}

if(disc==0 )

{

r1=r2=-b/(2.0*a );

cout << “roots are real and equal”<<endl;

cout<< “root1=”<<r1<<endl;

cout<< ”root2=”<<r2<<endl;

}

if(disc>0 )

{

r1=-b/(2.0*a)+sqrt(disc)/ (2.0)*a

r2=-b/(2.0*a)-sqrt(disc)/ (2.0)*a

cout<< “roots are real and different”<<endl;

cout<< “root1=”<<r1<<endl;

Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas

35

cout<< “root2=”<<r2<<endl;

}

getch ( );

}

The “if else” statement:

To make two way decision i.e when condition is true control will execute the statement of

if structure if not the statement of else will be executed

SYNTAX is

if(condition)

statement1;

else

statement2;

for set of statements

if(condition)

{

set of If’s statements

}

else

{

set of else’s statements

}

Flow Chart if condition else false true Block 2 Block 1 Statement after if-else
Flow Chart
if
condition
else
false
true
Block 2
Block 1
Statement after if-else

Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas

36

Ex:

#include<iostream.h>

#include<conio.h>

main( )

{

int n;

cout<< “enter an integer”;

cin>>n;

if(n>100)

cout<< “number is greater than 100”;

else

cout<< “number if is less than 100”;

getch( );

}

The Nested if statement:

When an if statement is used inside another if statement it is called a nested if statement it

is used for multiple conditions

SYNTAX

if (condition-1)

{

if(condition-2)

{

statement-1;

}

statement-2;

}

Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas

37

if first condition is satisfied and second not statement-1 is not executed it is only executed

if both conditions are satisfied 1 and 2 are both executed. If neither is satisfied non is

executed

Flow Chart

if Condition-1 False True if Condition-2 False True
if
Condition-1
False
True
if
Condition-2
False
True
if Condition-1 False True if Condition-2 False True Statement-3 Statement-2 Next statement “if-else-if”

Statement-3

False True if Condition-2 False True Statement-3 Statement-2 Next statement “if-else-if” statement: If

Statement-2

True if Condition-2 False True Statement-3 Statement-2 Next statement “if-else-if” statement: If and if-else

Next statement

False True Statement-3 Statement-2 Next statement “if-else-if” statement: If and if-else structure is

“if-else-if” statement:

If and if-else structure is placed in another if-else structure we get a nested if-else

structure

SYNTAX is

if (condition-1)

statement-1;

else if (condition-2)

statement-2;

……

……

Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas

38

else

statement-n;

Flow Chart true Condition-1 Block 1 false true Condition-2 Block 2 false Next statement
Flow Chart
true
Condition-1
Block 1
false
true
Condition-2
Block 2
false
Next statement

Switch statement:

It is an alternate of the if-lese-if statement and is used because the if-else-if statements

becomes complex. It has one variable or expression whose values are compared with

different cases for selection as shown in the SYNTAX below

Switch (expression / variable) //value returned as used for selection

{

case const-1: //may be numeric or character

state-1;

break; // if const-1 is selected the next statements will not execute

case const-2:

state-2;

break;

dafault: //if not match is selected this is run

state-3;

}

it has the same flow chart as that of the if-else-if statement

Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas

39

Conditional Operators:

It is an alternate of if-else structure. SYNTAX is

(condition)?exp-1:exp2;

examples explain its usage

int a = 5, b = 10. res;

res = (a>b)?a:b;

cout<< res;

will give output

10

Logical Operators:

These are used to combine relational expressions on conditions. It is a compound

condition There are three operators

1. && AND operator. all conditions must be satisfied for the execution

2. || OR operator. One or more must be satisfied for the execution

3. ! NOT operator. The results of condition is inverted

Ex.

#include<iostream.h>

#include<conio.h>

main( )

{

int a, b, c;

cin>> a>>b>>c;

if( (a>b) &&(a>c) )

cout<< “a is largest”;

elseif ( (b>a) &&(b>c) )

cout<< “b is largest”;

else

Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas

40

cout<< “c is largest”;

getch( );

return 0;

}

Ex.

#include<iostream.h>

#include<conio.h>

main( )

{

int c, b;

cin>> a>>b;

if( (a>100) ||(b>100) )

cout<< “one or more values are greater than 100”;

else

cout<< “no value is greater than 100”;

getch( );

}

Ex.

#include<iostream.h>

#include<conio.h>

main( )

{

int a,b;

cout<< “enter two values”;

cin>>a>>b;

if(!(a>b))

cout<< “2 nd value is largest”;

else

cout<< “1 st value is larges”;

getch( );

Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas

41

return 0;

}

“goto” control transfer statement:

it is used to transfer the control during execution. Usually used when you enter a wrong

value and need to rerun the program. The program is rerun from the point where there is a

flag or label to which the goto statement points as shown in the example below.

SYNTAX is

goto abc;

where

abc is label

Ex.

#include<iostream.h>

#include<conio.h>

void main( )

{

int a;

again: //this is the label. It has same naming rules as that of a variable

cout<< “enter a value”; cin>>a;

if(a>100)

cout<< “Ok…

end of program”;

else

{

cout<< “worng entry. Enter value again less than 100”;

getch();

goto again;

}

getch( );

}

Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas

42

Loops:

A statement on a set of statements that is executed repeatedly is called a loop. The

statements under a loop are executed for a specified number of times until some given

condition remain true

In C++ there are three kind of loops

1. for loop

2. while loop

3. do-while loop

“for” loop:

It is used to execute a set of statements for a fixed number of times it is also called counts

loop

SYNTAX is

for(initialization; condition; increment or decrement)

In initialization an initial value is assigned to the variable being used in condition

e.g.

for(a=6;a<10;a++)

The variable may be declared here or earlier under main( ) if the variable has already

being declared and initialized then we may write

for( ;a<10;a++)

The condition part carries a condition which returns true or false depending upon the

results of condition. Increment or decrement is used to increase or decrease the value of

variable to make a true condition false during execution of the statement for specific

period.

The statement or set of statements dependent on “for” are written inside the body of for

loop

e.g.

Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas

43

for(a=6;a<10;a++)

{

cout<<a<<endl;

}

note: this example executed 4 times

6

 

7

8

9

Flow Chart

executed 4 times 6   7 8 9 Flow Chart Initialized variable false condition true Body
Initialized variable

Initialized variable

false condition true
false
condition
true

Body of loop

Body of loop
9 Flow Chart Initialized variable false condition true Body of loop Statements after for body Increment
9 Flow Chart Initialized variable false condition true Body of loop Statements after for body Increment

Statements after for body

Increment decrement
Increment decrement

Increment decrement

9 Flow Chart Initialized variable false condition true Body of loop Statements after for body Increment

Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas

44

Ex. To print table

#include<iostream.h> #include<conio.h> main( )

{

int table, c, r; clrscr ( );

cout<< “enter a number”; cin>>table; for( c=1;c<=10;c++)

{

r=table*c; cout<<table<< “x”<<c<< “=”<<r<<endl;

}

getch( );

return 0;

}

Ex. Factorial

#include<iostream.h>

#include<conio.h>

main( )

{

int n; long int fact; clscr ( );

cout << “enter any number”; cin>>n;

fact=1;

for( ;n>=1;n--)

[ note that n has already been declared through the input]

{

fact=fact*n

}

cout <<“the factorial of is”<<fact; getch( ); return 0;

}

4

the factorial of 4 is 24

Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas

45

“while” Loop:

It is conditional loop statement used to execute a statement or set as long as a condition is

true

SYNTAX is

while( condition)

{

…….

}

Body of While

The computer evaluates the condition of while if it is true the body of while is executed

otherwise it is not. The body must always contain a statement that can make the condition

false otherwise the loop will become infinite

Ex:

#include<iostream.h>

main( )

GCUF

GCUF

GCUF

GCUF

GCUF

End…….OK

{

int c;

c=1;

while(c<=5 )

{ Flow Chart cout<< “GCUF”; c=c+1; condition } False cout<< “End……OK”; True getch( );
{
Flow Chart
cout<< “GCUF”;
c=c+1;
condition
}
False
cout<< “End……OK”;
True
getch( );
Body of loop
return 0;
}
Statement
after while

Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas

46

Ex. Program for series 1+1/2+1/3+1/4+……. #include<iostream.h>

#include<conio.h>

main( )

{

float s, c;

clrscr ( );

s=0.0;

c=1.0

while( c<=45)

{

s=s+1.0/c

c++;

}

cout<< “sum of series is=”<<s;

getch( );

return 0;

}

“do-while” Loop:

It is also a conditional loop in which condition is tested after the body of the loop has

been executed. So a loop that returns false in first execution of while and the body is not

executed will be executed once using do-while

SYNTAX is

do

{

statements;

}

while (condition)

Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas

47

Ex:

#include<iostream.h>

#include<conio.h>

main( )

{

int n;

n=1;

do

{

cout<< n<<endl;

c++;

}

while( n<=10)

cout<<endl<<”OK”

getch( );

return 0;

}

1 2 3 4 5 6 7 8 9 10 OK
1
2
3
4
5
6
7
8
9
10
OK

Flow Chart

Body of loop true condition false Statement after do-while
Body of loop
true
condition
false
Statement after do-while

Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas

48

Ex: Convert decimal num to binary num #include<iostream.h>

#include<conio.h>

main( )

{

int n, r;

clrscr( );

 

10

cout<< “enter some integer”;

0

cin>>n;

1

0

do

1

{

r=n%2;

n=n/2;

cout<<r<<endl

}

while(n>=1);

cout<<endl<< “ok”;

getch( );

return 0;

}

The Nested Loops:

A loop structure completely inside another loop is called nested loop

Ex: Using nested while loop print the following matrix on screen

1 2

3

4

5

1 3

5

7

9

1 4

7

10

13

Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas

49

#include<iostream.h>

#include<conio.h>

main( )

{

int u, i, n;

u=1;

while( u<=3)

{

i=1

n=1

while(i<=5 )

{

cout<<n<< “\t”;

n=n+u;

i=i+1;

}

cout<<endl;

u=u+1

1 2

3

4

5

1 3

5

7

9

1 4

7

10

13

}

getch( );

return 0;

}

Ex. Using nested for loop print on screen

1

1

2

1

2

3

1

2

3

4

1

2

3

4

5

Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas

50

#include<iostream.h>

#include<conio.h>

main( )

{

int u, i;

for (u=1;u<=5;u++ )

{

for( i=1;i<=u;i++)

{

cout<<i<< “\t”;

cout<<endl;

}

}

getch( );

return 0;

}

The break and continue statements:

The break statement causes an exit from a loop, just as it does from a switch statement.

The next statement after the break is executed is the statement following the loop.

The break statement takes you out of the bottom of a loop. Sometimes, however, you

want to go back to the top of the loop when something unexpected happens. Executing

continue has this effect. (Strictly speaking, the continue takes you to the closing brace of

the loop body, from which you may jump back to the top.)

Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas

51

Arrays:

Arrays is a sequence of objects of same data type. The objects are also called the

elements of the arrays. An array is the set of consecutive storage locations each

referenced by a name and its position. Position is referenced by index, for n elements the

index values are 0,1,2,3…

for the last element. And element when entered or retrieved is accessed by its index value

in C++, index value is written inside [] brackets. Arrays are used to process large amount

of data of same type

,n-1

where 0 is the index value of the first element and n-1 is

Location

Value

Storage

value of the first element and n-1 is Location Value Storage 2 1 4 1 5
2 1 4 1 5 3 2
2 1 4 1 5 3 2

2

1

4

1

5

3

2

Location Value Storage 2 1 4 1 5 3 2 1-D array: Row vector matrix Also
Location Value Storage 2 1 4 1 5 3 2 1-D array: Row vector matrix Also

1-D array:

Row vector matrix

Also known as list or linear arrays consist of 1 column or row, for example to declare the

temperature of 24 hours during a day we need to define the temperature data set, its type

and also the locations of temperature w.r.t time so that memory locations are reserved in

the computer for the said collection of data. The general SYNTAX for declaring 1-D

array is

type array name[n]

For example temperature of 24 hours in decimal form we may write

double temp[24]

Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas

52

Ex: How to access and retrieve data

#include<iostream.h>

#include<conio.h>

main( )

{

float a[5];

int i;

a[0]=9.9

a[1]=12.9

a[2]=13.1

a[3]=8.9

a[4]=10.6

for(i=0;i<=4;i++ )

{

cout<< “value in a[“ <<i<<“]=”<<a[i]<<endl;

}

getch( );

return 0;

}

Ex. To input and print the same data in reverse

#include<iostream.h>

#include<conio.h>

main( )

{

int abc[5], i;

for( i=0;i<=4;i++)

{

cout<< “Enter value in a[“<<i<<”]=”<<endl;

cin>>abc[i];

}

Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas

53

cout<< “output in reverse is”<<endl;

for( i=4;i<=0;i--)

{

cout<< “value ina[“<<i<<”]=”<<abc[i]<<endl;

}

getch( );

return 0;

}

Ex. Averaging array elements

#include <iostream.h>

#include<conio.h>

void main()

{

const int SIZE = 6; //size of array

double sales[SIZE]; //array of 6 variables

cout << “Enter sales for 6 days\n”;

for(int j=0; j<SIZE; j++) //put figures in array

cin >> sales[j];

double total = 0; for(j=0; j<SIZE; j++) //read figures from array total += sales[j]; //to find total double average = total / SIZE; // find average cout << “Average = “ << average << endl; return 0;

}

Ex. Initializing Arrays

#include <iostream.h>

#include<conio.h>

void main()

{

int month, day, total_days;

Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas

54

int days_per_month[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

cout << “\nEnter month (1 to 12): “; //get date

cin >> month;

cout << “Enter day (1 to 31): “;

cin >> day;

total_days = day; //separate days

for(int j=0; j<month-1; j++) //add days each month

total_days += days_per_month[j];

cout << “Total days from start of year is: “ << total_days

<< endl;

return 0;

}

Multi-dimensional Arrays:

In array of more than one array is called multi-dimensional array. Also known as table or

matrix. The index value for 2-D array are two, one represents the row number and other

the column number, for example a 2-D array temp with seven rows and three columns is

represented by temp[7][3] whose first element is temp[0][0] and last is temp[6][2]

the declaration SYNTAX for a 2-D array is

Where r= # of rows

c= # of columns

type name [r][c]

e.g. an array of integer values with 12 rows and 3 columns will be represented by

int abc[12][3];

where total # of elements is given by 12x3=36. The 1 st index value for row is 0 and last is

11, similarly 1 st index value for column is 0 and last is 2.

To enter or retrieve data of an array the elements are referenced by their index value

usually nested loops are used to access or retrieve elements of 2-D array. Examples

Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas

55

illustrate a 2-D array whose values are entered and then retrieved in tabular form on the

screen

Ex: Input data into array and output the same

#include<iostream.h> #include<conio.h> main( )

{

int abc[2][3], r, c; cout<< “Input data into table”<<endl;

r=0;

while(r<=1 )

{

c=0;

while( c<=0)

{

cout<< “enter value in row =”<<r<<”column=””<<c;

cin>>abc[r][c];

c=c+1;

}

r=r+1;

}

cout<< “printing table”<<endl;

r=0;

while( r<=1)

{

c=0;

while( c<=2)

{

cout<<abc[r][c]<< “\t’;

c=c+1;

}

cout<<endl;

Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas

56

r=r+1;

getch ( ); return 0;

}

Ex: Entering values in table and printing maximum values

#include<iostream.h>

#include<conio.h>

main( )

{

int r, c, m, aa[5][4];

clscr( );

for( c=0;c<4;c++)

for( r=0;r<4;r++)

{

cout<< “Enter value in [“<<c<<”, “<<r<<”]=”;

cin>>aa[r][c];

}

m=aa[0][0];

for(c=0;c<4;c++ )

for( r=0;r<4;r++)

{

if( m<aa[r][c])

m==aa[r][c]

}

cout<< “max value =”<<m;

cout<<endl<< “ok”<<endl;

getch( );

return 0;

}

Ex: Initializing 2-D Array

Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas

57

#include<iostream.h>

#include<conio.h>

const int DISTRICTS = 4; //array dimensions

const int MONTHS = 3;

int main()

{

int d, m;

//initialize array elements

double sales[DISTRICTS][MONTHS];

= { { 1432.07, 234.50, 654.01 },

{ 322.00, 13838.32, 17589.88 },

{ 9328.34, 934.00, 4492.30 },

{ 12838.29, 2332.63, 32.93 } };

cout << “\n\n”;

cout << “ Month\n”;

cout << “ 1 2 3”;

for(d=0; d<DISTRICTS; d++)

{

cout <<”\nDistrict “ << d+1;

for(m=0; m<MONTHS; m++)

cout << setw(10) << setiosflags(ios::fixed)

<< setiosflags(ios::showpoint) << setprecision(2)

<< sales[d][m]; //access array element

}

cout << endl;

return 0;

}

Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas

58

Pointers:

The memory of your computer can be imagined as a succession of memory cells, each

one of the minimal size that computers manage (one byte). These single-byte memory

cells are numbered in a consecutive way, so as, within any block of memory, every cell

has the same number as the previous one plus one. Thus, each cell can be easily located

in the memory because it has a unique address and all the memory cells follow a

successive pattern.

Reference operator ‘&’:

The address that locates a variable within memory is what we call a reference to that

variable. This reference to a variable can be obtained by preceding the identifier of a

variable with an ampersand sign (&), known as reference operator, and which can be

literally translated as "address of". For example:

int andy, ted;

ted = &andy;

This would assign to add the address of variable value.

andy = 25;

fred = andy;

ted = &andy;

The values contained in each variable after the execution of this, are shown in the

following diagram:

ted = &andy; The values contained in each variable afte r the execution of this, are

Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas

59

First, we have assigned the value 25 to andy (a variable whose address in memory we

have assumed to be 1776). The second statement copied to fred the content of variable

andy (which is 25). Finally, the third statement copies to ted not the value contained in

andy but a reference to it (i.e., its address, which we have assumed to be 1776).

The variable that stores the reference to another variable (like ted in the previous

example) is what we call a pointer. Pointers are a very powerful feature of the C++

language that has many uses in advanced programming.

Dereference operator ‘*’:

Using a pointer we can directly access the value stored in the variable that it points to. To

do this, we simply have to precede the pointer's identifier with an asterisk (*), which acts

as dereference operator (offset operator) and that can be literally translated to "value

pointed

Therefore, following with the values of the previous example, if we write:

beth = *ted;

by".

("beth equal to value pointed by ted") beth would take the value 25, since ted is 1776, and

the value pointed by 1776 is 25.

25, since ted is 1776, and the value pointed by 1776 is 25. The expression ted

The expression ted refers to the value 1776, while *ted (with an asterisk * preceding the

identifier) refers to the value stored at address 1776, which in this case is 25.

Notice the difference between the reference and dereference operators:

& is the reference operator and can be read as "address of"

Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas

60

* is the dereference operator and can be read as "value pointed by"

Declaring variables of pointer type:

Due to the ability of a pointer to directly refer to the value that it points to, it becomes

necessary to specify in its declaration which data type a pointer is going to point to. It is

not the same thing to point to a char as to point to an int or a float.

Declaration of pointers follows this SYNTAX:

type* name;

where type is the data type of the value that the pointer is intended to point to. This type

is not the type of the pointer itself! but the type of the data the pointer points to. For

example:

int * number;

char * character;

float * greatnumber;

The asterisk sign (*) that we use when declaring a pointer only means that it is a pointer,

and should not be confused with the dereference operator.

Ex: Initializing 2-D Array

#include <iostream.h>

#include <conio.h>

int main ()

{

int firstvalue, secondvalue;

int* mypointer;

mypointer = &firstvalue; //mypointer points to firstvalue

*mypointer = 10; //firstvalue equals the value pointed by mypointer

cout << "firstvalue is " << firstvalue << endl;

return 0;

}

Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas

61

Pointers and arrays:

The identifier of an array is equivalent to the address of its first element, as a pointer is

equivalent to the address of the first element that it points to, so in fact they are the same

concept. For example:

int numbers [20];

int * p;

The following assignment operation would be valid:

p = numbers;

After that, p and numbers would be equivalent and would have the same properties. The

only difference is that we could change the value of pointer p by another one, whereas

numbers will always point to the first of the 20 elements of type int with which it was

defined. Therefore, unlike p, which is an ordinary pointer, numbers is an array, and an

array can be considered a constant pointer. Therefore, the following allocation would not

be valid:

numbers = p;

Because numbers is an array, so it operates as a constant pointer, and we cannot assign

values to constants. Due to the characteristics of variables, all expressions that include

pointers in the following example are perfectly valid:

Ex: various ways of assigning values to arrays using pointers

#include <iostream.h>

#include <conio.h>

int main ()

{

clrscr();

int numbers[5];

int * p;

p = numbers;

*p = 10;

p++;

Programming with C++ Enhanced Lecture Notes GC university Faisalabad. By: S. M. Alay-e-Abbas

62

*p = 20;

p = numbers + 3;

*p = 30;

p = &numbers[3];

*p = 40;

p = numbers;

*(p+4) = 50;

for (int n=0; n<5; n++)

cout << numbers[n] << ", ";

getch();

return 0;

}