Example Programs

Program [1]

Write a program to declare a square matrix M [ ] [ ] of order ‘N’ where ‘N’ must be greater than 3 and less than 10. Allow the user to accept three different characters from the keyboard and fill the array according to the instruction given below:

(i) Fill the four corners of the square matrix by character 1.

(ii) Fill the boundary elements of the matrix (except the four corners) by character 2.

(iii) Fill the non-boundary elements of the matrix by character 3.

Test your program with the following data and some random data:

Example 1:

INPUT: N = 4

FIRST CHARACTER: @

SECOND CHARACTER: ?

THIRD CHARACTER: #

OUTPUT:

@ ? ? @

? # # ?

? # # ?

@ ? ? @

Example 2:

INPUT: N = 5

FIRST CHARACTER: A

SECOND CHARACTER: C

THIRD CHARACTER: X

OUTPUT:

A C C C A

C X X X C

C X X X C

C X X X C

A C C C A

Example 3:

INPUT: N = 12

OUTPUT: SIZE OUT OF RANGE

Program [2]

Write a  program  to  declare  a  square  matrix  A[  ][  ]  of  order  MxM  where  'M'  is  the  number  of  rows  and  the  number  of  columns,  such  that  M  must  be  greater  than  2  and    less  than 10.  Accept  the  value  of  M  as  user  input.  Display  an  appropriate  message  for    an  invalid  input.  Allow  the  user  to  input  integers   into   this   matrix.   Perform   the   following tasks:

(a) Display the original matrix.

(b) Rotate the matrix 90° clockwise as shown below:

Original matrix

1 2 3

4 5 6

7 8 9

Rotated matrix

7 4 1

8 5 2

9 6 3

(c) Find the sum of the elements of the four comers of the matrix.

Test your program with the sample data and some random data: Example 1

INPUT : M = 3

3 4 9

2 5 8

1 6 7

OUTPUT :

ORIGINAL MATRIX

3 4 9

2 5 8

1 6 7

MATRIX AFTER ROTATION

1 2 3

6 5 4

7 8 9

Sum of the corner elements = 20

Example 2

INPUT : M = 4

1 2 4 9

2 5 8 3

1 6 7 4

3 7 6 5

OUTPUT :

ORIGINAL MATRIX

1 2 4 9

2 5 8 3

1 6 7 4

3 7 6 5

MATRIX AFTER ROTATION
3 1 2 1
7 6 5 2
6 7 8 4
5 4 3 9
Sum of the corner elements = 18