Thursday, May 27, 2010

Program to Find Address of Element in Two Dimensional Array

#include< stdio.h >
#include< conio.h >
//global declaration of all variables
int a[5][5],i,j,m,n,c,r,l1,u1,l2,u2,eadd,badd,ch,yes=0;


//function declaration
void insert();
void row();
void column();


void main()
{
clrscr();


printf("\nEnter Lower Bound of ROW (L1) = ");
scanf("%d",&l1);
printf("\nEnter Upper Bound of ROW (U1) = ");
scanf("%d",&u1);
printf("\nEnter Lower Bound of COLUMN (L2) = ");
scanf("%d",&l2);
printf("\nEnter Upper Bound of COLUMN (U2) = ");
scanf("%d",&u2);


//calculate total elements in row
m=u1-l1+1;


//calculate total elements in columns
n=u2-l2+1;


do
{
    clrscr();
    printf("\n...............................................");
    printf(" \n 1 to Enter Array Elements");
    printf(" \n 2 to Find Address of Element in Row Major");
    printf(" \n 3 to Find Address of Element in Column Major");
    printf(" \n 4 to Exit");
    printf("\n...............................................");
    printf(" \n Enter Your Choice = ");
    scanf("%d",&ch);
    switch(ch)
    {
        case 1:insert(); //call of insert () function
               printf("\n\nPress Any Key to Continue");
               getch();
               yes=1;
               break;


        case 2: row(); // call of function row() to find address in row major
            printf("\n\nPress Any Key to Continue");
            getch();
            yes=1;
            break;


        case 3: column(); // call of function column() to find address in column major
            printf("\n\nPress Any Key to Continue");
            getch();
            yes=1;
            break;


        case 4: yes=0;
            break;
    }
} while(yes==1);
getch();
}


//Function to Insert element in Array
void insert()
{       //enter array elements
    printf("\nEnter Array Elemnts \n");
    for(r=l1;r < u1;r=r+1)
    {
    for(c=l2;c < u2;c=c+1)
    {
        scanf("%d",&a[r][c]);
    }
    }
}
//Function to Calculate address of element a[i][j] in ROW major
void row()
{
    // Enter postion i and j
    printf("\n Address of element \n");
    printf("\n i = ");
    scanf("%d",&i);
    printf("\n j = ");
    scanf("%d",&j);


    //find base address
    badd=(int)&a;


    //calculate address of element a[i][j] in row major
    eadd=badd + (sizeof(int)*((n * (i-l1)) + (j-l2)));
    printf("\n\nAddress of element a[%d][%d] = %d", i,j,eadd);
}


//Function to Calculate address of element a[i][j] in COLUMN major
void column()
{
    // Enter postion i and j
    printf("\n Address of element \n");
    printf("\n i = ");
    scanf("%d",&i);
    printf("\n j = ");
    scanf("%d",&j);


    //find base address
    badd=(int)&a;
     
    //calculate address of element a[i][j] in column major
    eadd=badd + (sizeof(int)*((m * (j-l2)) + (i-l1)));
    printf("\n\nAddress of element a[%d][%d] = %d", i,j,eadd);
}

No comments:

Post a Comment