Matrix with Specific Values
This program creates and displays a square matrix with specific values based on the relative positions of the elements. For each element in the matrix, the value is determined by comparing its row index and column index. Specifically, elements where the row index is less than the column index are assigned the value 1
, elements where the row index is greater than the column index are assigned -1
, and elements where the row index equals the column index are assigned 0
. The matrix is first filled according to these rules and then displayed to the user.
Code Breakdown
Algorithm
- Start
- Initialize Variables: Define matrix
a[10][10]
, and variablesi
,j
,m
, andn
. - Input Matrix Order: Prompt the user to enter the number of rows
m
and columnsn
(ensure it's a square matrix). - Fill Matrix:
- For each element in the matrix:
- If the row index
i
is less than the column indexj
, seta[i][j]
to1
. - If the row index
i
is greater than the column indexj
, seta[i][j]
to-1
. - If the row index
i
equals the column indexj
, seta[i][j]
to0
.
- If the row index
- For each element in the matrix:
- Display Matrix: Print the matrix row by row.
- End
Code Explanation
Example Flowchart
+-------------------------+
| Start |
+-------------------------+
|
v
+-------------------------+
| Clear the screen |
+-------------------------+
|
v
+-------------------------+
| Prompt for matrix order |
| (rows m, columns n) |
+-------------------------+
|
v
+-------------------------+
| Read m and n |
+-------------------------+
|
v
+-------------------------+
| Initialize i = 0 |
+-------------------------+
|
v
+-------------------------+
| i < m ? |
+-----------+-------------+
| Yes
v
+-------------------------+
| Initialize j = 0 |
+-------------------------+
|
v
+-------------------------+
| j < n ? |
+-----------+-------------+
| Yes
v
+-------------------------+
| i < j ? |
+-----------+-------------+
| Yes
v
+-------------------------+
| a[i][j] = 1 |
+-------------------------+
|
v
+-------------------------+
| i > j ? |
+-----------+-------------+
| Yes
v
+-------------------------+
| a[i][j] = -1 |
+-------------------------+
|
v
+-------------------------+
| Else |
+-------------------------+
| a[i][j] = 0 |
+-------------------------+
|
v
+-------------------------+
| Increment j |
+-------------------------+
|
v
+-------------------------+
| j < n ? |
+-----------+-------------+
| No
v
+-------------------------+
| Increment i |
+-------------------------+
|
v
+-------------------------+
| i < m ? |
+-----------+-------------+
| No
v
+-------------------------+
| Print matrix |
+-------------------------+
|
v
+-------------------------+
| End |
+-------------------------+