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

Unit-4 array computer programming

The document provides a comprehensive overview of arrays, including one-dimensional and multi-dimensional arrays, their advantages, types, and applications. It covers array declaration, initialization, element access, updating, traversing, inserting, deleting, and merging operations, along with examples in C programming. Additionally, it discusses sorting algorithms, specifically bubble sort, and provides sample code for various array operations.

Uploaded by

saransh8998
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)
3 views

Unit-4 array computer programming

The document provides a comprehensive overview of arrays, including one-dimensional and multi-dimensional arrays, their advantages, types, and applications. It covers array declaration, initialization, element access, updating, traversing, inserting, deleting, and merging operations, along with examples in C programming. Additionally, it discusses sorting algorithms, specifically bubble sort, and provides sample code for various array operations.

Uploaded by

saransh8998
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/ 33

Unit- 4

Array

Concept of one dimensional and multi – dimensional array: Array is a linear data
structure where all elements are arranged sequentially. It is a collection of elements of same
data type stored at contiguous memory locations.

The main advantage of the array is random access and cache friendliness. There are mainly
three types of the array:
 One Dimensional (1D) Array
 Two Dimension (2D) Array
 Multidimensional Array
One Dimensional Array:
 It is a list of the variable of similar data types.
 It allows random access and all the elements can be accessed with the help of their index.
 The size of the array is fixed.
 For a dynamically sized array, vector can be used in C++.
 Representation of 1D array:

Two Dimensional Array:


 It is a list of lists of the variable of the same data type.
 It also allows random access and all the elements can be accessed with the help of their
index.
 It can also be seen as a collection of 1D arrays. It is also known as the Matrix.
 Its dimension can be increased from 2 to 3 and 4 so on.
 They all are referred to as a multi-dimension array.
 The most common multidimensional array is a 2D array.
 Representation of 2 D array:

Difference Table:

Basis One Dimension Array Two Dimension Array

Store a single list of the


Store a ‘list of lists’ of the element of a
Definition element of a similar data
similar data type.
type.

Represent multiple data Represent multiple data items as a table


Representation
items as a list. consisting of rows and columns.

The declaration varies for


different programming The declaration varies for different
language: programming language:
1. For C++, 1. For C++,
datatype datatype
Declaration
variable_name[row] variable_name[row][column]
2. For Java, 2. For Java,
datatype [] datatype [][] variable_name= new
variable_name= new datatype[row][column]
datatype[row]

Dimension One Two


Basis One Dimension Array Two Dimension Array

size of(datatype of the size of (datatype of the variable of the


Size(bytes) variable of the array) * size array)* the number of rows* the number
of the array of columns.

Address of a[i][j] can be calculated in


two ways row-major and column-major
1. Column Major: Base Address +
Size of each element (number of
Address of a [index] is
rows(j-lower bound of the
Address equal to (base Address+
column)+(i-lower bound of the
calculation. Size of each element of
rows))
array * index).
2. Row Major: Base Address + Size of
each element (number of columns(i-
lower bound of the row)+(j-lower
bound of the column))

int arr[5]; //an array with int arr[2][5]; //an array with two rows
one row and five columns and five columns will be created.
Example
will be created. a b c d e
{a , b , c , d , e} f g h i j

Applications of Arrays:
 2D Arrays are used to implement matrices.
 Arrays can be used to implement various data structures like a heap, stack, queue, etc.
 They allow random access.
 They are cache-friendly.

Syntax of Array Declaration


data_type array_name [size];
or
data_type array_name [size1] [size2]...[sizeN];
where N is the number of dimensions.
Example of Array Declaration
// declaring array of integers
int arr_int[5];

// declaring array of characters


char arr_char[5];
Array Initialization with Declaration:
data_type array_name [size] = {value1, value2, ... valueN};

3. Array Initialization with Declaration without Size

data_type array_name[] = {1,2,3,4,5};

4. Array Initialization after Declaration (Using Loops)

for (int i = 0; i < N; i++) {


array_name[i] = valuei;
}
ex.
// C Program to illustrate element access using array
// subscript
#include <stdio.h>
int main()
{

// array declaration and initialization


int arr[5] = { 15, 25, 35, 45, 55 };

// accessing element at index 2 i.e 3rd element


printf("Element at arr[2]: %d\n", arr[2]);

// accessing element at index 4 i.e last element


printf("Element at arr[4]: %d\n", arr[4]);

// accessing element at index 0 i.e first element


printf("Element at arr[0]: %d", arr[0]);

return 0;
}

