0% found this document useful (0 votes)
7 views

Arrays in C_modified

The document provides a comprehensive overview of arrays in C, detailing their declaration, initialization, and memory allocation. It covers both one-dimensional and multi-dimensional arrays, including examples of accessing elements, calculating sizes, and performing operations like matrix multiplication. Additionally, it includes code snippets to illustrate the concepts discussed.

Uploaded by

Shuhaib Cp
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Arrays in C_modified

The document provides a comprehensive overview of arrays in C, detailing their declaration, initialization, and memory allocation. It covers both one-dimensional and multi-dimensional arrays, including examples of accessing elements, calculating sizes, and performing operations like matrix multiplication. Additionally, it includes code snippets to illustrate the concepts discussed.

Uploaded by

Shuhaib Cp
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

Arrays in C

An array in C is a collection of data items of similar data type. One or more values same data
type, which may be primary data types (int, float, char), or user-defined types such as struct or
pointers can be stored in an array.
In C, the type of elements in the array should match with the data type of the array itself.
The size of the array, also called the length of the array, must be specified in the declaration
itself. Once declared, the size of a C array cannot be changed. When an array is declared, the
compiler allocates a continuous block of memory required to store the declared number of
elements.

Fig 1: Array Allocation in Memory


Array elements are stored in contiguous memory locations. Each element is identified by an
index starting with "0". The lowest address corresponds to the first element and the highest
address to the last element.

Declaration of an Array in C

Syntax: type arrayName[size];


The "size" must be an integer constant greater than zero and its "type" can be any valid C
data type.
#include <stdio.h>

int main(){
int arr[5];
int i;

for (i = 0; i <= 4; i++){


printf("a[%d]: %d\n", i, arr[i]);
}
return 0;
}

Output :

a[0]: -133071639
a[1]: 32767
a[2]: 100
a[3]: 0
a[4]: 4096
Initialization of an Array in C

At the time of declaring an array, you can initialize it by providing the set of comma-
separated values enclosed within the curly braces {}.
Syntax:
data_type array_name [size] = {value1, value2, value3, ...};
// Initialization of an integer array
#include <stdio.h>

int main()
{
int numbers[5] = {10, 20, 30, 40, 50};

int i; // loop counter

// Printing array elements


printf("The array elements are : ");
for (i = 0; i < 5; i++) {
printf("%d ", numbers[i]);
}

return 0;
}

Output

The array elements are : 10 20 30 40 50

Getting Size of an Array in C

The compiler allocates a continuous block of memory. The size of the allocated memory depends
on the data type of the array.
Example 1: Size of Integer Array
If an integer array of 5 elements is declared, the array size in number of bytes would be
"sizeof(int) x 5"

#include <stdio.h>

int main(){
int arr[5] = {1, 2, 3, 4, 5};
printf("Size of array: %ld", sizeof(arr));
return 0;
}
Output

Size of array: 20

Example 2 : Adjacent Address of Array Elements

#include <stdio.h>

int main(){
int a[] = {1, 2, 3, 4, 5};
int i;

for(i = 0; i < 4; i++){


printf("a[%d]: %d \t Address: %d\n", i, a[i], &a[i]);
}
return 0;
}

Output

a[0]: 1 Address: 2102703872


a[1]: 2 Address: 2102703876
a[2]: 3 Address: 2102703880
a[3]: 4 Address: 2102703884

Accessing Array Elements


Each element in an array is identified by a unique incrementing index, stating with "0". To
access the element by its index, this is done by placing the index of the element within square
brackets after the name of the array. The elements of an array are accessed by specifying the
index (offset) of the desired element within the square brackets after the array name.

Example 3 : Accessing array elements


#include <stdio.h>

int main(){

int n[5]; /* n is an array of 5 integers */


int i, j;

/* initialize elements of array n to 0 */


for(i = 0; i < 5; i++){
n[i] = i + 100;
}

/* output each array element's value */


for(j = 0; j < 5; j++){
printf("n[%d] = %d\n", j, n[j]);
}
return 0;
}

Output:

n[0] = 100
n[1] = 101
n[2] = 102
n[3] = 103
n[4] = 104

/* Program to store the marks of 10 students */


#include <stdio.h>

int main(){
int marks[10] = {50, 55, 67, 73, 45, 21, 39, 70, 49, 51};
int i, sum = 0;
float avg;

for (i = 0; i <= 9; i++){


sum += marks[i];
}
avg = (float)sum / 10;
printf("Average: %f", avg);
return 0;
}
Output :
Average: 52.000000
Multidimensional Arrays in C

