Pages

Showing posts with label array boundary elements. Show all posts
Showing posts with label array boundary elements. Show all posts

Wednesday, August 31, 2011

Two Dimensional Array Program with C and C++

This article will show how to find boundary elements and higher and lower level elements of a matrix or a two dimensional array with C and C++ program. The following program will first take user inputs to build a two dimensional array or a matrix and then show the matrix, the boundary elements and the sum of the boundary elements, diagonal elements and its sum. Here, for loop is used to set and retrieve array elements. 


Programming code to find boundary elements and higher and lower level elements of a matrix.

#include<stdio.h>
#include<conio.h>
void main()
{
  int a[5][5],m,n,sum=0;
  printf("Enter row :");
  scanf("%d",&m);
  printf("Enter coloum :");
  scanf("%d",&n);
  printf("Enter matrix element :\n");
  for(int i=0;i<m;i++)
  {
            for(int j=0;j<n;j++)
            {
              printf("a[%d][%d]=",i,j);
              scanf("%d",&a[i][j]);
            }
  }
  printf("\nMatrix is : \n");
  for(i=0;i<m;i++)
  {
            for(int j=0;j<n;j++)
            {
              printf("%d\t",a[i][j]);
            }
            printf("\n");
  }
  printf("\nBoundary element :");
  for(i=0;i<m;i++)
  {
            for(int j=0;j<n;j++)
            {
              if((i*j==0)||(i==m-1)||(j==n-1))
              {
                        printf("%d  ",a[i][j]);
                        sum=sum+a[i][j];
              }
            }
  }
  printf("\nSum of boundary element is : %d",sum);

 printf("\nHigher level : ");
 sum=0;
 for(i=0;i<m;i++)
 {
   for(int j=0;j<n;j++)
   {
             if(i==j)
             {

               printf("\t%d",a[i][j]);
               sum=sum+a[i][j];
             }
   }

 }
  printf("\nSum of higher level = %d",sum);

  printf("\nLower lavel : ");
  sum=0;
  i=m;
  for(int j=0;j<n;j++)
  {
            i=i-1;
            printf("\t%d",a[i][j]);
            sum=sum+a[i][j];
  }
  printf("\nSum of lower level = %d",sum);
  getch();
}

Output