Powered By Blogger

Thursday 28 April 2011

Create a 2D array dynamically then passing it to another function using Call by Reference and then updating the matrix by using pointers and without copying it to any other dummy matrix and without using generel matrix accesing logic. Then its printed from the Main() function.

#include<stdio.h>
#include<conio.h>
int passed(int **,int,int);
int main(void)
{
    int **matrix,order[2],i=0,j=0;
    printf("\n**************** Addition to 2D matrix by pointer arithmetic  ****************\n\n");
    printf("Input the order of the matrix (m n) ::\n");
    for(i=0;i<2;i++)
        scanf(" %d",&order[i]);
    matrix=(int**)malloc((order[0]+2)*sizeof(int*));
    for(i=0;i<order[0];i++)
        matrix[i]=(int*)malloc((order[1]+2)*sizeof(int));
    printf("\n\nEnter the elements of the matrix (Row Wise)::\n");
    for(i=0;i<order[0];i++)
    {
        for(j=0;j<order[1];j++)
        {
            scanf("%d",&matrix[i][j]);
        }
    }

    printf("\n\nMatrix Before ::\n\n");
    for(i=0;i<order[0];i++)
    {
        for(j=0;j<order[1];j++)
        {
            printf("%5d",matrix[i][j]);
        }
        printf("\n");
    }
    passed(matrix,order[0],order[1]);
    printf("\n\nMatrix after ::\n\n");
    for(i=0;i<order[0];i++)
    {
        for(j=0;j<order[1];j++)
        {
            printf("%5d",matrix[i][j]);
        }
        printf("\n");
    }
    getch();
    return 0;
}


int passed(int **arr,int row,int col)
{
    int *p[10],i=0,j=0,val=0;
    printf("\n\nEnter a value to add to each element of the matrix:: ");
    scanf("%d",&val);
for(i=0;i<row;i++)
{
    p[i]=arr[i];
}
for(i=0;i<row;i++)
{
    for(j=0;j<col;j++)
    {
        *(p[i]+(j*1))=*(p[i]+(j*1))+val;
    }
}
return 0;
}

No comments:

Post a Comment