Home > Backend Development > C++ > Write a program in C language to print out a square matrix arranged in a Z shape

Write a program in C language to print out a square matrix arranged in a Z shape

WBOY
Release: 2023-08-27 10:57:17
forward
1284 people have browsed it

Program Description

Print the elements of a square matrix in Z form

A square matrix is ​​a matrix with the same number of rows and columns. An n×n matrix is ​​called an n-order square matrix

Algorithm

Write a program in C language to print out a square matrix arranged in a Z shape

To print the elements of the Square Matrix in Z form
We need to print the first row of matrix then diagonal and then last row of the square matrix.
Copy after login

Example

The Chinese translation is:

Example

/* Program to print a square matrix in Z form */
#include<stdio.h>
int main(){
   int rows, cols, r, c, matrix[10][10];
   clrscr(); /*Clears the Screen*/
   printf("Please enter the number of rows for the Square matrix: ");
   scanf("%d", &rows);
   printf("</p><p>");
   printf("Please enter the number of columns for the Square matrix: ");
   scanf("%d", &cols);
   printf("</p><p>");
   printf("Please enter the elements for the Matrix: </p><p>");
   for(r = 0; r < rows; r++){
      for(c = 0;c < cols;c++){
         scanf("%d", &matrix[r][c]);
      }
   }
   printf("The Z Form Elements in the Square Matrix are: ");
   printf("</p><p>");
   for(r = 0; r < rows; r++){
      printf("%d\t ", matrix[0][r]);
   }
   for (r=1,c=cols-2;r<cols && c>=0;r++,c--){
      printf("%d\t ", matrix[r][c]);
   }
   for (r = 1; r < cols; r++){
      printf("%d\t ", matrix[cols-1][r]);
   }
   getch();
   return 0;
}
Copy after login

Output

Write a program in C language to print out a square matrix arranged in a Z shape

The above is the detailed content of Write a program in C language to print out a square matrix arranged in a Z shape. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template