C exercises and solutions: C array printing a matrix


C array: print a matrix exercise

By using two-dimensional array, write C program to display a matrix as shown below:
01 11 1 
-10 11 1
-1-1 01 1
-1-1 -10 1
-1-1 -1-1 0
 

Solution:
#include<stdio.h>
#include<conio.h>
 
   int main()
    {
    
     int matrix[5][5];
     int i,j;
     for(i=0;i<5;i++) //assign values to the matrix

        for(j=0;j<5;j++){ //

           if(i==j) matrix[i][j]=0;if row=column=> fill the matrix with 0
           else if(i>j) matrix[i][j]=-1;//if row>columns=> fill matrix with -1
           else matrix[i][j]=1; //if row<columns=> fill matrix with 1
             }    
           
     for(i=0;i<5;i++){ //print the array
        for(j=0;j<5;j++)
            printf("%d\t",matrix[i][j]);
       printf("\n");  
       }
     getch();
     return 0;
 
    }
   
 


Comments




This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.