Update Array Element:


We can update the value of an element at the given index i in a similar way to accessing an
element by using the array subscript operator [ ] and assignment operator =
.
array_name[i] = new_value;
C Array Traversal
Traversal is the process in which we visit every element of the data structure. For C array
traversal, we use loops to iterate through each element of the array.

Array Traversal using for Loop


for (int i = 0; i < N; i++) {
array_name[i];
}

Example:
// C Program to demonstrate the use of array
#include <stdio.h>
int main()
{
// array declaration and initialization
int arr[5] = { 10, 20, 30, 40, 50 };

// modifying element at index 2


arr[2] = 100;

// traversing array using for loop


printf("Elements in Array: ");
for (int i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}

return 0;
}

Output
Elements in Array: 10 20 100 40 50

Example of 1D Array in C
// C Program to illustrate the use of 1D array
#include <stdio.h>

int main()
{

// 1d array declaration
int arr[5];

// 1d array initialization using for loop


for (int i = 0; i < 5; i++) {
arr[i] = i * i - 2 * i + 1;
}

printf("Elements of Array: ");


// printing 1d array by traversing using for loop
for (int i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}

return 0;
}
Output
Elements of Array: 1 0 1 4 9

Example of 2D Array in C
// C Program to illustrate 2d array
#include <stdio.h>

int main()
{

// declaring and initializing 2d array


int arr[2][3] = { 10, 20, 30, 40, 50, 60 };

printf("2D Array:\n");
// printing 2d array
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ",arr[i][j]);
}
printf("\n");
}

return 0;
}

Output
2D Array:
10 20 30
40 50 60
B. Three-Dimensional Array in C
Another popular form of a multi-dimensional array is Three Dimensional Array or 3D Array. A
3D array has exactly three dimensions. It can be visualized as a collection of 2D arrays stacked
on top of each other to create the third dimension.
Syntax of 3D Array in C
array_name [size1] [size2] [size3];
Example of 3D Array
// C Program to illustrate the 3d array
#include <stdio.h>

int main()
{

// 3D array declaration
int arr[2][2][2] = { 10, 20, 30, 40, 50, 60 };

// printing elements
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
for (int k = 0; k < 2; k++) {
printf("%d ", arr[i][j][k]);
}
printf("\n");
}
printf("\n \n");
}
return 0;
}

Output
10 20
30 40

50 60
00
Inserting an Element into an Array
Insertion is the process of adding a new element at a specified position in the array. Here’s how
we can achieve this in C.

Example Code

#include <stdio.h>

