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

pps_Array

The document discusses the concept of arrays in C programming, highlighting their importance for managing large sets of data efficiently. It covers array declaration, initialization, element access, and traversal, along with the benefits and disadvantages of using arrays. Additionally, it emphasizes the role of arrays in data manipulation and efficient algorithm implementation.

Uploaded by

amitabhjain002
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

pps_Array

The document discusses the concept of arrays in C programming, highlighting their importance for managing large sets of data efficiently. It covers array declaration, initialization, element access, and traversal, along with the benefits and disadvantages of using arrays. Additionally, it emphasizes the role of arrays in data manipulation and efficient algorithm implementation.

Uploaded by

amitabhjain002
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

12/4/2023

Why do we need arrays?


 We can use normal variables (v1, v2, v3, ..) when we have
small number of objects,
ARRAY IN C but if we want to store large number of instances, it
becomes difficult to manage them with normal variables.

The idea of array is to represent many instances in one


Dr. Sumit Srivastava variable.
Dept. of CSE, BIT Mesra Ranchi
Email:- [email protected]

Sumit Srivastav @ BIT Mesra

1 2

Array Arrays
An array is an ordered list of values
 An array is a collection of data elements that are of the
same type (e.g., a collection of integers, collection of The entire array Each value has a numeric index
has a single name
characters, collection of doubles). 0 1 2 3 4 5 6 7 8 9

scores 79 87 94 82 67 98 87 81 74 91
 Arrays are referred to as structured data types. An array is
defined as finite, ordered collection of homogenous data, An array of size N is indexed from zero to N-1

stored in contiguous memory locations. This array holds 10 values that are indexed from 0 to 9

Sumit Srivastav @ BIT Mesra 3 24-01-2019

3 4
12/4/2023

Arrays Declaration of an Array


A particular value in an array is referenced using the array
Syntax of Array Declaration
name followed by the index in brackets
data_type array_name [size];
For example, or
the expression data_type array_name [size1] [size2]...[sizeN];

scores[2]
where N is the number of dimensions.
refers to the value 94 (the 3rd value in the array)

That expression represents a place to store a single integer and can


be used wherever an integer variable can be used

5 6

Declaration of an Array Declaring an Array


data-type variable-name[size];

Example

int arr[10]; Right

int m;
int array[m]; Wrong
The C arrays are static in nature, i.e., they are allocated memory at the
compile time.

7 8
12/4/2023

Declaring an Array Example of Array Declaration


// C Program to illustrate the array declaration
#include<stdio.h> #include<stdio.h> #include <stdio.h>
main() #define MAX 100
int main()
{ main()
{
int n; {
int a[MAX]; // declaring array of integers
scanf("%d", &n);
printf("%d",sizeof(a)); int arr_int[5];
printf("n=%d\n",n); // declaring array of characters
}
int a[n]; char arr_char[5];
printf("%d",sizeof(a));
return 0;
} }

9 10

Initialization of an Array Array Initialization with Declaration

 When the array is declared or allocated memory, the elements of the Use an initializer list to initialize multiple elements of the array.
array contain some garbage value. So, we need to initialize the array
An initializer list is the list of values enclosed within braces { }
to some meaningful value.
separated b a comma.

 There are multiple ways in which we can initialize an array in C.

1. Array Initialization with Declaration data_type array_name [size] = {value1, value2, ... valueN};

2. Array Initialization with Declaration without Size

3. Array Initialization after Declaration (Using Loops)

11 12
12/4/2023

Array Initialization with Declaration Array Initialization with Declaration without Size

data_type array_name [size] = {value1, value2, ... valueN};  If we initialize an array using an initializer list, we can skip
declaring the size of the array as the compiler can
automatically deduce the size of the array in these cases.

 The size of the array in these cases is equal to the number of


elements present in the initializer list as the compiler can
automatically deduce the size of the array.

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


The size of the above arrays is 5 which is automatically deduced by the compiler.

13 14

Array Initialization after Declaration (Using Loops)


Example of Array Initialization
#include <stdio.h>
 We initialize the array after the declaration by assigning the
int main()
initial value to each element individually. {

// array initialization using initialier list


 We can use for loop, while loop, or do-while loop to assign int arr[5] = { 10, 20, 30, 40, 50 };

the value to each element of the array. // array initialization using initializer list without specifying
size
int arr1[] = { 1, 2, 3, 4, 5 };
for (int i = 0; i < N; i++)
// array initialization using for loop
{
float arr2[5];
array_name[i] = valuei; for (int i = 0; i < 5; i++) {
} arr2[i] = (float)i * 2.1;
}
return 0; }

15 16
12/4/2023

Access the Elements of an Array Access the Elements of an Array


To access an array element, refer to its index number.
To access an array element, refer to its index number.
 Array indexes start with 0: [0] is the first element. [1] is the
second element, etc.

 This statement accesses the value of the first element [0] in


myNumbers:

 Example
int myNumbers[] = {25, 50, 75, 100};
printf("%d", myNumbers[0]);

