How to Declare and Initialize Array in C

Today you will learn How to Declare and Initialize Array in C. In this post, I will also explain to you what is C ARRAY and  How to Declare and Initialize Array in C?.  

C Array

How to Declare and Initialize Array in C


A collection of similar types of data elements stored in contiguous memory spaces is referred to as an array. Arrays are a derived data type in the C programming language that may hold primitive data types like int, char, double, float, and so on. It can also store a collection of derived data types like pointers, structures, and so on. 

The most fundamental data structure is an array, in which each data component can be accessed at random by its index number.

If you need to keep comparable elements, a C array is useful. For example, if we want to record a student's grades in six subjects, we don't need to create separate variables for each subject's grades. Instead, we can create an array that can be used to hold the marks in each subject in memory locations.

To Access the array's elements, only a few lines of code are required.

Properties of Array


The properties in the array are as follows.

o An array's elements all have the same data type and size, for example, int = 4 bytes.

o The array's elements are kept in contiguous memory regions, with the first element kept in the smallest memory place.

o We can access elements of the array at random because we can calculate the address of each element of the array using the specified base address and data element size.

C Array's Benefits

1) Data Access Code Optimization: Less code is required to access the data.

2) Ease of traversal: We may quickly obtain the items of an array by utilizing the for a loop.

3) Sorting is simple: We simply need a few lines of code to sort the array's components.

4) Random Access: The array allows us to access any element at any time.

Declaration of C Array


In the C programming language, we can declare an array in the following fashion.

1. data_type array_name[array_size];


Let's look at an example of how to declare an array.

1. int marks[5];

The data type is int, the array name is marked, and the array size is 5.

Initialization of C Array

The simplest way to initialize an array is by using the index of each element. We can initialize each element of the array by using the index. Consider the following example.


1. marks[0]=80;//initialization of array

2. marks[1]=60;

3. marks[2]=70;

4. marks[3]=85;

5. marks[4]=75;

C Array Example

1. #include<stdio.h>

2. int main(){

3. int i=0;

4. int marks[5];//declaration of array

5. marks[0]=80;//initialization of array

6. marks[1]=60;

7. marks[2]=70;

8. marks[3]=85;

9. marks[4]=75;

10. //traversal of array

11. for(i=0;i<5;i++){

12. printf("%d \n",marks[i]);

13. }//end of for loop

14. return 0;

15. }


Output

80

60

70

85

75

Post a Comment

0 Comments