Left Right Top Bottom Sum

 Coding Problem Keys 

 Left Right Top Bottom Sum 

 Problem Statement 

The program must accept a matrix of size R*C and for each cell the program must print the sum of left, right, top and bottom cells.

 Boundary Conditions 

2 <= R, C <= 20
1 <= Matrix element value <= 10

Input Format

The first line contains R and C separated by a space.
The next R lines, each contains C integers separated by a space.

Output Format

The first R lines, each contains C integers separated by a space.

 Example Input/Output 1 

 Input 

5 4
7 3 8 4
8 1 10 4
4 8 4 6
3 2 2 1
1 1 10 1

 Output 

11 16 17 12
12 29 17 20
19 11 26 9
7 14 17 9
4 13 4 11

 Example Input/Output 2 

 Input 

3 3
1 2 3
4 5 6
7 8 9

 Output 

6 9 8
13 20 17
12 21 14

 Note: Max Execution Time Limit: 50 millisecs 

 Solution 

 Programming Language: C Language 

#include<stdio.h>
#include<stdlib.h>
int getLeftRightTopBtmSum(int r,int c,int i,int j,int a[r][c]){
    int sum=0;
    //Left Cell
    if(j-1>=0){
        sum+=a[i][j-1];
    }
    //Right Cell
    if(j+1<c){
        sum+=a[i][j+1];
    }
    //Top Cell
    if(i-1>=0){
        sum+=a[i-1][j];
    }
    //Bottom Cell
    if(i+1<r){
        sum+=a[i+1][j];
    }
    return sum;
}
int main(){
    int r,c;
    scanf("%d%d",&r,&c);
    int a[r][c];
    for(int i=0;i<r;i++){
        for(int j=0;j<c;j++){
            scanf("%d",&a[i][j]);
        }
    }
    for(int i=0;i<r;i++){
        for(int j=0;j<c;j++){
            printf("%d ",getLeftRightTopBtmSum(r,c,i,j,a));
        }
        printf("\n");
    }
}
//Published By PKJCODERS

 (Note: Incase If the code doesn't Pass the output kindly comment us with your feedback to help us improvise.) 

Comments

Popular Posts

Mango Distribution

Maximum Goods Transported

Value Equals Previous Two

RAT CHEESE MAZE

Alphabetical Order Pattern

Iterate Base