Write a C program to read a 2D array of N*M class numbers and print square elements of 2D array using pointers and functions.Sample Input2 3(Read row and column size)1 2 32 1 2Sample Output1 4 94 1 4
Question
Write a C program to read a 2D array of N*M class numbers and print square elements of 2D array using pointers and functions.Sample Input2 3(Read row and column size)1 2 32 1 2Sample Output1 4 94 1 4
Solution
Sure, here is a simple C program that reads a 2D array of N*M class numbers and prints the square of each element using pointers and functions.
#include <stdio.h>
#include <stdlib.h>
void read_matrix(int *arr, int m, int n) {
for(int i=0; i<m; i++) {
for(int j=0; j<n; j++) {
printf("Enter element at [%d][%d]: ", i, j);
scanf("%d", (arr + i*n + j));
}
}
}
void print_squares(int *arr, int m, int n) {
for(int i=0; i<m; i++) {
for(int j=0; j<n; j++) {
printf("%d ", (*(arr + i*n + j)) * (*(arr + i*n + j)));
}
printf("\n");
}
}
int main() {
int m, n;
printf("Enter number of rows: ");
scanf("%d", &m);
printf("Enter number of columns: ");
scanf("%d", &n);
int *arr = (int *)malloc(m * n * sizeof(int));
read_matrix(arr, m, n);
print_squares(arr, m, n);
free(arr);
return 0;
}
This program first reads the number of rows and columns from the user. It then dynamically allocates memory for a 2D array using the malloc function. The read_matrix function is used to read the elements of the array from the user. The print_squares function is used to print the square of each element in the array. Finally, the allocated memory is freed using the free function.
Similar Questions
#include<stdio.h> int main() { int rows,i,j,count=1,space; printf("Enter number of rows : "); scanf("%d",&rows); for(i=1;i<=rows;i++) { for(space=1;space<=rows-i;space++); { printf(" "); } for(j=1;j<=1;j++) {printf("%2d",count++);} printf(" "); } return 0; }
How do you initialize a 2D array in C?
If A is an m x n matrix then AT (Transpose of A) is an n x m matrix, such that rows of A become columns of AT and columns of A become rows of AT.Given a 2D array, you have to implement the given function,int** Transpose(int** matrix, int rowCount, int columnCount);Implement the function to find the transpose of the matrix and return the new matrix as output.Input:matrix:2 46 8Output:2 64 8Explanation: Values 2 and 4 in the first row become the first column in the returned matrix.Similarly, values 6 and 8 in the second row become the second column in the returned matrix.Sample inputmatrix:1 2 3 4 5 6Sample Output1 4 2 5 3 6
What is the correct way to declare a 2D array in C?
Create an array of integers, then create an array of pointers pointing to each element in the integer array. Print the values using both arrays. Write the code in c
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.