void insert(int arr[], int *n, int pos, int value) {

for (int i = *n; i > pos; i--) {

arr[i] = arr[i - 1];

arr[pos] = value;

(*n)++;

int main() {

int arr[10] = {1, 2, 4, 5};

int n = 4;

int pos = 2;

int value = 3;

insert(arr, &n, pos, value);


for (int i = 0; i < n; i++) {

printf("%d ", arr[i]);

return 0;

Explanation

1. Header File Inclusion


#include <stdio.h>

This line includes the standard input-output header file necessary for using printf and other
standard I/O functions.

2. Insert Function Definition


void insert(int arr[], int *n, int pos, int value) {

for (int i = *n; i > pos; i--) {

arr[i] = arr[i - 1];

arr[pos] = value;

(*n)++;

 The insert function takes four parameters:


 arr[]: The array where the new value will be inserted.
 *n: A pointer to an integer representing the current size of the array.
 pos: The position at which the new value should be inserted.
 value: The value to be inserted into the array.
2. Deleting an Element from an Array
Deletion is the process of removing an element from a specified position in the array.

Example Code

#include <stdio.h>

void delete(int arr[], int *n, int pos) {

for (int i = pos; i < *n - 1; i++) {

arr[i] = arr[i + 1];

(*n)--;

int main() {

int arr[10] = {1, 2, 3, 4, 5};

int n = 5;

int pos = 2;

delete(arr, &n, pos);

for (int i = 0; i < n; i++) {


printf("%d ", arr[i]);

return 0;

Explanation

1. Delete Function Definition


void delete(int arr[], int *n, int pos) {

for (int i = pos; i < *n - 1; i++) {

arr[i] = arr[i + 1];

(*n)--;

 The delete function takes three parameters:


 arr[]: The array from which the value will be deleted.
 *n: A pointer to an integer representing the current size of the array.
 pos: The position of the value to be deleted.
3. Traversing an Array
Traversal is the process of accessing each element of the array exactly once.

Example Code

#include <stdio.h>

void traverse(int arr[], int n) {


for (int i = 0; i < n; i++) {

printf("%d ", arr[i]);

printf("\n");

int main() {

int arr[5] = {1, 2, 3, 4, 5};

int n = 5;

traverse(arr, n);

return 0;

Explanation
1. Traverse Function Definition
void traverse(int arr[], int n) {

for (int i = 0; i < n; i++) {

printf("%d ", arr[i]);

printf("\n");
}

 The traverse function takes two parameters:


 arr[]: The array to be traversed.
 n: The size of the array.
4.Merge operations: Merging two arrays means combining/concatenating the elements of both
arrays into a single array.
Example
Input: arr1 = [1, 3, 5], arr2 = [2, 4, 6]
Output: res = [1, 3, 5, 2, 4, 6]
Explanation: The elements from both arrays are merged into a single array.
Input: arr1 = [10, 40, 30], arr2 = [15, 25, 5]
Output: res = [10, 40, 30, 15, 25, 5]
Explanation: Elements from both arrays are merged into a single array.

// C program to merge two arrays into a new array using


// memcpy()
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int* mergeArrays(int arr1[], int n1, int arr2[], int n2) {

// Resultant array to store merged array


int *res = (int*)malloc(sizeof(int) * n1 * n2);

// Copy elements of the first array


memcpy(res, arr1, n1 * sizeof(int));

// Copy elements of the second array


memcpy(res + n1, arr2, n2 * sizeof(int));

return res;
}

int main() {
int arr1[] = {1, 3, 5};
int arr2[] = {2, 4, 6};
int n1 = sizeof(arr1) / sizeof(arr1[0]);
int n2 = sizeof(arr2) / sizeof(arr2[0]);

// Merge arr1 and arr2


int* res = mergeArrays(arr1, n1, arr2, n2);

for (int i = 0; i < n1 + n2; i++)


printf("%d ", res[i]);

return 0;
}

Output
135246

Program to find sum of elements


in a given array using recursion
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// function to return sum of elements


// in an array of size n
int sum(int arr[], int n)
{
// base case
if (n == 0) {
return 0;
}
else {
// recursively calling the function
return arr[0] + sum(arr + 1, n - 1);
}
}

int main()
{
int arr[] = { 12, 3, 4, 15 };
int n = sizeof(arr) / sizeof(arr[0]);

printf("%d", sum(arr, n));

return 0;
}

Write a program to find the largest number in an array

#include <stdio.h>

int largest(int arr[], int n) {


int i;
int max = arr[0];
// Traverse array elements from second and
// compare every element with current max
for (i = 1; i < n; i++)
if (arr[i] > max)
max = arr[i];

return max;
}

int main() {
int arr[] = { 10, 324, 45, 90, 9808 };
int n = sizeof(arr) / sizeof(arr[0]);

printf("%d", largest(arr, n));


return 0;
}

Sorting: Sorting refers to ordering data in an increasing or decreasing manner according to some
linear relationship among the data items. ordering: arranging items in a sequence ordered by
some criterion; categorizing: grouping items with similar properties.

Bubble sort: Bubble Sort is a comparison based simple sorting algorithm that works by
comparing the adjacent elements and swapping them if the elements are not in the correct
order. It is an in-place and stable sorting algorithm that can sort items in data structures such as
arrays and linked lists.
Bubble Sort Algorithm:
 Compare and swap the adjacent elements if they are in the wrong order starting from the
first two elements.
 Do that for all elements moving from left to right. We will get the largest element at the
right end.
 Start compare and swap again from the start but this time, skip the last element as its
already at correct position.
 The second last element will be moved at the right end just before the last element.
 Repeat the above steps till all the elements are sorted.

// C program for implementation of Bubble sort


#include <stdio.h>

void swap(int* arr, int i, int j) {


int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}

void bubbleSort(int arr[], int n) {


for (int i = 0; i < n - 1; i++) {

// Last i elements are already in place, so the loop


// will only num n - i - 1 times
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1])
swap(arr, j, j + 1);
}
}
}

int main() {
int arr[] = { 6, 0, 3, 5 };
int n = sizeof(arr) / sizeof(arr[0]);

// Calling bubble sort on array arr


bubbleSort(arr, n);

for (int i = 0; i < n; i++)


printf("%d ", arr[i]);

return 0;
}

Output
0356

Merge sort: It is a comparison-based sorting algorithm that works by dividing the input array
into two halves, then calling itself for these two halves, and finally it merges the two sorted
halves.
It is based on the three principles: divide, conquer and combine which is better implemented
using recursion using two functions:
1. mergeSort() – For Divide
2. merge() – For Conquer and Combine

// C program for the implementation of merge sort


#include <stdio.h>
#include <stdlib.h>

// Merges two subarrays of arr[].


// First subarray is arr[left..mid]
// Second subarray is arr[mid+1..right]
void merge(int arr[], int left, int mid, int right) {
int i, j, k;
int n1 = mid - left + 1;
int n2 = right - mid;
// Create temporary arrays
int leftArr[n1], rightArr[n2];

// Copy data to temporary arrays


for (i = 0; i < n1; i++)
leftArr[i] = arr[left + i];
for (j = 0; j < n2; j++)
rightArr[j] = arr[mid + 1 + j];

// Merge the temporary arrays back into arr[left..right]


i = 0;
j = 0;
k = left;
while (i < n1 && j < n2) {
if (leftArr[i] <= rightArr[j]) {
arr[k] = leftArr[i];
i++;
}
else {
arr[k] = rightArr[j];
j++;
}
k++;
}

// Copy the remaining elements of leftArr[], if any


while (i < n1) {
arr[k] = leftArr[i];
i++;
k++;
}

// Copy the remaining elements of rightArr[], if any


while (j < n2) {
arr[k] = rightArr[j];
j++;
k++;
}
}

// The subarray to be sorted is in the index range [left-right]


void mergeSort(int arr[], int left, int right) {
if (left < right) {

// Calculate the midpoint


int mid = left + (right - left) / 2;

// Sort first and second halves


mergeSort(arr, left, mid);
mergeSort(arr, mid + 1, right);

// Merge the sorted halves


merge(arr, left, mid, right);
}
}

int main() {
int arr[] = { 12, 11, 13, 5, 6, 7 };
int n = sizeof(arr) / sizeof(arr[0]);

// Sorting arr using mergesort


mergeSort(arr, 0, n - 1);

for (int i = 0; i < n; i++)


printf("%d ", arr[i]);
return 0;
}

Output
Given array is
12 11 13 5 6 7

Insertion sort: It is a simple sorting algorithm used to sort a collection of elements in a given
order. It is less efficient on large lists than more advanced algorithms such as quicksort, heap
sort, or merge sort but it is simple to implement and is suitable to sort small data lists.
Insertion Sort Algorithm in C
 Start with the second element (index 1) as the key.
 Compare the key with the elements before it.
 If the key is smaller than the compared element, shift the compared element one position
to the right.
 Insert the key where the shifting of elements stops.
 Repeat steps 2-4 for all elements in the unsorted part of the list.

// C program to implement insertion sort


#include <math.h>
#include <stdio.h>

void insertionSort(int arr[], int N) {

// Starting from the second element


for (int i = 1; i < N; i++) {
int key = arr[i];
int j = i - 1;

// Move elements of arr[0..i-1], that are


// greater than key, to one position to
// the right of their current position
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}

// Move the key to its correct position


arr[j + 1] = key;
}
}

int main() {
int arr[] = { 12, 11, 13, 5, 6 };
int N = sizeof(arr) / sizeof(arr[0]);

printf("Unsorted array: ");


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

// Calling insertion sort on array arr


insertionSort(arr, N);

printf("Sorted array: ");


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

return 0;
}

Output
Unsorted array: 12 11 13 5 6
Sorted array: 5 6 11 12 13

Character array and string: String is a sequence of characters that are treated as a single data
item and terminated by a null character '\0'. Remember that the C language does not support
strings as a data type. A string is actually a one-dimensional array of characters in C language.
These are often used to create meaningful and readable programs.

Declaring and Initializing String variables in C:

// valid

char name[13] = "StudyTonight";

char name[10] = {'c','o','d','e','\0'};

// Illegal

char ch[3] = "hello";

char str[4];

str = "hello";

String Input and Output in C

 %s format specifier to read a string input from the terminal.


 But scanf() function, terminates its input on the first white space it encounters.
 edit set conversion code %[..] that can be used to read a line containing a variety of
characters, including white spaces.
 The gets() function can also be used to read character string with white spaces

Code example:

char str[20];

printf("Enter a string");

scanf("%[^\n]", &str);

printf("%s", str);
We can also ue gets function to get the string as input.

char text[20];

gets(text);

printf("%s", text);

String Handling Functions in C

C language supports a large number of string handling functions that can be used to carry out
many of the string manipulations. These functions are packaged in the string.h library. Hence,
you must include string.h header file in your programs to use these functions.

The following are the most commonly used string handling functions.

Method Description

strcat() It is used to concatenate(combine) two strings

strlen() It is used to show the length of a string

strrev() It is used to show the reverse of a string

strcpy() Copies one string into another


strcmp() It is used to compare two string

There are many more String functions, but in this tutorial we will learn how to use the above
mentioned string functions.

1. strcat() function
Syntax is:

strcat("hello", "world");

strcat() will add the string "world" to "hello" i.e ouput = helloworld.

2. strlen() and strcmp() function


strlen() will return the length of the string passed to it and strcmp() will return the ASCII
difference between first unmatching character of two strings.

int j = strlen("studytonight");

int i=strcmp("study ", "tonight");

printf("%d %d",j,i);

12 -1

3. strcpy() function
It copies the second string argument to the first string argument.

let's see an example of strcpy() function,

#include<stdio.h>

#include<string.h>
int main()

char s1[50], s2[50];

strcpy(s1, "StudyTonight");

strcpy(s2, s1);

printf("%s\n", s2);

return(0);

StudyTonight

4. strrev() function:
It is used to reverse the given string expression.

Code snippet for strrev():

#include <stdio.h>

int main()

{
char s1[50];

printf("Enter your string: ");

gets(s1);

printf("\nYour reverse string is: %s",strrev(s1));

return(0);

Enter your string: studytonight

Your reverse string is: thginotyduy

Arithmetic operations on strings: Character arithmetic is used to implement arithmetic


operations like addition, subtraction, multiplication, and division on characters in C language.
In character arithmetic character converts into an integer value to perform the task. For this
ASCII value is used.
It is used to perform actions on the strings.

Example:

// C program to demonstrate character arithmetic.

#include <stdio.h>

int main()

{
char ch1 = 125, ch2 = 10;

ch1 = ch1 + ch2;

printf("%d\n", ch1);

printf("%c\n", ch1 - ch2 - 4);

return 0;

Output
-121
y

ex.

#include <stdio.h>

int main()

char a = 'A';

char b = 'B';

printf("a = %c\n", a);


printf("b = %c\n", b);

printf("a + b = %c\n", a + b);

return 0;

Output
a=A
b=B
a+b=â

String handling function: The C string functions are built-in functions that can be used for
various operations and manipulations on strings. These string functions make it easier to perform
tasks such as string copy, concatenation, comparison, length, etc. The <string.h> header file
contains these string functions.

Function Description Syntax

Find the length of a string excluding ‘\0’ NULL


strlen(str);
strlen() character.

strcpy() Copies a string from the source to the destination. strcpy(dest, src);

strncpy( dest, src, n


Copies n characters from source to the destination.
strncpy() );

strcat() Concatenate one string to the end of another. strcat(dest, src);

Concatenate n characters from the string pointed to


strncat(dest, src, n);
strncat() by src to the end of the string pointed to by dest.

strcmp() Compares these two strings lexicographically. strcmp(s1, s2);


Compares first n characters from the two strings
strncmp(s1, s2, n);
strncmp() lexicographically.

strchr() Find the first occurrence of a character in a string. strchr(s, c);

strrchr() Find the last occurrence of a character in a string. strchr(s, ch);

strstr() First occurrence of a substring in another string. strstr(s, subS);

sprintf(s, format,
Format a string and store it in a string buffer.
sprintf() …);

Split a string into tokens based on specified


strtok() delimiters.

Applications of pointers: Pointers in C are variables that are used to store the memory address
of another variable. Pointers allow us to efficiently manage the memory and hence optimize
our program.
C Pointers Application
The following are some major applications of pointers in the C programming language:
1. Passing Arguments by Reference
Passing arguments by reference serves two purposes:
i.) to modify the variable in another function.
Example
The below example demonstrates the use of pointers by swapping two numbers.
// C program to demonstrate that we can change
// local values of one function in another using pointers.

#include <stdio.h>

void swap(int* x, int* y)


{
int temp = *x;
*x = *y;
*y = temp;
}

int main()
{
int x = 10, y = 20;
swap(&x, &y);
printf("%d %d\n", x, y);
return 0;
}

Output
20 10
ii.) For Efficiency Purpose
Example
The below example demonstrates the use of pointers to write efficient code.
#include <stdio.h>

// function to print an array by passing reference to array


void printArray(int* arr, int n)
{
// here array elements are passed by reference
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
}

int main()
{
int arr[5] = { 1, 2, 3, 4, 5 };
printArray(arr, 5);
return 0;
}

Output
12345
Note: Passing large structure without reference would create a copy of the structure (hence
wastage of space).
2. For Accessing Array Elements
Compiler internally uses pointers to access array elements. We can also use these pointers to
access and modify the elements of the given array.
Example
The below example demonstrate the use of pointers to access elements of an array.
// C program to demonstrate that compiler
// internally uses pointer arithmetic to access
// array elements.

#include <stdio.h>

int main()
{
int arr[] = { 100, 200, 300, 400 };

// Compiler converts below to *(arr + 2).


printf("%d ", arr[2]);

// So below also works.


printf("%d\n", *(arr + 2));

return 0;
}

Output
300 300
3. To Return Multiple Values
The functions in C can only return a single value, but we can use pointers to return multiple
values from a C function.
Example
The below example demonstrates the use of pointers to return square and square root of
numbers using pointers.
// C program to demonstrate that using a pointer
// we can return multiple values.

#include <math.h>
#include <stdio.h>

void fun(int n, int* square, double* sq_root)


{
*square = n * n;
*sq_root = sqrt(n);
}

int main()
{

int n = 100;
int sq;
double sq_root;
fun(n, &sq, &sq_root);

printf("%d %f\n", sq, sq_root);


return 0;
}
Output:
10000
10
4. For dynamic memory Allocation
We can use pointers to dynamically allocate memory i.e Dynamic memory allocation. The
advantage of dynamically allocated memory is, it is not deleted until we explicitly delete it.
Example
The below example shows the use of pointers to dynamically allocate memory.
// C program to dynamically allocate an
// array of given size.

#include <stdio.h>
#include <stdlib.h>
int* createArr(int n)
{
int* arr = (int*)(malloc(n * sizeof(int)));
return arr;
}

int main()
{
int* pt = createArr(10);
return 0;
}

Function on array: Pass arrays to a function in C

In C programming, you can pass an entire array to functions. Before we learn that, let's see how
you can pass individual elements of an array to functions.

Pass Individual Array Elements

Passing array elements to a function is similar to passing variables to a function.


Example 1: Pass Individual Array Elements
#include <stdio.h>
void display(int age1, int age2) {
printf("%d\n", age1);
printf("%d\n", age2);
}

int main() {
int ageArray[] = {2, 8, 4, 12};

// pass second and third elements to display()


display(ageArray[1], ageArray[2]);
return 0;
}
Run Code

Output

Here, we have passed array parameters to the display() function in the same way we pass
variables to a function.

// pass second and third elements to display()


display(ageArray[1], ageArray[2]);

We can see this in the function definition, where the function parameters are individual
variables:

void display(int age1, int age2) {


// code
}
Example 2: Pass Arrays to Functions

// Program to calculate the sum of array elements by passing to a function

#include <stdio.h>
float calculateSum(float num[]);

int main() {
float result, num[] = {23.4, 55, 22.6, 3, 40.5, 18};

// num array is passed to calculateSum()


result = calculateSum(num);
printf("Result = %.2f", result);
return 0;
}

float calculateSum(float num[]) {


float sum = 0.0;

for (int i = 0; i < 6; ++i) {


sum += num[i];
}

return sum;
}
Run Code

Output

Result = 162.50

To pass an entire array to a function, only the name of the array is passed as an argument.

result = calculateSum(num);

You might also like