Lec 23 Pointers and arrays Practise problems
Lec 23 Pointers and arrays Practise problems
problems
Lecture 23
Example: Passing arrays between functions:
}
}
O/P:
1234 56
1212 33
1434 80
1312 78
Example :Passing 2-D Array to a Function
/* Three ways of accessing a 2-D array */
void main( ) show ( int ( *q )[4], int row, int col ) // 2nd way
{ {
int a[3][4] = { int i, j ;
1, 2, 3, 4, int *p ;
5, 6, 7, 8, for ( i = 0 ; i < row ; i++ )
9, 0, 1, 6 {
}; p=q+i;
display ( a, 3, 4 ) ; for ( j = 0 ; j < col ; j++ )
show ( a, 3, 4 ) ; printf ( "%d ", * ( p + j ) ) ; }}
print ( a, 3, 4 ) ;
} print ( int q[ ][4], int row, int col ) // 3rd way
display ( int *q, int row, int col ) // one {
way int i, j ;
{ for ( i = 0 ; i < row ; i++ )
int i, j ; {
for ( i = 0 ; i < row ; i++ ) for ( j = 0 ; j < col ; j++ )
{ printf ( "%d ", q[i][j] ) ; }}
for ( j = 0 ; j < col ; j++ )
printf ( "%d ", * ( q + i * col + j ) ) ; }}
Example:
Write a C program to accept 5 numbers, store them in an array and find out the
smallest number using pointer.
#include<stdio.h>
int main()
{
int a[5],*s,i,small;
s=&a[0];
printf("Enter 5-Elements :\n\n ");
for(i=0;i<5;i++,s++)
scanf("%d",s);
s=&a[0];
small=*s;
for(i=0;i<5;i++,s++)
if(*s<small)
small=*s;
printf("\nSmallest Element : %d",small);
return 0;
}
Example: Write a program which performs the following tasks:
− initialize an integer array of 10 elements in main( )
− pass the entire array to a function modify( )
− in modify( ) multiply each element of array by 3
− return the control to main( ) and print the new array elements in main( )
#include<stdio.h>
int main()
{
int arr[] = { 10,20,30,40,50,60,70,80,90,100 }, i;
modify(arr);
for (i = 0; i<10; i++)
printf("%d ", arr[i]);
return 0;
}
void modify(int *elem)
{
int i;
for (i = 0; i<10; i++)
{
*elem *= 3;
elem++; }}
First Method:
#include <stdio.h>
void main()
{
int arr[] = { 10,20,30,40,50,60,70,80,90,100 }, i,j;
for (i = 0; i<10; i++){
modify(&arr[i]);
}
for (j = 0; j<10; j++)
printf("%d\n", arr[j]);
return 0;
}
void modify(int *pnt)
{
*pnt *= 3; OR *pnt = *pnt * 3;
}
Second Method:
#include <stdio.h>
void main()
{
int arr[] = { 10,20,30,40,50,60,70,80,90,100 },j;
modify(&arr[0],10);
#include<stdio.h>
void main()
{
int arr[2][2] = { {1, 2}, {3, 4} }, i;
modify(arr,2,2);
}
void modify(int *q,int row,int col)
{
int i, j ;
for ( i = 0 ; i < row ; i++ )
{
for ( j = 0 ; j < col ; j++ )
printf ( "%d ", * ( q + i * col + j )*3 ) ;
}}