Module-4 Arrays and Pointers
Module-4 Arrays and Pointers
#include<stdio.h>
void main()
{
int number1;
int number2;
int number3;
int number4;
int number5;
number1 = 10;
number2 = 20;
number3 = 30;
number4 = 40;
number5 = 50;
printf( "number1: %d \n", number1);
printf( "number2: %d \n", number2);
printf( "number3: %d \n", number3);
printf( "number4: %d \n", number4);
printf( "number5: %d ", number5);
}
It was simple, because we had to store just 5 integer numbers. Now let's assume we have to
store 5000 integer numbers, so what is next???
Types of array
Single Dimensional Array :- An Array which has only one subscript is known as Single
dimensional array or One dimensional array
The individual array elements are processed by using a common array name with different
index values that start with Zero and ends with array_size-1
data_type array_name[array_size];
where
array_size : an integer constant indicating the maximum number of data elements to be stored.
Array Representation
Here
and so on..
Example:
int b[4]={10,12,14,16};
Here each value will be stored in respective index values of the array.
i.e in location b[0] we store the value 10, in location b[1] we store the value 12 and so on…
Suppose if we try to insert more values then the size of the array it will give us an error “Excess
elements in array initializer”
Example:
int b[4]={10,12,14,16,18};
Here the size of the array b is 4 but we are trying to store 5 values hence we will be getting the
error in this case.
2. Initialization of array elements one by one:- Here the user has the liberty to select the
locations and store values and the array. This type of initialization is not used much practically
Example
int b[4];
b[0]= 10;
b[2]=14;
Only the array locations specified by the user will contain the values which the user wants the
other locations of array will either be 0 or some garbage value.
3. Partial initialization of array :- If the number of values initialized in the array is less than
the size of the array then it is called partial initialization. The remaining locations in the array
will be initialized to zero or NULL(‘\0’) value automatically
Example:
int b[4]={10,12};
4. Array initialization without specifying the size :- Here the size or the array is not specified
by the user, the compiler will decide the size based on the number of values declared in the
array.
Example:
int b[ ]={6,12,18};
Here the size of the array is specified and the compiler will set the array size as 3 for this
example
5. Run Time array Initialization:- If the values are not known by the programmer in advance
then the user makes use of run time initialization. It helps the programmer to read unknown
values from the end users of the program from keyboard by using input function scanf().
Here we make use of a looping construct to read the input values from the keyboard and store
them sequentially in the array.
Example: /* C program to demonstrate run time initialization*/
#include<stdio.h>
void main()
{
int b[5],i;
printf(“Enter 5 elements\n”);
for(i=0;i<5;i++)
{
scanf(“%d”,&b[i]);
}
}
We can access the elements of array using index or subscript of element. An index gives the
portion of element in the array .To access an array element make use of array_name[index]
To access value 16 we write b[2]=16 similarly if we wish to print the value 18 we write
printf(“%d”,b[3]);
#include<stdio.h>
void main()
{
int a[20 ],n,i;
printf(“Enter the array size”);
scanf(“%d”,&n);
Printf(“Enter the array elements\n”);
for(i=0;i<n;i++)
{
scanf(“%d”,&a[i]);
}
printf(“The elements entered in the array are\n”);
for(i=0;i<n;i++)
{
printf(“%d\t”,a[i]);
}
}
#include<stdio.h>
void main()
{
int a[20 ],n,i;
printf(“Enter the number of elements\n”);
scanf(“%d”,&n);
printf(“The first %d natural numbers are:\n”,n);
for(i=0;i<n;i++)
{
a[i]=i+1;
printf("a[%d]=%d\n",i,a[i]);
}
}
include<stdio.h>
void main()
{
int a[20 ],b[20],c[20],n, i;
printf(“Enter the number of elements\n”);
scanf(“%d”,&n);
printf(“Enter the elements of Array A\n”);
for(i=0;i<n;i++)
scanf(“%d”,&a[i]);
printf(“Enter the elements of Array B\n”);
for(i=0;i<n;i++)
scanf(“%d”,&b[i]);
printf(“Array Addition\n”);
for(i=0;i<n;i++)
c[i]=a[i]+b[i];
printf(“The resultant array is \n”);
for(i=0;i<n;i++)
printf(“%d\n”,c[i]);
}
4. Write C program to find largest and smallest number in an array of n elements
include<stdio.h>
void main()
{
int a[10 ],n,i,max,min
printf(“Enter the number of elements\n”);
scanf(“%d”,&n);
printf(“Enter the values \n”);
for(i=0;i<n;i++)
scanf(“%d”,&a[i]);
max=min=a[0];
for(i=0;i<n;i++)
{
if(a[i]>max)
max=a[i];
if(a[i]<min)
min=a[i];
}
printf(“Largest number=%d\n”,max);
printf(“Smallest number=%d\n”,min);
}
5. Write a C program to read n integer elements in an array and print the same in
reverse order.
#include<stdio.h>
void main()
{
int a[20 ],n,i;
printf(“Enter the array size”);
scanf(“%d”,&n);
Printf(“Enter the array elements\n”);
for(i=0;i<n;i++)
scanf(“%d”,&a[i]);
printf(“The elements entered in the array are\n”);
for(i=0;i<n;i++)
printf(“%d\t”,a[i]);
printf(“The elements of the array in reverse order are\n”);
for(i=n-1;i>=0;i--)
printf(“%d\t”,a[i]);
}
6. Write a C Program to find the sum of odd, even, all and average of n numbers using
arrays
#include<stdio.h>
void main()
{
int a[20 ],sum=0,esum=0,osum=0,n,i;
float avg;
printf(“Enter the array size”);
scanf(“%d”,&n);
printf(“Enter the array elements\n”);
for(i=0;i<n;i++)
{
scanf(“%d”,&a[i]);
}
for(i=0;i<n;i++)
{
sum=sum+a[i];
if((a[i]%2)==0)
esum=esum+a[i];
else
osum=osum+a[i];
}
avg=sum/n;
printf(“The sum of all numbers is %d”,sum);
printf(“The sum of even numbers is %d”,esum);
printf(“The sum of odd numbers is %d”,osum);
printf(“The average of all numbers is %f”,avg);
}
#include<stdio.h>
#include<conio.h>
void main()
{
int fib[20],n,i;
printf(“Enter the no. of Fibonacci series to be generated\n”);
scanf("%d",&n);
fib[0]=0;
fib[1]=1;
if(n==1)
printf(“fibonacci series is %d”,fib[0]);
else if(n==2)
printf(“fibonacci series is %d \t %d”,fib[0],fib[1]);
else
for(i=2;i<n;i++)
{
fib[i]=fib[i-1]+fib[i-2];
}
printf(“The fibonacci series are :\n");
for(i=0;i<n;i++)
{
printf("%d\t",fib[i]);
}
}
Sorting Techniques:-
The Process of arranging the elements in ascending or descending order is called sorting
Bubble sort: The sorting algorithm is a comparison based algorithm in which each pair of
adjacent elements is compared and the elements are swapped if they are not in order. This
algorithm is not suitable for large datasets as its average and worst case time complexity are of
O(n2). where n is the number of items.
#include<stdio.h>
void main()
{
int a[50],n,i,j,temp;
printf("Enter the number of elements\n");
scanf("%d",&n);
printf("Enter %d elements\n",n);
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("The entered elements are\n");
for(i=0;i<n;i++)
{
printf("%d\t",a[i]);
}
printf("\n***** SORTING ******\n");
for(i=1;i<n;i++)
{
for(j=0;j<n-i;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
printf("The sorted elements are\n");
for(i=0;i<n;i++)
{
printf("%d\t",a[i]);
}
}
/*C program to sort numbers in ascending order using selection sort technique*/
#include<stdio.h>
void main()
{
int a[20],n,i,j,temp;
printf("Enter total elements\n");
scanf("%d",&n);
printf("Enter %d elements\n",n);
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
printf("The sorted elements are\n");
for(i=0;i<n;i++)
{
printf("%d\t",a[i]);
}
}
Searching Techniques:
The process of finding a particular element in the large amount of data is called searching.
Linear search:- A Linear search is also called as sequential Search. In this technique we search
for a given specific element called as key element in the large list of data in sequential order. If
the key element is present in the list of data then the search is successful otherwise search is
unsuccessful.
Benefits:
• Simple approach
• Works well for small arrays
• Used to search when the elements are not sorted
Disadvantages:
#include<stdio.h>
void main()
{
int a[100],n,i,key,flag=0;
printf("Enter the no of elements\n");
scanf("%d",&n);
printf("Enter %d elements ",n);
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("Enter the element to be searched\n" );
scanf("%d",&key);
for(i=0;i<n;i++)
{
if(key==a[i])
{
flag=1;
break;
}
}
if(flag= =1)
printf("Element found at position %d\n", i+1);
else
printf("Element not found\n");
}
Binary Search: It is fast search algorithm which works on the principle of divide and conquer.
for this algorithm to work properly the data collection should be in the sorted form
– middle element
2. If the middle element is the correct value, done. Otherwise, go to step 1. using only the
half of the array that may contain the correct value.
3. Continue steps 1. and 2. until either the value is found or there are no more elements to
examine
Advantages:
Disadvantages:
#include<stdio.h>
void main()
{
int a[100],n,i,low,high,mid,key,flag=0;
printf("Enter the size of the array\n");
scanf("%d",&n);
printf("Enter %d elements in ascending order\n",n);
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("Enter the element to be searched\n" );
scanf("%d",&key);
low=0;
high=n-1;
while(low<=high)
{
mid=(low+high)/2;
if(key==a[mid])
{
flag=1;
break;
}
else
if(key>a[mid])
low=mid+1;
else
high=mid-1;
}
if(flag= =1)
Syntax:
data_type array_name[size1][size2];
where,
data_type: is the type of data to be stored and processed in the computer’s memory
Example:
int a[2][3];
Represents a is a two dimensional integer array that holds two rows and three columns.
1)Initializing all elements row wise:- A multidimensional array can be initialized by specifying
bracketed values for each row.
Example:
int[2][3]={{5,3,4} {6,1,2}} ;
The feasible way of accessing elements in a two dimensional array is by using nested loops.
Reading and printing 2 dimensional array:-
Reading 2D array
where m-rowsize, n-columnsize, i-row index and j-column index
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d", &a[i][j]);
}
}
Printing 2D array
where m-rowsize, n-columnsize, i-row index and j-column index
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("%d", a[i][j]);
}
printf(“\n”)
}
1. Write a c program to read and print the matrix of m rows and n columns
#include<stdio.h>
void main()
{
int a[20 ][20]m,n,i,j;
printf(“enter the row and column size\n”);
scanf(“%d%d”,&m,&n);
printf(“Enter the elements of matrix\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d", &a[i][j]);
}
}
printf(“The elements of matrix are\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("%d\t", a[i][j]);
}
printf(“\n”);
}
}
Output
Enter the row and column size
23
Enter the elements of matrix
3 4 5 9 10 12
The elements of matrix are
3 4 5
9 10 12
include<stdio.h>
void main()
{
int a[20 ][20],b[20][20],c[20][20],m,n, i,j;
printf(“enter the rows and column of matrix\n”);
scanf(“%d%d”,&m,&n);
printf(“Enter the elements of Matrix A\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf(“%d”,&a[i][j]);
}
}
printf(“Enter the elements of Matrix B\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf(“%d”,&b[i][j]);
}
}
printf(“Matrix Addition\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
c[i][j]=a[i][j]+b[i][j];
}
}
printf(“The resultant matrix is\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf(“%d\n”,c[i]);
}
printf(“\n”);
}
}
include<stdio.h>
void main()
{
int a[20 ][20],b[20][20], m,n, i,j;
printf(“enter the rows and column of matrix\n”);
scanf(“%d%d”,&m,&n);
printf(“Enter the elements of Matrix\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf(“%d”,&a[i][j]);
}
}
printf(“Enter the elements of Matrix are\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf(“%d\t”,a[i][j]);
}
printf(“\n”);
}
printf(“Matrix Transpose\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
b[j][i]=a[i][j];
}
}
printf(“The Transpose of the matrix is \n”);
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
printf(“%d\t”,b[i][j]);
}
printf(“\n”);
}
}
include<stdio.h>
void main()
{
int a[20 ][20], m,n, i,j;
printf(“enter the no rows and column of matrix\n”);
scanf(“%d%d”,&m,&n);
printf(“Enter the elements of Matrix\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf(“%d”,&a[i][j]);
}
}
printf(“Matrix A is \n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf(“%d\t”,a[i][j]);
}
printf(“\n”);
}
printf(“The diagonal Elements are\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
if(i==j)
{
printf(“%d”,a[i][j]);
}
}
printf(“\n”);
}
}
5. Write a C Program to find sum of the the rows and columns of given matrix
#include<stdio.h>
void main()
{
int a[20 ][20], m,n, i,j,sum;
printf(“enter the no rows and column of matrix\n”);
scanf(“%d%d”,&m,&n);
printf(“Enter the elements of Matrix\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf(“%d”,&a[i][j]);
}
}
printf(“Martix A is Displayed as \n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf(“%d\t”,a[i][j]);
}
printf(“\n”);
}
for(i=0;i<m;i++)
{
sum=0;
for(j=0;j<n;j++)
{
sum=sum+a[i][j];
}
printf(“sum of the elements of row %d in matrix=%d”,i,sum);
}
for(i=0;i<m;i++)
{
sum=0;
for(j=0;j<n;j++)
{
sum=sum+a[j][i];
}
printf(“sum of the elements of column %d in matrix=%d”,i,sum);
}
#include<stdio.h>
void main()
{
int a[20 ][20], m,n, i,j,sum=0;
printf(“enter the order of matrix”);
scanf(“%d%d”,&m,&n);
printf(“Enter the elements of Matrix\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf(“%d”,&a[i][j]);
}
}
printf(“Martix A is Displayed as \n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf(“%d\t”,a[i][j]);
}
printf(“\n”);
}
for(i=0;i<m;i++)
{
sum=sum+a[i][i];
}
printf(“The sum of the diagonal elements of matrix=%d\n”,sum);
}
#include<stdio.h>
void main()
{
int a[20 ][20], m,n, i,j,large;
printf(“enter the order of matrix\n”);
scanf(“%d%d”,&m,&n);
printf(“Enter the elements of Matrix\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf(“%d”,&a[i][j]);
}
}
printf(“Martix A is Displayed as \n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf(“%d\t”,a[i][j]);
}
printf(“\n”);
}
large=0;
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
if(a[i][j]>large)
large=a[i][j];
}
}
printf(“The largest element in the matrix = %d\n”,large);
}
Multidimensional array
An array having 3 or more subscript or dimensions is known as multidimensional array.
It is also known as arrays of arrays or matrix.
The general form of multidimensional array is
data_type array_name[s1][s2][s3]….[sn];
Where s1 is the size of ith dimension.
Representation of Multidimensional Array
POINTERS
Pointers: A pointer is a variable that holds the address of another variable. The pointer variable
contains only the address of the referenced variable not the value stored at that address.
Disadvantages of pointers
1. One of the disadvantage of using pointer is that program may crash if sufficient memory
is not available at run time to store pointers.
Datatype *ptrname;
Data type: It specifies the type of the pointer variable that you want to declare like (int, float,
char, double or void)
* (Asterisk): tells the compiler that you are creating a pointer variable and ptrname specifies the
name of the pointer variable.
Initialization of pointer variable: Similar to the initialization of other variables at the time of their
declaration, you can also initialize the pointer variable by assigning address of othervariables to
them.
Syntax
Datatype *ptrname = expression;
Where
Datatype: It can be any basic data type,
ptrname is a pointer variable
expression can be any constant value or any variable containing value.
Example 1:
int a;
int *ptr = &a; //address of a is stored in ptr variable .
Example 2:
float temp; // temp is a variable of float type
float *p; //p is a ptr variable pointing to float type
p=&temp; // pointer variable p holds the address of temp
program to illustrate declaration and initialization
Example:
#include<stdio.h>
void main()
{
int *ptr; / /declaration ofpointer variable
int a=10;
ptr=&a; / /initialization of pointer variable
printf(“the value of a=%d\”,a);
printf(“the value of a using pointer=%d\n”,*ptr);
printf(“the address of a=%u\n”,ptr);
}
Output:
The value of a=10
The value of a using pointer=10
The address of a =32200
Using the address of (&) operator: A computer uses memory to store the instructions of different
programs and the values of different variables. Since memory is a sequential collection of storage
cells, each cell has an address. When you declare a variable, the operating system allocates memory
according to the size of the data type of that variable. In this memory location, the value of the
variable is stored.
This statement request the operating system to allocate two bytes of space in memory and stores 100
in that location.
a ------------ variable name
By using the address of (&) operator, you can determine the address of a variable.
#include<stdio.h>
Void main()
{
int a=100,*ptr1;
float b=12.6, *ptr2;
ptr1=&a;
ptr2=&b;
printf(“the address of a = %u and its value is%d\n”,ptr1,*ptr1);
printf(“the address of b =%u and its value is %f\n”,ptr2,*ptr2);
getch();
}
Output: the address of a=2600 and its value is 100
The address of b=4876 and its value is 12.600000
#include<stdio.h>
void swap(int *a, int *b);
void main()
{
int x,y;
x=100;
y=200;
printf(“before swap: x=%d\n y=%d\n”x,y);
swap(&x,&y);
printf(“after swap: x=%d\n,y=%d\n”,x,y);
}
void swap(int *a, int *b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}
Output:
Before swap: x=100
y=200
After swap: x=200
y=100
Pointers and arrays: Arrays are closely related to pointers in C programming but the important
difference between them is that, a pointer variable can take different addresses as value
whereas, in case of array it is fixed. This can be demonstrated by an example:
#include <stdio.h>
void main()
{
char c[4];
int i;
for(i=0;i<4;++i){
printf("Address of c[%d]=%x\n",i,&c[i]);
}
}
Notice, that there is equal difference (difference of 1 byte) between any two consecutive elements
of array.
int arr[4];
In arrays of C programming, name of the array always points to the first element of an array.
Here, address of first element of an array is &arr[0]. Also, arr represents the address of the
pointer where it is pointing. Hence, &arr[0] is equivalent to arr.
void main()
{
int i,marks[10],sum=0;
printf("Enter 10 marks:\n");
for(i=0;i<10;++i)
scanf("%d",(marks+i));
for(i=0;i<10;++i){
sum += *(marks+i);
}
printf("Sum=%d",sum);
getch();
}
Output
Enter 10 marks:
2 3 4 5 3 5 7 10 21 28
Sum=88
Pointer Arithmetic
Pointer arithmetic is very important to understand, if you want to have complete knowledge of
pointer. In this topic we will study how the memory addresses change when you increment a pointer.
16 bit Machine
In a 16 bit machine, size of all types of pointer, be it int*, float*, char* or double* is always 2 bytes.
But when we perform any arithmetic function like increment on a pointer, changes occur as per the
size of their primitive data type.
Size of datatypes on 16-bit Machine :
Type Size(bytes)
Char 1
Long 4
Float 4
Double 8
long double 10
Examples for Pointer Arithmetic
Now lets take a few examples and understand this more clearly.
int* i;
i++;
In the above case, pointer will be of 2 bytes. And when we increment it, it will increment by 2
bytes because int is also of 2 bytes.
float* i;
i++;
In this case, size of pointer is still 2 bytes. But now, when we increment it, it will increment by 4
bytes because float is of 4 bytes.
double* i;
i++;
Similarly, in this case, size of pointer is still 2 bytes. But now, when we increment it, it willincrement
by 8 bytes because its data type is double.
Pointers to Pointer
A pointer to a pointer is a form of multiple indirection, or a chain of pointers. Normally, a pointer
contains the address of a variable. When we define a pointer to a pointer, the first pointer contains
the address of the second pointer, which points to the location that contains the actual value as
shown below.
A variable that is a pointer to a pointer must be declared as such. This is done by placing an
additional asterisk in front of its name. For example, the following declaration declares a pointer
to a pointer of type int −
int **var;
When a target value is indirectly pointed to by a pointer to a pointer, accessing that value requires
that the asterisk operator be applied twice, as is shown below in the example −
#include <stdio.h>
void main ()
{
int var;
int *ptr;
int **pptr;
var = 3000;
ptr = &var;
pptr = &ptr;
printf("Value of var = %d\n", var );
printf("Value available at *ptr = %d\n", *ptr );
printf("Value available at **pptr = %d\n", **pptr);
getch();
}
Output:
Value of var = 3000
Value available at *ptr = 3000 Value
available at **pptr = 3000