Saturday, September 11, 2021

Addition of each row and each column in 2d array

 
import java.util.*;
class Even_series
{
   int arr[][]=new int [5][5];
   int i,j, sum_row, sum_col;
    Scanner sc=new Scanner(System.in);       
   public void take()
            {
                for( i=0;i<5;i++)
                {
                     for( j=0;j<5;j++)
                     {            
                 System.out.print("\nValue: ");
                 arr[i][j]=sc.nextInt();
                }          
             }
              System.out.print("\nArray as follows\n"); 
              for( i=0;i<5;i++)
                {
                     for( j=0;j<5;j++)
                     {            
                 System.out.print(" "+arr[i][j]);                 
                } 
                System.out.println();
             }
             display();
            }
            private void display()
            {
                for(i=0;i<5;i++)
                {
                     sum_row=0;
                     sum_col=0;
                   for(j=0;j<5;j++)
                   {
                       sum_row+=arr[i][j];
                       sum_col+=arr[j][i];
                    }
                    System.out.println("\nSum of row no "+ (i+1) + ": "+sum_row);
                    System.out.println("\nSum of column no "+ (i+1) + ": "+sum_col);
                }
            }
        }
            
      Sample Input Output

Value: 1
Value: 2
Value: 3
Value: 4
Value: 5
Value: 6
Value: 7
Value: 8
Value: 9
Value: 9
Value: 7
Value: 6
Value: 5
Value: 4
Value: 3
Value: 2
Value: 3
Value: 4
Value: 5
Value: 6
Value: 7
Value: 6
Value: 5
Value: 4
Value: 3
Array as follows
 1 2 3 4 5
 6 7 8 9 9
 7 6 5 4 3
 2 3 4 5 6
 7 6 5 4 3
Sum of row no 1: 15
Sum of column no 1: 23
Sum of row no 2: 39
Sum of column no 2: 24
Sum of row no 3: 25
Sum of column no 3: 25
Sum of row no 4: 20
Sum of column no 4: 26
Sum of row no 5: 25
Sum of column no 5: 26

No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner