Adding two Matrix (3 x 3) In C programming

The files "mata.txt" and "matb.txt" contain integer matrices of size 3 x 3. Write a program that calculates the sum of the matrices in a new matrix. The resulting sum matrix shall be saved to the file "sum.txt".

#include<stdio.h>

int main()
{
    FILE *filea, *fileb,*filec; //initialize the files
    int arraya[3][3],arrayb[3][3],sum[3][3]; //initialize arrays which consists 3*3 elements 
    int i ,j;

//PART A
//We try to read from file mata.txt (filea).

    if ((filea=fopen("mata.txt","r"))==NULL) // try to read from txt file 
    {
        printf("Failed to open mata.txt"); 
    }
    else
    {
        for(i=0;i<3;i++)
        {
            for(j=0;j<3;j++){
                fscanf(filea,"%d",&arraya[i][j]); //reading from txt file
            }
        }
    }
    fclose(filea);

//PART B
//We try to read from file mata.txt (fileb).

    if ((fileb=fopen("matb.txt","r"))==NULL)
    {
        printf("Failed to open matb.txt");
    }
    else{
        for (i=0;i<3;i++)
        {
            for (j=0;j<3;j++){
                fscanf(fileb,"%d",&arrayb[i][j]);
            }
        }
    }
    fclose(fileb);
    
//PART C
//Matrix addition

    for(i=0;i<3;i++)
        {
        for(j=0;j<3;j++)
        {
            sum[i][j]=arraya[i][j]+arrayb[i][j]; //adding two matrix
        }
    }

//PART D
//We now open a new file sum.txt (filec) and save the result in the file.
    if((filec=fopen("sum.txt","w"))==NULL) // trying to open and write to file
    {
        printf("Failed to open sum.txt");
    }
        for(i=0;i<3;i++)
        {
            for(j=0;j<3;j++)
            {
                if(j==2)
                {
                 fprintf(filec,"%d\n",sum[i][j]); // printing in file file sum.txt
                }
                else
                {
                    fprintf(filec,"%d  ",sum[i][j]);
                }


        }
    }
    printf("The sum of the matrices has been calculated into the file sum.txt.\n");
    fclose(filec);
    return 0;

}

Comments

Popular posts from this blog

What is LDR and how it works with circuit to try on?

Use of 4 Strain Gauge Sensors and LabView DAQ to Measure and Calculate Weigth

POWER SUPPLY (5A Constant Current Source)