// Outputs 25

17 18

Example Change an Array Element


#include <stdio.h>
To change the value of a specific element, refer to the index
int main() { number.
Output:
// array declaration and initialization array_name[i] = new_value;
int arr[5] = { 15, 25, 35, 45, 55 };
Element at arr[2]: 35
 Example
// accessing element at index 2 i.e 3rd element
printf("Element at arr[2]: %d\n", arr[2]); Element at arr[4]: 55

// accessing element at index 4 i.e last element int myNumbers[] = {25, 50, 75, 100};
printf("Element at arr[4]: %d\n", arr[4]); Element at arr[0]: 15
myNumbers[0] = 33;
printf("%d", myNumbers[0]);
// accessing element at index 0 i.e first element
printf("Element at arr[0]: %d", arr[0]);
// Now outputs 33 instead of 25
return 0; }

19 20
12/4/2023

Set Array Size Set Array Size (Example)


Another common way to create arrays, is to specify the #include <stdio.h>
// Outputs 25
size of the array, and add elements later . int main() {
// Declare an array of four integers:
 Example int myNumbers[4];
// Declare an array of four integers:
int myNumbers[4];
// Add elements to it
myNumbers[0] = 25;
myNumbers[1] = 50;
// Add elements myNumbers[2] = 75;
myNumbers[3] = 100;
myNumbers[0] = 25;
myNumbers[1] = 50; printf("%d\n", myNumbers[0]);
myNumbers[2] = 75;
return 0;
myNumbers[3] = 100;
}

21 22

Array Traversal 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];
}

23 24
12/4/2023

Loop Through an Array Loop Through an Array


You can loop through the array elements with the for loop. You can loop through the array elements with the for loop.
 The following example outputs all elements in the myNumbers  The following example outputs all elements in the
array. myNumbers array.
 Example  Example
int myNumbers[] = {25, 50, 75, 100}; int myNumbers[] = {25, 50, 75, 100};
int i; int i;

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


printf("%d\n", myNumbers[i]); printf("%d\n", myNumbers[i]);
} }
// Outputs 25, 50,75,100

25 26

Example Example
// C Program to demonstrate the use of array
#include <stdio.h> // C Program to demonstrate the use of Output
array
Elements in Array: 10 20 100 40 50
int main() #include <stdio.h>
{ int main()
// array declaration and initialization {
int arr[5] = { 10, 20, 30, 40, 50 }; // array declaration and
initialization
int arr[5] = { 10, 20, 30, 40, 50 };
// modifying element at index 2
arr[2] = 100; // modifying element at index 2
arr[2] = 100;
// traversing array using for loop // traversing array using for loop
printf("Elements in Array: "); printf("Elements in Array: ");
for (int i = 0; i < 5; i++) { for (int i = 0; i < 5; i++) {
printf("%d ", arr[i]); printf("%d ", arr[i]);
}
}
return 0; }
return 0; }

27 28
12/4/2023

Benefits of Using Array in C Benefits of Using Array in C


An array is crucial in C language, providing several benefits to 3. Better Memory Usage
programmers. The use of array in C offers a more efficient way to store data in memory.
As arrays hold elements in contiguous locations, computers can find and
1. Faster Access to Elements retrieve data in no time. Thus, reducing the amount of memory used to store
As each element is assigned an individual index number in an array, random data, which comes in handy while working with massive datasets.
and direct access to elements in an array becomes easier and faster. You can
also manipulate elements without hassle, making arrays a preferred choice 4. Easy Declaration and Initialization
for apps that need to retrieve data quickly. To declare an array in C, you simply need to specify the data type, array
name, and the number of elements it will store. It allows you to initialize
2. Improved Functionality arrays during declaration, saving a great deal of time and energy.
It is easy to manipulate arrays with pointers as using them, you can perform
otherwise-complex operations, such as swapping elements, conveniently. 5. Simplified Operations
This enhances its functionality and makes it a top choice for programmers. Arrays simplify complex operations involving multiple data elements. It
enhances productivity, ensures time efficiency, and enhances the whole
process. Storing the salary of 100 employees or marks of 100 students in a
class and calculating the average is a cakewalk with arrays.

29 30

Benefits of Using Array in C Benefits of Using Array in C


Some more advantages of the C array are as follows: • You can access elements in any order in O(1) time.

• It is easy to apply the search process. • A more efficient way to store multiple values of the same type.

• As arrays create a single array of multiple elements at once, you need to • In C, you can use various built-in functions, such as searching and
use fewer lines of code. This results in cleaner and more optimized code. sorting, to manipulate arrays.

• Involves low overhead. • As C supports multiple-dimension arrays, it is useful to represent


complex data structures like matrices.
• You can traverse elements using a single loop.

• Sorting code is easier as you have to write just a few lines of code.

• It is easy to convert arrays into pointers, enabling passing arrays to


functions as returning arrays from functions.

31 32
12/4/2023

Disadvantages of Array in C Disadvantages of Array in C


