Array
Consecutive group of memory locations
Same name and type (int, char, etc.)
To refer to an element
Specify array name and position number
(index)
Format: arrayname[ position number ]
First element at position 0
N-element array c
c[ 0 ], c[ 1 ] c[ n - 1 ]
Arrays
Array elements like other variables
Assignment, printing for an integer array c
c[ 0 ] = 3;
cout << c[ 0 ];
X[0]
X[1]
int x[50];
int y[50];
x=y; //not valid
for (int i=0; i<50; i++)
x[i]=y[i];
if (x= = y) //not valid
cout << x; // valid but gives the address of first element
x=x+y; //not valid
return x; //not valid
Declaring Arrays
When declaring arrays, specify
Name
Type of array
Any data type
Number of elements
type arrayName[ arraySize ];
int c[ 10 ]; // array of 10 integers
float d[ 3284 ]; // array of 3284 floats
Initializing arrays
For loop
Set each element
Initializer list
Specify each element when array declared
int n[ 5 ] = { 1, 2, 3, 4, 5 };
If not enough initializers, rightmost elements 0
If too many syntax error
Initialization
Global and static arrays are automatically initialized
to default values, i.e., pattern of 0's in all bits.
Arrays declared in local scope are not automatically
initialized
Initialization is possible at the time of declaration
as: int idata[5]={1, -1, 4, 2, -3};
The number of initialization data within { } should
not be greater than the declared size of array.
Initializing arrays
Array initialization
int main ()
{
double a[4] = (22.2, 44.4, 66.6, 88.8);
for (int i = 0; i < 4; i++)
cout << a[i] << endl;
}
a[0] = 2 2 . 2
a[1] = 4 4 . 4
a[21 = 6 6 . 6
a[3] = 8 8 . 8
int main()
{
double a[4] = (22.2, 44.4);
for (int i = 0; i < 4; i++)
cout << a[i] << endl;
}
Output:
a[0] = 2 2 . 2
a[1] = 4 4 . 4
a[21 = 0.0
a[3] = 0.0
Int main()
const int size = 4;
double a[size];
cout << "Enter<< size<< real numbers:\n";
for (int i = 1; i <= size; i++) {
cout<< i ;
cin >> a[i-1];
cout << "Here they are in reverse order:\n";
for (i = size-l; i >= 0; i--)
cout << i << a[i] << endl;
#include <iostream>
#include <iomanip>
int main()
} // end main
Element
Value
0
0
0
0
0
0
0
0
0
0
#include <iostream>
#include <iomanip>
int main()
int n[ 10 ] = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 };
} // end main
Output:
Element
Value
32
27
64
18
95
14
90
70
60
37
#include <iostream>
#include <iomanip>
int main()
{
// constant variable can be used to specify array size
const int arraySize = 10;
int s[ arraySize ]; // array s has 10 elements
for ( int i = 0; i < arraySize; i++ ) // set the values
s[ i ] = 2 + 2 * i;
cout << "Element" << setw( 13 ) << "Value" << endl;
} // end main
Element
0
1
2
3
4
5
6
7
8
9
Value
2
4
6
8
10
12
14
16
18
20
#include <iostream>
int main()
int a[ arraySize ] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int total = 0;
total += a[ i ];
cout << "Total of array element values is " << total << endl;
} // end main
Strings
Arrays of characters
All strings end with null ('\0')
Examples
char string1[] = "hello";
Null character implicitly added
string1 has 6 elements
} // end main
If not static
Created (and destroyed) in every function call
we apply static to a local array declaration so the array is not
created and destroyed each time the program calls the function,
and the array is not destroyed each time the function terminates the
program.
Arrays passed-by-reference
Functions can modify original array data
Value of name of array is address of first element
Function knows where the array is stored
Can change original memory locations
Individual array elements passed-by-value
Like regular variables
square( myArray[3] );
Function prototype
void modifyArray( int b[], int arraySize );
int main()
{
const int arraySize = 5;
// size of array a
int a[ arraySize ] = { 0, 1, 2, 3, 4 }; // initialize a
{
// multiply each array element by 2
for ( int k = 0; k < sizeOfArray; k++ )
b[ k ] *= 2;
{
// multiply parameter by 2
cout << "Value in modifyElement is "
<< ( e *= 2 ) << endl;
Sorting array
Sorting data
Important computing application
Virtually every organization must sort some
data
Massive amounts must be sorted
Example:
Go left to right, and exchange elements as
necessary
One pass for each element
Original: 3 4 2 7 6
Pass 1:
3 2 4 6 7 (elements exchanged)
Pass 2:
2 3 4 6 7
Pass 3:
2 3 4 6 7 (no changes needed)
Pass 4:
2 3 4 6 7
Pass 5:
2 3 4 6 7
Small elements "bubble" to the top (like 2 in this
example)
Swapping variables
int x = 3, y = 4;
y = x;
x = y;
What happened?
y = 4, temp = 0;
// temp gets 3
// x gets 4
// y gets 3
using std::setw;
int main()
{
const int arraySize = 10; // size of array a
int a[ arraySize ] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 };
int hold; // temporary location used to swap array elements
// bubble sort
// loop to control number of passes
for ( int pass = 0; pass < arraySize - 1; pass++ )
Unbound array
In some programming languages, an index variable will
not be allowed to go beyond the bounds set by the arrays
definition.
Row 0
Column 0
a[ 0 ][ 0 ]
Column 1
a[ 0 ][ 1 ]
Column 2
a[ 0 ][ 2 ]
Column 3
a[ 0 ][ 3 ]
Row 1
a[ 1 ][ 0 ]
a[ 1 ][ 1 ]
a[ 1 ][ 2 ]
a[ 1 ][ 3 ]
Row 2
a[ 2 ][ 0 ]
a[ 2 ][ 1 ]
a[ 2 ][ 2 ]
a[ 2 ][ 3 ]
Multiple-Subscripted Arrays
To initialize
Default of 0
Initializers grouped by row in braces
int b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 }
};
Row 0
Row 1
Or Int b[2][2]={1,2,3,4};
1
int b[ 2 ][ 2 ] = { { 1 }, { 3, 4 } };
Multiple-Subscripted Arrays
Referenced like normal
cout << b[ 0 ][ 1 ];
Outputs 0
Cannot reference using commas
cout << b[ 0, 1 ];
Syntax error
Function prototypes
Must specify sizes of subscripts
First subscript not necessary, as with singlescripted arrays
Sum of rows:
Example: int x[52][7]
Sum of 3rd row:
for (int i=0; i<7; i++)
Sum+=x[2][i];
Pointers
When we say a certain variable is pointer.
What does it mean?
A pointer is a variable which holds the memory
address of another variable.
Pointer notation:
consider
int i=3;
This declaration tells the compiler
Reserve space in memory to hold the integer value.
Associate the name i with this memory location
Store the value 3 at this location.
Location name
i
3
6485
Value at location
Location number
}
Output:
Address of i=6485
& is used in the statement is a address operator.
Pointer operator:
A pointer operator is represented by a combination of
* (asterisk) with a variable.
If a variable of integer data type and also declared
*(asterisk) with another variable, it means the variable is
of type pointer to integer. It will be used in the program
indirectly to access the value of one or more integer
variables.
Example: int *ptr
Where ptr is a pointer variable which holds the address of an
integer data type.
All pointer variables must be declared before it is used in
the program like other variable.
Address operator:
An address operator is represented by a combination of &
(ampersand) with a pointer variable.
If a pointer variable is an integer type and also declared &
with the pointer variable, then it means that the variable
is of type address of.
The & is a unary operator that returns the memory address
of its operand.
Example:
m=&ptr
The above statements means that m receives the address
of ptr.
ptr
3
6485
m
6485
3276
int *m
It stands for value at address i.e. 3.
Pointer expression:
A pointer is a variable data type and hence the general rule
to assign its value to the pointer is same as that of any
other variable data type.
Example: int x, y
int *ptr1, *ptr2
ptr1=&x; //the memory address of x is assigned to ptr1
y=*ptr1; //the contents of the pointer variable ptr1 is
assigned to variable y.
ptr1=ptr2 //the address of ptr1 is assigned to ptr2.
1.
int x;
int x_pointer; //declaration must have the prefix of *.
x_pointer =&x;
2. float y;
float *y_pointer;
y_pointer =y //the address operator have to use with y.
3. int x;
char *c_pointer;
c_pointer = &x; //mixed type is not permitted
Pointer arithmetic
As a pointer holds the memory address of a variable,
arithmetic operators can be used with pointers eg. +, -,
++, --.
Pointers are variables. They are not integers . But can be
displayed as unsigned integers.
Ptr++ causes the pointer to be incremented but not by 1.
Ptr-- causes the pointer to be decremented but not by 1.
Example:
Int value, *ptr;
Value=120
Ptr=&value; //let the value is 2000
Ptr++;
Cout <<ptr <<endl;
The program will display 2002.
{
*nPtr = *nPtr * *nPtr * *nPtr; // cube *nPtr
const qualifier
Value of variable should not be modified
const used when function does not need to
change a variable
int * p;
++(*P);
++p;
int * const cp;
++ (*cp) ;
++cp;
const int * pc;
.++ (*pc) ;
++pc;
const int * const cpc;
++(*cpc);
++cpc;
// a pointer to an int
// ok: increments int *p
// ok: increments pointer p
// a constant pointer to an int
// ok: increments int *cp
// illegal: pointer cp is
constant
// a pointer to a constant int
// illegal: int *pc is constant
// ok: increments pointer pc
// a constant pointer to a
constant int
// illegal: int *cpc is constant
// illegal: pointer cpc is
constant
int main()
{
int num[]={24,34,12,44,56,17};
int i, *j
j=&num[0]; //assign address of zeroth element
for (i=0; i<=5; i++)
{
cout <<address=<<j<<endl;
cout <<element=<<*j<<endl;
j++; //increment pointer to point to next location
}
}
Output:
Address=4001 element=24
Address=4003 element=34
Address=4005 element=12
Address=4007 element=44
Address=4009 element=56
Address=4011 element=17
int num[]={24,34,12,44,56,17}
*num refer to the zeroth element of the array, i.e. 24
Similarly *(num+1) refer to first element of the array, i.e 34.
Following notation are same:
num[i]
*(num+i)
*(i+num)
i[num]
Accessing array element in different ways:
int main()
{
int num[]={24,34,12,44,56,17};
int i
int s[4][2]={
{1234, 56}
{1212, 33}
{1434, 80}
{1312, 78}
}
int i;
for (i=0; i<=3, i++)
Output:
Address of 0 th 1-D
Address of 1 th 1-D
Address of 2 th 1-D
Address of 3 th 1-D
array=5002
array=5006
array=5010
array=5014
Int I, j;
for {i=0; i<=3; i++)
{
for (j=0; j<=1; j++)
cout << *(*(s+i)+j))<<endl;
}
}
Output:
1234 56
1212 33
1434 80
1312 78
Array of pointers
There can be array of pointers similar to array of ints or
array of floats.
Since a pointer variable always contains an address, an
array of pointers is a collection of addresses.
Example:
int main ()
{
int *arr[4]; //array of integer pointers
int i=31, j=5, k=19, l=71, m;
arr[0]=&i;
arr[1]=&j;
arr[2]=&k;
arr[3]=&l;
int i, flag, a;
char yourname [10];
cout <<enter your name<<endl;
cin >>yourname;
flag=NOTFOUND
for (i=0; i<=5; i++)
{
a=strcmp (&masterlist[i][0], yourname)
if (a==0)
{
cout <<welcome <<endl;
flag=FOUND;
break;
}
}
if (flag==NOTFOUND)
cout <<sorry, you are not allowed<<endl;
}
Output:
Enter your name dinesh
Sorry, you are not allowed
Enter your name raman
Welcome
The first subscript gives the number of names in the array,
while the second subscript gives the length of each item
in the array.
int I;
char t;
cout <<original:<<&name[2][0]<<&name[3][0]<<endl;
For (i=0; i<=9; i++)
{
t=names[2][i];
names[2][i]=names[3][i];
names[3][i]=t;
}
cout <<new:<<&names[2][0]<<&names[3][0]<<endl;
}
Output:
Original: raman srinivas
New: srinivas raman
To exchange the names we are required 10 exchange corresponding
characters of the two names.
char *names[]={
akshay;
parag;
raman;
srinivas;
gopal;
rajesh;
};
char *temp;
cout <<Original: <<names [2]<<names[3]<<endl;
temp=names[2];
names[2]=names[3];
names[3]=temp;
cout <<New:<<names[2]<<names[3]<<endl;
}
Output:
Original: raman srinivas
New: srinivas raman
POINTERS TO POINTERS
Pointers to function
Every type of variable, with the exception register, has an
address.
We have seen how we can reference variables of type
char, int , float etc through their address.
Pointer can also point to functions like array as the
functions address we can point to it, which provides
another way to invoke it.
Example: //To get address of a function
int main ()
{
int display()
cout <<address of function display is = <<display<<endl;
display();
}
display()
{
cout <<welcome to pointer<<endl;
}
Output the program is
Address of the function display is 1125
Welcome to pointer
func_ptr=display;
So the func_ptr is being assigned the address of display()
Therefore, func_ptr must be a pointer to the function
display().
int (*func_ptr)();
The above declaration means that func_ptr is a pointer to
a function, which returns an int.
And to invoke the function we required to write the
statement,
(*func_ptr)();
References
A reference is an alias, a synonym for another variable. It is
declared by using the reference operator & appended to
the references type.
Example:
int main ()
int n = 33;
int& r = n; // r is a reference for n
cout << "n = << n << r = << r << endl;
- -n
cout << "n =<< n << r = << r << endl;
r *= 2;
cout<< n = << n << "r = << r << endl;
Output:
n=33 r=33
n=32 r=32
n=64 r=64
The two identifiers n and r are different names for the
same variable: they always have the same value.
Decrementing n changes both n and r to 32. Doubling r
increases both n and r to 64.
Output:
&n = 0x3fffdl4 &r = 0x3fffdl4
new operator
Delete operator
The delete operator reverses the action of the new
operator, returning allocated memory to the free store.
It should only be applied to pointers that have been
allocated explicitly by the new operator:
float* q = new float(3.14159);
delete q; // deallocates q
*q = 2.71828;
// Error: q has been deallocated
Deallocating q returns the block of sizeof ( float ) bytes to
the free store, making it available for allocation to other
objects.
Example :
A program to create a dynamic memory allocation for the
standard data types: integer, floating point, character and
double.
The pointer variables are initialized with some data and
the contents of the pointer are display on the screen.
//Using new and delete operators
#include <iostream>
int main ()
{
int *ptr_i=new int (25);
float *ptr_f=new float (-10.1234);
char *ptr_c=new char (a);
double *ptr_d= new double(1243.57);
Dynamic array
An array name is really just a constant pointer that is
allocated at compile time:
float a[20]; // a is a const pointer to a block of 20 floats
float* const p = new float[20]; // so is p
Here, both a and p are constant pointers to blocks of 20
floats.
The declaration of a is called static binding because it is
allocated at compile time; the symbol is bound to the
allocated memory even if the array is never used while
the program is running.
In contrast, we can use a non-constant pointer to
postpone the allocation of memory until the program is
running. This is generally called run-time binding or
dynamic binding:
float* p = new float[20];
An array that is declared this way is called a dynamic
array.
Structure
Sometimes some logically related elements need to be
treated under one unit e.g. the elements storing a students
information (roll_no, name, class, marks, grade) needs to
be processed under one roof.
A structure is a collection of variables referenced under one
name.
Collection of one or more variables, possibly of different
types, under a single name for convenient handling.
Heterogeneous mixture of various data types
Each component has a name and is called a member
Member list is like a series of variable declarations
struct declaration is a type declaration for the whole
collection
Structures
In general, a struct declaration looks like
struct <type name>
{
<Member list>;
} <variable list>;
The variables declared in variable list are of type <type
name>
Members of a struct can be struct themselves leading to
hierarchical structures.
Same member name can occur in different structs
Example:
#include <iostream>
int main ()
{
struct sample {
int x;
float y;
};
struct sample a;
a.x=10;
a.y=20.2;
cout << content of x= <<a.x <<endl;
cout << content of y= <<a.y <<endl;
Output:
Content of x=10;
Content of y=20.2
Nested structure
An element of a structure may even be an array or a structure itself.
A structure can be nested inside another structure.
Struct addr
//structure tag
{ int houseno;
char area[26];
char city[26];
char state[26];
};
struct emp
//structure tag
{ int empno;
char name[26];
char desig [16];
addr address;
float basic;
};
emp worker;
//create structure variable
Nested structure
The structure emp has been defined having several
elements including a structure address also.
The element address (of structure emp) is itself a structure
of type addr.
While defining such structure, the inner structure should be
defined before outer structure.
Accessing nested structure members:
The member of structure are accessed using dot operator.
To access the city member of address structure which is an
element of another structure worker,
We will write: worker.address.city
To initialize houseno member of address structure, element of
worker structure:
worker.address.houseno=889
#include <iostream>
#include <stdio.h>
Struct addr
//Global definition
{ int houseno;
char area[26];
char city[26];
char state[26];
};
struct emp
{ int empno;
char name[26];
char desig [16];
addr address; //another structure
float basic;
};
emp worker;
//create structure variable
int main ()
{
cout <<\n <<enter employee no <<endl;
cin >> worker.empno>>endl;
cout <<\n <<name<<endl;
gets (worker.name); //to read white spaces also as >> cant read
cout << \n <<Designation<<endl;
gets (worker.desig);
cout <<\n <<enter address <<endl;
cout <<house no <<endl;
cin >> worker.address.houseno >>endl;
cout << worker basic<<endl;
cin >> worker.basic;
return 0;
}
To initialize a nested structure at the time of declaration, as follows:
Emp worker={1085, sandeep, manager, {777, Tnagar, delhi,
delhi, 9800};
Arrays of structures
An array is a group of identical data which are stored in a common
heading. A similar type of structure placed in a common heading or a
common variable name is called arrays of structures.
e.g. To process the students particulars for the entire school
struct school {
int rollno;
int age;
char sex;
float height;
float weight;
};
school student [300];
The student is a structure variable. It may accommodate the structure of
300 student.
example:
#include <iostream>
#define MAX 3
Int main ()
{
struct school {
long int rollno;
int age;
char sex;
float height;
float weight;
};
scool student [MAX]= {
{ 95001, 24, M, 167.9, 57.6 },
{ 95002, 25, F, 156.9, 45 },
{ 95003, 27, M, 187.9, 78}
};
for (int i=0; i<=MAX-1; ++i) {
Content of structure =1
Rollno=95001
Age=24
Sex=M
Height =187.9
Weight= 78
Content of structure=2
Rollno=95002
Age=25
Sex=F
Height = 156.9
Weight= 45
Content of structure =3
Rollno=95003
Age=27
Sex=M
Height = 156.9
Weight= 45
Example:
struct book
{
char name [25];
char author [25];
int callno;
};
int main()
{
struct book b1={let us c++, YPK, 101};
display (b1);
}
display (struct book b)
{
cout << b.name<<b.author<<b.callno<<endl;
}
Out put:
Let us c++ YPK 101
Structure pointers
The way we can have a pointer to an int, or a pointer
pointing to a char, similarly we can have a pointer
pointing to a struct. A pointer can be used to hold the
address of a structure variable.
Example:
struct sample {
int x;
float y;
char s;
};
struct sample *ptr;
Where ptr is a pointer variable holding the address of the
structure sample and is having three members such as
int x, float y and char s.
int x;
int y;
};
sample *ptr;
sample one;
ptr=&one;
(*ptr).x=10;
(*ptr).y=20;
cout << contents of x= <<(*ptr).x <<endl;
cout << contents of y= <<(*ptr).y <<endl;
}
Output:
Contents of x=10
Contents of y=20
//Method 2:
#include <iostream>
int main()
{
struct sample {
int x;
int y;
};
sample one;
sample *ptr;
ptr=&one;
ptr->=10;
ptr->y=20;
cout <<contents of x= <<ptr->x<<endl;
cout <<contents of y= <<ptr->y<<endl;
}
Output:
Contents of x=10
Contents of y=20
int x;
int y;
};
sample *ptr;
cout <<enter value for x and y \n;
cin >>ptr->x>>ptr->y;
cout << contents of x= <<ptr->x <<endl;
cout << contents of y= <<ptr->y<<endl;
}
struct sample {
int *ptr1;
float *ptr2;
};
sample *first;
int value1;
float value2;
value1=10;
value2=-20.02;
first ->ptr1=&value1;
first -> ptr2=&value2;
cout << contents of the first number= ;
cout << *first->ptr1<<endl;
cout <<contents of the second number= ;
cout <<*first->ptr2<<endl;
}
Output:
Contents of the first number=10
Contents of the second number=-20.02
int *ptr1;
float *ptr2;
};
sample *first;
int value1;
float value2;
-----
----- (*first).ptr1=&value1;
(*first).ptr2=&value2;
----- }
Unions
Union like structure a data type with a difference in the way
the data is stored and retrieved.
The union stores values of different types in a single
location.
The declaration and usage of union is same as structures.
Union holds only one value for one data type. If a new
assignment is made, the previous value is automatically
erased.
The symbolic representation of a union declaration is:
Union user_defined_name{
member 1;
member 2;
----
member n;
};
union sample {
int first;
float second;
char third;
} one, two;
Where one, two are the union variables name similar to
data size of the sample.
union value {
int ch;
double dd;
};
union value x;
Similar to structures, the dot (.) operator is used to access a unions
individual field.
x.ch;
x.dd;
typedef
The typedef is used to define new data items
that are equivalent to the existing data types.
Once a user defined data is declared, then
new variables, arrays, structures and so on
can be declared in terms of this new data
types.
The general format of the user defined data
types:
typedef dataype newtype.
integer i,j;
real a,b;
The typedef is used in a program to make it
readable and portable.
Example:
#include <iostream>
int main ()
{
typedef int integer;
typedef float real;
typedef char character;
integer i,j;
character ch;
real a,b;
i=10;
j=30;
ch=m
a=-23.45;
b=34.89;
cout <<using typedef <<endl;
cout <<i= <<i <<\t;
cout <<j= <<j <<endl;
cout <<ch= <<ch <<endl;
cout <<a= << a<<\t;
cout <<b= <<b <<endl;
}
Output:
Using typedef
i=10 j=30
ch=m
a=-23.45 b=34.89