Satyam Singh
Satyam Singh

Reputation: 11

Print the largest value of each row in the given matrix

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
    int m=3,n=3,k=0,i,j,Total=0, Next_Total;
    int *input3[9]={3,6,9,1,4,7,2,8,9};
    int arr[m][n];
    for(i=0;i<m;i++){
        for(j=0;j<n;j++){
            arr[i][j]=input3[k++];//assigning values in 2d array
        }
    }
    for(i=0;i<m;i++){
        for(j=0;j<n;j++){
            printf("%d ", arr[i][j]);//printing values of 2d array
        }
        printf("\n");
    }
    for(i=0;i<m;i++){
        for(j=0;j<n;j++){
            Total= Total + arr[i][j];// adding values each row of 2d array in Total
            printf("%d", Total);
        }
        if(Total>Next_Total){
            Next_Total=Total;// comparing the values and printing the largest 
        }
        
    }
    printf("%d", Next_Total);
}

In the line 22 i am adding values but i am not getting desired output, I don't know why i am getting this 391819233032404949 value.

Upvotes: 1

Views: 49

Answers (1)

Nilanshu96
Nilanshu96

Reputation: 157

That weird result is because of the print statement in your for loop. As it is printing multiple times in the same line

Also remove * from int *input3[9]={3,6,9,1,4,7,2,8,9}; as it is an array of int pointers.

Also your solution is incorrect as well as you have to initialize total to 0 after each row.

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<limits.h>
int main()
{
    int m=3,n=3,k=0,i,j,Total=0, Next_Total=INT_MIN;
    int input3[9]={3,6,9,1,4,7,2,8,9};
    int arr[m][n];
    for(i=0;i<m;i++){
        for(j=0;j<n;j++){
            arr[i][j]=input3[k++];//assigning values in 2d array
        }
    }
    for(i=0;i<m;i++){
        for(j=0;j<n;j++){
            printf("%d ", arr[i][j]);//printing values of 2d array
        }
        printf("\n");
    }
    for(i=0;i<m;i++){
        for(j=0;j<n;j++){
            Total= Total + arr[i][j];// adding values each row of 2d array in Total
            
        }
        if(Total>Next_Total){
            Next_Total=Total;// comparing the values and printing the largest 
        }
        Total = 0;
    }
    printf("%d", Next_Total);
}

Upvotes: 1

Related Questions