Home > Software design >  sum of squaresum of rows of the matrix
sum of squaresum of rows of the matrix

Time:03-02

The task is to output the sum of the square sum of each row without using arrays. I have written a code and it doing the job, only I couldn't find a way that allows dynamic sizing of the matrix according to the first input which will be the size of the matrix, so that instead of pressing 'enter' after each element, the user can separate each element by a 'space' and separate the rows with 'enter', like in an actual matrix. If there is a way, please tell me. Here is the code where one needs to press 'enter' after each element.

/*Take matrix size as input. read each element and give out the sum of squaresum of rows of the matrix*/
#include <stdio.h>
int main(){
    int m,n;    //matrix size row,column
    int rowsum = 0,sum = 0,a,col,row = 0;
    printf("Enter the size of matrix\n");
    scanf("%d %d",&m,&n);   //take row and col
    while (row!=m)      //calculate sum of each element of column one by one row-wise
    {
        col = 0;    //start from col 1 i.e col 0
        rowsum = 0; 
        printf("Enter elements of %d row\n",row 1);
        while (col!=n){     //calculate sum of each element of rows one by one col-wise
            scanf("%d",&a); //read the element
            rowsum  = a;    //add read element to sum of that row
            col   ; //move to next element
        }
        sum  = rowsum*rowsum;   //add the sq. of that rowsum before moving on to next
        row   ; //move to next row
    }
    printf("%d is sum of squaresum of rows",sum);
    return 0;
}

Thank you in advance.

CodePudding user response:

You can get rid of the next character while scanning so that you are able to enter only one space after a number. Also, you can put any character in between the numbers in this way. Use "%*c" to skip a character while scanning. Here is the code:

/*Take matrix size as input. read each element and give out the sum of squaresum of rows of the matrix*/
#include <stdio.h>
int main(){
    ...
    while (row!=m)      //calculate sum of each element of column one by one row-wise
    {
        col = 0;    //start from col 1 i.e col 0
        rowsum = 0;
        printf("Enter elements of %d row\n",row 1);
        while (col!=n){     //calculate sum of each element of rows one by one col-wise
            scanf("%d%*c",&a); //read the element

            rowsum  = a;    //add read element to sum of that row
            col   ; //move to next element
        }
    ...
    }
    return 0;
}

Some possible inputs for a row while size selected as (2, 3):

Enter the size of matrix
2 3
Enter elements of 1 row
1;2;3
Enter elements of 2 row
4;5;6

Output:

261 is sum of squaresum of rows

Another possible way:

Enter the size of matrix
2 3
Enter elements of 1 row
1 2 3
Enter elements of 2 row
4 5 6

Output is the same one above.

  • Related