Multi-dimensional arrays can be termed as nested arrays. In such a case, each


element in the outer array is an array itself. Such type of nesting can be upto any
level. If each element in the outer array is another one-dimensional array, it
forms a two-dimensional array. In turn, the inner array is an array of another set
of one dimensional array, it is a three-dimensional array, and so on.

Declaration of Multidimensional Arrays

Syntax: type name[size1][size2]...[sizeN];

A multidimensional array can have any number of dimensions. In this tutorial,


we will learn about the two commonly used types of multidimensional arrays:

1. Two-dimensional Array
2. Three-dimensional Array or higher dimensional arrays

Two-dimensional Array in C

A two-dimensional array in an array of one-dimensional arrays. Each element of


a two-dimensional array is an array itself. It is like a table or a matrix. The
elements can be considered to be logically arranged in rows and columns.
Hence, the location of any element is characterized by its row number and
column number. Both row and column index start from 0.

Declaration and Initialization of Two-dimensional Array

The following statement declares and initializes a two-dimensional array −

int arr[3][5] = {1,2,3,4,5, 10,20,30,40,50, 5,10,15,20,25};


or
int arr[ ][5] = {1,2,3,4,5, 10,20,30,40,50, 5,10,15,20,25};
The arr array has three rows and five columns. In C, a two dimensional array is a
row−major array. The first square bracket always represents the dimension size
of rows, and the second is the number of columns. Obviously, the array has 3 X
5 = 15 elements. The array is initialized with 15 comma−separated values put
inside the curly brackets. Elements are read into the array in a row−wise manner,
which means the first 5 elements are stored in first row, and so on. Hence, the
first dimension is optional in the array declaration.

To increase the readability, elements of each row can be optionally put in curly
brackets as follows −
int arr[ ][5] = {
{1,2,3,4,5},
{10,20,30,40,50},
{5,10,15,20,25}
};
The numbers are logically arranged in a tabular manner as follows –

Example 4 : Printing Elements of Two-dimensional Array

#include <stdio.h>
int main () {

/* an array with 5 rows and 2 columns*/


int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}};
int i, j;

/* output each array element's value */


for ( i = 0; i < 5; i++ ) {
for ( j = 0; j < 2; j++ ) {
printf("a[%d][%d] = %d\n", i,j, a[i][j] );
}
}

return 0;
}

Output:
a[0][0] = 0
a[0][1] = 0
a[1][0] = 1
a[1][1] = 2
a[2][0] = 2
a[2][1] = 4
a[3][0] = 3
a[3][1] = 6
a[4][0] = 4
a[4][1] = 8

In case of a two or multi-dimensional array, the compiler assigns a memory lock


of the size which is the product of dimensions multiplied by the size of the data
type. In this case, the size is 3 X 5 X 4 = 60 bytes, 4 being the size of int data
type. Even though all the elements are stored in consecutive memory locations,
we can print the elements in row and column format with the use of nested loops.

Example 5: Printing Two-dimensional Array as Matrix in Row and Columns

#include <stdio.h>

int main() {
int arr[3][5] = {1,2,3,4,5, 10,20,30,40,50, 5,10,15,20,25};
int i, j;

for (i=0; i<3; i++){

for (j=0; j<5; j++){


printf("%4d", arr[i][j]);
}
printf("\n");
}
return 0;
}

Output:
1 2 3 4 5
10 20 30 40 50
5 10 15 20 25

Row-wise Sum of Multidimensional Array's Elements


You can find the sum of all elements row-wise or column-wise by accessing the
elements using indices. In the case of a three-dimensional array, you need to use
depth, row, and column indices. And, in the case of a two-dimensional array, you
need to use row and column indices. Here, we are using a two-dimensional array.

Example 6: Row-wise Sum of Numbers


#include <stdio.h>
int main() {
int arr[3][5] = {{1,2,3,4,5}, {10,20,30,40,50}, {5,10,15,20,25}};
int i, j;
int sum;
for (i=0; i<3; i++){
sum=0;
for (j=0; j<5; j++){
sum+=arr[i][j];
}
printf("Sum of row %d: %d\n", i, sum);
}
return 0;
}

Output:
Sum of row 0: 15
Sum of row 1: 150
Sum of row 2: 75

Matrix Multiplication

Matrix algebra is a branch of mathematics, where a matrix is a 2D array of


numbers arranged in rows and columns. Multiplication of two matrices is possible
only if the number of columns of the first matrix is equal to the number of rows
of the second matrix. The product of two compatible matrices is equal to the dot
products between rows of the first matrix and columns of the second matrix. If
the two matrices are of size a[m][n] and b[p][q], the result of their multiplication
is a matrix of the size (the multiplication is possible only if n is equal to p) is
c[m][q].

