C two-dimensional array

Example - Two-dimensional array


#include <stdio.h>
/*from   www  . j  a  va  2 s  . com*/
main(){
    int a[3][2];
    int i,j;
    for(i = 0;i<3;i++){
        for(j=0;j<2 ;j++) {
           a[i][j]=2;
        }
    }

    for(i = 0;i<3;i++){
        for(j=0;j<2;j++) {
           printf("value in array %d\n",a[i][j]);
        }
    }

    for(i = 0;i<3;i++){
        for(j=0;j<2;j++){
           printf("value in array %d and address is %8u\n", a[i][j],&a[i][j]);
        }
    }
}

The code above generates the following result.

Transpose of a matrix


#include<stdio.h>
#include<conio.h>
#define ROW 3/*from w  ww .jav a2  s .c  om*/
#define COL 3

void dis(int a[][COL],int,int);
void trans(int a[][COL],int,int);

void main()
{
   int a[ROW][COL];
   a[0][0] = 1;    a[0][1] = 2;    a[0][2] = 3;
   a[1][0] = 4;    a[1][1] = 5;    a[1][2] = 6;
   a[2][0] = 7;    a[2][1] = 8;    a[2][2] = 9;

   printf("\nThe matrix is \n");
   dis(a,ROW,COL);
   trans(a,ROW,COL);
   printf("The tranpose of the matrix is\n");
   dis(a,ROW,COL);
   getch();
}

void dis(int d[3][3 ],int i,int k)
{
   int j,l;
   for(j=0;j<i;j++)
   {
      for(l=0;l<k;l++)
             printf("%d ",d[j][l]);
      printf("\n");
   }
}
void trans(int mat[][3],int k ,int l)
{
   int i,j,temp;
   for(i=0;i<k;i++)
       for(j=i+1;j<l;j++)
      {
         temp=mat[i][j];
         mat[i][j]=mat[j][i];
         mat[j][i]=temp;
      }
}

The code above generates the following result.





















Home »
  C Language »
    Language Basics »




C Language Basics
Data Types
Operator
Statement
Array