Académique Documents
Professionnel Documents
Culture Documents
value at a time.
We want to find the average value of a village having
population of 500.
Solution 1 : Construct 500 variables to store the age
of the persons.
Solution 2 : Construct a single variable capable of
storing or holding all the 500 values.
It is easier to handle one variable than handling 500
variables.
Introduction
This single variable capable of storing or holding all
Introduction
Array Declaration :
int marks[5];
Type of variables : Integer
Dimension : 5
marks : Name of the variable
[ ] : Indication of an array
Each member in the array is referred to by its position.
Position is from 0 to 4.
for(i = 0;i<5;i++)
{
printf(Enter the marks :);
scanf(%d, &marks[i]);
}
for(i = 0;i<5;i++)
sum = sum + marks[i];
average = sum/5;
Array Initialization
Array Initialization :
int marks[5] = {32,45,56,67,78}
int marks[ ] = {32,45,56,67,78}
Array elements are always stored in contiguous
locations.
marks[0]marks[1]marks[2]marks[3]marks[4]
32
45
2004
2006
56
2008
67
78
2010
2012
Bound Checking
In C there is no check to see if the subscript used for
reference.
In call by value, we pass the values of array elements
to the function.
In call by reference, we pass the address of array
elements to the function.
Call by Value
main()
{
int i, marks[5] = {32,45,56,67,78}
for(i = 0;i<5;i++)
findsum(marks[i]);
}
findsum(int m)
{
static int sum;
sum = sum + m;
printf(Sum = %d, sum);
}
Call by Reference
main()
{
int i, marks[5] = {32,45,56,67,78}
for(i = 0;i<5;i++)
findsum(&marks[i]);
}
findsum(int *m)
{
static int sum;
sum = sum + *m;
printf(Sum = %d, sum);
}
Pointer
main()
{
int i = 3,*x;
x = &i;
//consider the address of i is 2004
printf(\n Content of x: %u, x);
x++;
printf(\n Content of x: %u, x);
x--;
printf(\n Content of x: %u, x);
}
A Pointer when incremented, points to an immediately
next location of its type.
int i = 3,*x;
x= &i;
//consider the address of i is 2004
x = x + 2;
Subtraction of a number to a pointer.
int i = 3,*x;
x= &i;
//consider the address of i is 2004
x = x - 2;
Contd
Subtraction of one pointer from another
One pointer variable can be subtracted from another
provided both point to the elements of the same array.
Resulting value indicate the number of values stored
between those two pointers.
int marks[5] = {32,45,56,67,78}
int *i,*j;
i = &marks[1];
j = &marks[4];
printf(%d, j i);
Contd
Comparison of two pointer variables
Pointer variables can be compared provided both
variables point to objects of the same data type.
int marks[5] = {32,45,56,67,78}
int *i,*j;
i = &marks[1];
j = &marks[4];
j = j 3;
if(i = = j)
printf(Both point to the same location.);
Operations on Pointer
which are NOT possible
Addition of two pointers
Multiplication of a pointer with a constant
Division of a pointer with a constant
Contd
*marks
*(marks + 0)
*(0 + marks)
marks[0]
0[marks]
All will give the value of the first element of array.
Thank You