Along with numerous advantages, arrays also have a few drawbacks. Here Insertion and Deletion are Costly
are a few limitations of arrays in C that you should know: Insertion and deletion operations in an array are complicated because it is
No Built-in Bounds Checking essential to traverse the array and rearrange elements after the operation.
If a program tries to access an out-of-bound element in an array, it can lead This process can be costlier and more challenging.
to a runtime error or crash the program. Limited Size
Inflexible Structure The size of the array or number of elements is fixed and can’t be changed
Arrays are static in nature, so data can’t be resized based on user during runtime once allocated. So, if a program requires to store more data
requirements. Data size and type stored in an array are predetermined, than the assigned size, a new array with a larger size must be allocated, and
restricting flexibility and adaptability. then the data is copied to it. This is quite time-consuming and inefficient.
Restricted Data Type Memory Wastage
Arrays store only one type of data at a time, i.e., homogenous data. So, if Elements are assigned memory even when it’s not used. This wastes a lot of
you want to store multiple data types, you need to create several arrays or memory, which can be a concern for programs involving large amounts of
data structures. For example, in the char data type, you can only store data.
characters. If you try to store other data types, such as integers, it will show
an error.

33 34

Use of Array in C Use of Array in C


Here are some common uses of arrays in C: Data manipulation
Grouping related data Arrays provide a convenient way to manipulate and process a collection of
Arrays allow you to group related data items of the same type together. For data. You can perform various operations on array elements, such as
example, you can use an array to store a list of integers, characters, or any sorting, searching, filtering, and performing mathematical computations.
other data type. Efficient algorithms
Sequential access Many algorithms and data structures rely on arrays for their implementation.
Arrays provide a way to access elements sequentially using index values. Arrays are fundamental building blocks for data structures like stacks,
This allows you to iterate over the array elements easily using loops, such as queues, and matrices. They also play a crucial role in sorting and searching
for or while loops. algorithms.
Efficient storage Compact representation
Arrays allocate a contiguous block of memory for storing elements, making Arrays offer a compact and memory-efficient representation for storing
memory management more efficient. Elements in an array can be accessed large amounts of data. They allow you to access and manipulate large
directly by their index, without the need for searching or traversing data datasets without consuming excessive memory.
structures.

35 36
12/4/2023

Two-Dimensional Arrays
A Two-Dimensional array or 2D array in C is an array that has
exactly two dimensions.
Multidimensional Arrays  They can be visualized in the form of rows and columns organized
in a two-dimensional plane.

A multidimensional array is basically an array of arrays.  Syntax of 2D Array in C

array_name[size1] [size2];

Here,
•size1: Size of the first dimension.
•size2: Size of the second dimension.

37 38

Two-Dimensional Arrays Access the Elements of a 2D Array


A 2D array is also known as a matrix (a table of rows and columns). To access an element of a two-dimensional array, specify the
 To create a 2D array of integers, take a look at the following example: index number of both the row and column.

int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };


• Example

The first dimension represents the number of rows [2], while the int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };
second dimension represents the number of columns [3]. The values are printf("%d", matrix[0][2]);
placed in row-order, and can be visualized like this:
// Outputs 2

This statement accesses the value of the element in the first


row (0) and third column (2) of the matrix array.

39 40
12/4/2023

Change Elements in a 2D Array Loop Through a 2D Array


To change the value of an element, refer to the index number of To loop through a multi-dimensional array, you need one loop
the element in each of the dimensions. for each of the array's dimensions.

• Example • Example
int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };
int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };
matrix[0][0] = 9;
int i, j;
printf("%d", matrix[0][0]);
for (i = 0; i < 2; i++) {
// Now outputs 9 instead of 1 for (j = 0; j < 3; j++) {
printf("%d\n", matrix[i][j]);
This statement change the value of the element in the first }
row (0) and first column (0).
}

41 42

Loop Through a 2D Array Example


/ C Program to illustrate 2d array
Example #include <stdio.h>
#include <stdio.h>
int main() {
Output
int main() {
int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} }; // declaring and initializing 2d array 2D Array:
int arr[2][3] = { 10, 20, 30, 40, 50, 60 };
int i, j; 10 20 30
for (i = 0; i < 2; i++) { printf("2D Array:\n"); 40 50 60
for (j = 0; j < 3; j++) {
// printing 2d array
printf("%d\n", matrix[i][j]);
} for (int i = 0; i < 2; i++) {
} for (int j = 0; j < 3; j++) {
printf("%d ",arr[i][j]);
return 0; }
} printf("\n");
}
// Output: 1 4 2 3 6 8
return 0; }

43 44
12/4/2023

Examples
/* Valid declaration*/
int abc[2][2] = {1, 2, 3 ,4 }
/* Valid declaration*/
int abc[][2] = {1, 2, 3 ,4 }
/* Invalid declaration – you must specify second dimension*/
int abc[][] = {1, 2, 3 ,4 }
/* Invalid because of the same reason mentioned above*/
int abc[2][] = {1, 2, 3 ,4 }

45

You might also like