- 2072 Chaitra · 2+8 marks
String; replace diagonal by minimum
Short answer
A string is a character array terminated by '\0'. The program reads 9 integers into a 3x3 matrix using a pointer, finds the minimum value via pointer arithmetic, then sets all diagonal elements (positions where i=j) to that minimum, and prints the modified matrix.
What is a string? Write a program to read a 3*3 square matrix, find minimum integer value of a matrix, replace the diagonal elements by the minimum element and display it using pointer.
String
A string is a sequence of characters stored in a character array and ended by the null character '\0'. It is declared as char name[20]; and can be initialised as char name[] = "Nepal"; (6 bytes including '\0'). Strings are read with scanf("%s"), gets() or fgets(), printed with %s, and handled with <string.h> functions such as strlen, strcpy, strcmp and strcat.
Program
A pointer p is set to the first element of the matrix. A 2D array is stored row by row, so element a[i][j] is *(p + i*3 + j). The program finds the minimum with the pointer, puts it on the diagonal positions (i = j), and prints the matrix using the pointer.
#include <stdio.h>
int main(void)
{
int a[3][3], *p = &a[0][0], min;
printf("Enter 9 integers: ");
for (int i = 0; i < 9; i++)
scanf("%d", p + i); /* p + i is the address of element i */
min = *p;
for (int i = 1; i < 9; i++)
if (*(p + i) < min)
min = *(p + i);
for (int i = 0; i < 3; i++)
*(p + i * 3 + i) = min; /* a[i][i] = min */
printf("Minimum = %d\nMatrix after replacing the diagonal:\n", min);
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++)
printf("%4d", *(p + i * 3 + j));
printf("\n");
}
return 0;
}
Sample run (matrix 7 2 9 / 4 8 6 / 5 3 1)
Input: 7 2 9 4 8 6 5 3 1
Enter 9 integers: Minimum = 1
Matrix after replacing the diagonal:
1 2 9
4 1 6
5 3 1
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Reverse array and display via pointer · Computer Programming, chapter 9
- Copy string converting lower to upper using pointer · Computer Programming, chapter 9 · asked 3×
- Second largest element using pointer · Computer Programming, chapter 9
- Accessing array elements using pointer · Computer Programming, chapter 9
- Sum and average between M and N using pointer · Computer Programming, chapter 9
- Reverse a string using functions · Computer Programming, chapter 7 · asked 2×
- 8086 ALP: count vowels and display string · Microprocessor, chapter 3
- Derive CST element stiffness matrix · Finite Element Method, chapter 6
- Transition elements; non-typical 3d element · Engineering Chemistry, chapter 5
- Bar stiffness matrix and 2D truss element · Computational Techniques in Civil Engineering, chapter 4