Length of array:
- sizeof() function returns the total size of array.
- We can find the length of array by dividing total size with single element size.
int main() { float arr[5]; printf(“Total size of array : %d \n”, sizeof(arr)); printf(“Array element size : %d \n”, sizeof(arr[0])); printf(“Length of Array : %d \n”, sizeof(arr)/sizeof(arr[0])); return 0; } |
Note: Address of the first element is called the base address. The address of the ith element is given by the following formula, Addressi = base_address + i*size_of_element |
Array Initialization:
- We can assign values directly in the declaration of array is called Initialization.
- If we assign the elements less than the length of array, other locations get default values.
int main() { int arr[5] = {10, 20, 30}; int i; printf(“Array default values are : \n”); for(i=0 ; i<5 ; i++){ printf(“%d \n”, arr[i]); } return 0; } |
C Program to display First and Last element of Array:
int main () { int arr[] = {10, 20, 30, 40, 50}; printf(“First element : %d \n”, arr[0]); printf(“Last element : %d \n”, arr[4]); return 0; } |
C Program to display last element using length:
int main () { int arr[] = {10, 20, 30, 40, 50}; int len = sizeof(arr)/sizeof(int); printf(“Length : %d \n”, len); printf(“Last element : %d \n”, arr[len-1]); return 0; } |
C Program to Check First and Last elements Sum equals to 10 or not in Array:
int main () { int arr[] = {4, 3, 9, 2, 6}; int first = arr[0]; int last = arr[4]; if(first+last==10) printf(“Equals to 10 \n”); else printf(“Not equals to 10 \n”); return 0; } |
C program to check the First element of Array is Even or Not:
int main () { int arr[] = {4, 3, 9, 2, 6}; if(arr[0]%2==0) printf(“First element is Even \n”); else printf(“First element is not Even \n”); return 0; } |
C Program to replace the First and Last elements of array with 10:
int main () { int arr[] = {4, 3, 9, 2, 6}, i; arr[0] = 10; arr[4] = 10; printf(“Array elements are : \n”); for(i=0 ; i<5 ; i++){ printf(“%d \n”, arr[i]); } return 0; } |
C Program to Increase First and Decrease Last elements of Array:
int main () { int arr[] = {4, 3, 9, 2, 6}; int i; arr[0]++; arr[4]–; printf(“Array elements are : \n”); for(i=0 ; i<5 ; i++){ printf(“%d \n”, arr[i]); } return 0; } |
C program to swap first and last elements of array:
int main () { int arr[] = {4, 3, 9, 2, 6}; int i, temp; temp = arr[0]; arr[0] = arr[4]; arr[4] = temp; printf(“Array elements are : \n”); for(i=0 ; i<5 ; i++){ printf(“%d \n”, arr[i]); } return 0; } |