Monday, October 22, 2018

Array in C Programming

0 comments

Array in C Programming

an array is a collection of similar type of data items and each data item is called an element of array. The data type of element may be any valid data type like char, int, float.
The elements of array share the some variable name but each element has a different index number known as subscript.
An array can be define as an ordered list of homogeneous data elements. All these elements are stored in consecutive memory location.

syntax: - data type array-name[ size of element];
  Ex.-int a[10];
  

In C Programming, we have 3 types of arrays
1.    One Dimensional Array
2.    Two-Dimensional Array
3.    Multi-Dimensional Array
o    Three-Dimensional Array
o    Four-Dimensional Array etc

Syntax or Declaration of One-Dimensional Array in C

  • Datatype: It will decide the type of elements array will accept.
For example: - If we want to store Float values then we declare the Data Type as float, If we want to store integer values then we declare the Data Type as int, etc.
  • Array Name: This is  name of Array who you give of  Array.
For example: - students[], age[], marks[], employees[] etc
  • Array Size: Number of elements an array can hold or store.
For example: - Array[10]  ,  array will hold 10 values.


For Example: -
int Student_Age [5];
1.    Here, we used int as the data type to declare an array. So, above array will accept only integers.
2.    Student_Age is the array name
3.    The size of an Array is 5 it means; Student_Age array will only accept 5 integer values.
o    If we try to store more than 5 then it will throw an error.
o    We can store less than 5.
For Example: - if we store only 2 integer values then remaining blank 3 which values will be assigned to default value (Which is NULL=0).
 
 

Initialization of Array in C Programming

There are many ways to initialization the array in C language

First Approach

int Employees [5] = {1, 2, 3, 4, 5}
Here,  initialized  array at the declaration time.

Second Approach 

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

Here, we did not mention the array size, but the compiler is intelligent enough to calculate the size by checking the number of elements, in this way memory allocated at the execution time.

Third Approach

int Student [5] = {1, 2, 3, 4}
Here we declared Student array with size 5 but you only assigned 4 variables. In these situations, the remaining values will be assigned to default values NULL (0 in this case).



 


 

No comments:

Post a Comment