C Program to Input an Array, Store the Squares of these Elements in an Array & Print it
This is a C program which inputs array & stores the squares of these elements in an array & print them.
1. Create a two-dimentional array of define its elements statically.
2. Run a for loop, the number of rows in this two-dimentional array times.
3. Inside this for loop, a function is called passing every row of the 2D array as a parameter(i.e passing 1D array).
4. Inside this function, value of every column of that row is multiplied by its own number, and stored in the same place, thus storing the square of the previously stored number.
5. Now print all the elements of the 2D array.
Here is source code of the C Program to input array & stores the of these elements in an array & print them. The program is successfully compiled and tested using Turbo C compiler in windows environment. The program output is also shown below.
/*
* C Program to Input an Array, Store the Squares of these Elements in an Array & Print it
*/
#include <stdio.h>
#define MAX_ROWS 3
#define MAX_COLS 4
void print_square(int [ ] );
void main (void)
{
int i;
int num [MAX_ROWS][MAX_COLS] = { {10, 20, 30, 40}, {50, 60, 70, 80}, {90, 100, 110, 120} };
for (i = 0; i < MAX_ROWS; i++)
print_square(num[i]);
}
void print_square(int x[ ])
{
int j;
for (j = 0; j < MAX_COLS; j++)
printf ("%d\t", x[j] * x[j]);
printf("\n");
}
1. Declare a 2D array of some fixed row and column size (lets say 3 and 4 respectively).
2. Define all its elements at the time of declaration.
3. Run a for loop from 0 to row-1, sending each row of the 2D array in the function printSquare() as its parameter.
4. Inside this function, again a loop runs to access all the column values of the given row.
5. Thus the loop runs from 0 to column-1, accessing each column value, evaluating its square, storing the result at the same place.
6. Now, print the array.
100 400 900 1600 2500 3600 4900 6400 8100 10000 12100 14400
Sanfoundry Global Education & Learning Series – 1000 C Programs.
Here’s the list of Best Books in C Programming, Data Structures and Algorithms.
- Practice Computer Science MCQs
- Apply for Computer Science Internship
- Watch Advanced C Programming Videos
- Check Computer Science Books
- Apply for C Internship