2. C PROGRAMMING
Arrays
Arrays are used to store multiple values in a single variable, instead of
declaring separate variables for each value.
To create an array, define the data type (like int) and specify the name
of the array followed by square brackets [].
To insert values to it, use a comma-separated list, inside curly braces:
3. C PROGRAMMING
Syntax for declaring an array:-
dataType array_name[arraySize];
Example:- Declare an array
int student_marks[20];
char student_name[10];
float numbers[5];
Note:- After the declaration, size of the array cannot be changed.
4. C PROGRAMMING
Access elements of an array in C
In C, you can access the elements of the array using their index.
Suppose, you declare an array like below:-
If you want to access the first element of the above array then do
numbers[0] and if you want to access the second element then do
numbers[1] and so on.
The first index of the array is 0 not 1. That’s why numbers[0] is the first
element.
To access the last element of the array, do numbers[4].
numbers[0] numbers[1] numbers[2] numbers[3] numbers[4]
2 3 4 5 6
5. C PROGRAMMING
• Initialize an array:-
• At the time of declaration, it is possible to initialize an array.
• int numbers[5] = {2, 3, 4, 5, 6};
• You can also initialize an array like below:-
• int numbers[] = {2, 3, 4, 5, 6};
• In case, if you don’t specify the size of the array during initialization then the
compiler will know it automatically.
• numbers[0] = 2
• numbers[1] = 3
• numbers[2] = 4
• numbers[3] = 5
• numbers[4] = 6
6. C PROGRAMMING
Basic Example of an array:-
#include<stdio.h>
int main()
{
int numbers[5] = {2, 3, 4, 5, 6};
printf(" Basic Example of an array");
printf("First number is : %dn",numbers[0]);
printf("Third number is : %dn",numbers[2]);
printf("Last number is : %dn",numbers[4]);
}
7. C PROGRAMMING
Change the value of array elements:-
In C, you can also change the elements of the array after declaring it.
Example:- Changing the value of array elements
#include<stdio.h>
int main()
{
int numbers[5] = {2, 3, 4, 5, 6};
numbers[0] = 4; // changing value from 2 to 4!
numbers[2] = 5; // changing value from 4 to 5!
numbers[4] = 10; // changing value from 6 to 10!
printf("First number is : %dn",numbers[0]);
printf("Third number is : %dn",numbers[2]);
printf("Last number is : %dn",numbers[4]);
}
8. C PROGRAMMING
#include <stdio.h>
int main()
{
//Initialize array
int arr[5] = {1, 2, 3, 4, 5};
printf("Elements of given array: n");
//Loop through the array by incrementing value of i
for (int i = 0; i < =5; i++) {
printf("%d ", arr[i]);
}
9. #include <stdio.h>
int main() {
int array[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
int a;
for(a = 9; a >= 0; a--)
printf("%d ", array[a]);
return 0;
}
10. C PROGRAMMING
Arrays using functions :
#include <stdio.h>
void display(int age1, int age2) {
printf("%dn", age1);
printf("%dn", age2);}
int main() {
int ageArray[] = {2, 8, 4, 12};
// pass second and third elements to display()
display(ageArray[1], ageArray[2]);
return 0;
}