What is Array in C?
In C language, an array is a collection of similar data types that are stored together in contiguous memory locations. The elements of an array are accessed using an index, which represents the position of the element within the array.
Arrays are declared with a specific size and data type, and can be initialized with default values or with specific values for each element. For example, the following code declares an array of integers with a size of 5 and initializes the first element to 0:
For creating array in c , we have to use []
(subscript) operator inside []
we can specify size of array. Array has index for each data , array index always starts with 0 .
integer type array
Here is int
data type array:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char const *argv[])
{
int arr1[5]; // declare an array with capacity
// assign the value using index
arr1[0] = 10;
arr1[1] = 20;
arr1[2] = 30;
arr1[3] = 40;
arr1[4] = 50;
int arr[] = {10, 65, 35, 4, 50}; // create and initialize
printf(" %d", arr[0]); // 10
printf(" %d", arr[2]); // 35
printf(" %d", arr[4]); //50
return 0;
}
Characters Array (Char)
create a char array that can store character data type . In this case , if we create array using char data type it will be string . At the end of the char array we have to add NULL
character that is \0
because, sequences of characters terminated by NULL
characters known as string .
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char const *argv[])
{
// valid syntax
char name[] = "PanditProgrammer"; // array automatic capacity
char str[20] = {'H','e','l','l','o','\0'}; //
// invalid syntax
char str1[5];
str1 = {'C','l','a','n','g','u','a','g','e','\0'}; // error
char str2[10] = "This is c language course"; //error
printf("the name is %s\n",name);
printf("the name is %s\n",str);
printf("%s",str2);
return 0;
}
Arrays in C are often used for storing and manipulating large amounts of data, such as in algorithms, numerical analysis, and data structures. They provide a way to efficiently access and manipulate large collections of data using a single variable, and are a fundamental data structure in many programming languages.