Criteria : For two matrices to be multiplied, the number of columns of the first
matrix must be equal to the number of rows of the second matrix, and the resultant
matrix will be of the order r1x c2, where r1 is the number of rows of the first
matrix and c2 is the number of columns of the second matrix.
The product of two matrices is the sum of the products across some row of matrix
A with the corresponding entries down some column of matrix B.

Algorithm for Matrix Multiplication


1. Take r1 and c1 input from the user.
2. Take r1xc1 elements as input from the user. These are the elements of the
first matrix.
3. Take r2 and c2 input from the user.
4. Take r2xc2 elements as input from the user. These are the elements of the
second matrix.
5. Now check for matrix multiplication criteria i.e. check if c1 equals r2. If
they are not equal, print that the matrix multiplication is not possible and
exit from the program.
6. If they are equal, perform matrix multiplication by multiplying each
column with the corresponding row to get the corresponding row elements
of the resultant matrix.
7. Print the resultant matrix.
Example
Example 7: Matrix multiplication
# include<stdio.h>
int main(){
int mat1[3][3] = { {2, 4, 1} , {2, 3, 9} , {3, 1, 8} };
int mat2[3][3] = { {1, 2, 3} , {3, 6, 1} , {2, 4, 7} };
int mat3[3][3], sum=0, i, j, k;

for(i=0; i<3; i++){


for(j=0; j<3; j++){
sum=0;
for(k=0; k<3; k++)
sum = sum + mat1[i][k] * mat2[k][j];
mat3[i][j] = sum;
}
}
printf("\nMatrix 1 ...\n");
for(i=0; i<3; i++){
for(j=0; j<3; j++)
printf("%d\t", mat1[i][j]);
printf("\n");
}

printf("\nMatrix 2 ...\n");
for(i=0; i<3; i++){
for(j=0; j<3; j++)
printf("%d\t", mat2[i][j]);
printf("\n");
}

printf("\nMultiplication of the two given Matrices: \n");


for(i=0; i<3; i++){
for(j=0; j<3; j++)
printf("%d\t", mat3[i][j]);
printf("\n");
}

return 0;
}
Output:
Matrix 1 ...
2 4 1
2 3 9
3 1 8

Matrix 2 ...
1 2 3
3 6 1
2 4 7

Multiplication of the two given Matrices:


16 32 17
29 58 72
22 44 66

------------------------------------------------------------------------------------------------------------

# include <stdio.h>
# include <stdlib.h>
void input(int arr[][10], int m, int n) {
int i, j;
printf("\nEnter elements of matrix:\n");

for (i = 0; i < m; ++i) {


for (j = 0; j < n; ++j) {
printf("Enter elements a%d%d: ", i + 1, j + 1);
scanf("%d", & arr[i][j]);
}
}
}

void display(int arr[][10], int m, int n) {


int i, j;
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
printf("%d", arr[i][j]);
}
}
}

void multiply(int a[][10], int b[][10], int c[][10], int m, int n, int p, int q) {
int i, j, k;
for (i = 0; i < m; ++i) {
for (j = 0; j < q; ++j) {
c[i][j] = 0;
}
}
for (i = 0; i < m; ++i) {
for (j = 0; j < q; ++j) {
for (k = 0; k < n; ++k) {
c[i][j] += a[i][k] * b[k][j];
}
}
}
}
int main(){
int m, n, p, q, i, j, k;
int a[10][10], b[10][10], res[10][10];

printf("Enter the no of rows and cols of first matrix\n");


scanf("%d%d", & m, & n);
printf("Enter the number of rows and cols of the second matrix\n");
scanf("%d%d", & p, & q);

if (n != p) {
printf("Matrix is incompatible for multiplication\n");
} else {
printf("Enter the elements of Matrix-A:\n");
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
scanf("%d", & a[i][j]);
}
}

printf("Enter the elements of Matrix-B:\n");


for (i = 0; i < p; i++) {
for (j = 0; j < q; j++) {
scanf("%d", & b[i][j]);
}
}

for (i = 0; i < m; i++) {


for (j = 0; j < q; j++) {
res[i][j] = 0;
for (k = 0; k < p; k++) {
res[i][j] += a[i][k] * b[k][j];
}
}
}

printf("The product of the two matrices is:-\n");

for (i = 0; i < m; i++) {


for (j = 0; j < q; j++) {
printf("%d\t", res[i][j]);
}
printf("\n");
}
}

return 0;
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy