data_type name [size]
int array[10]
float array[5]
arr[0] -> accessing value using index#include <stdio.h>
int main()
{
int ar[5];
ar[2] = 100;
ar[3] = 102;
ar[4] = 50;
printf("%d", ar[2]);
return 0;
}- memory management of array
- input output of array
#include <stdio.h>
int main()
{
int a[2];
scanf("%d %d %d", &a[0], &a[1], &a[2]);
printf("%d %d %d", a[0], a[1], a[2]);
return 0;
}- instead of hardcoded use loop
#include <stdio.h>
int main()
{
int a[5];
// scanf("%d %d %d", &a[0], &a[1], &a[2]);
// printf("%d %d %d", a[0], a[1], a[2]);
for (int i = 0; i <= 4; i++)
{
// printf("a[%d]\n", i);
scanf("%d", &a[i]);
}
for (int i = 0; i <= 4; i++)
{
printf("%d ", a[i]);
}
return 0;
}- reverse array
#include <stdio.h>
int main()
{
int n;
scanf("%d", &n);
int a[n];
for (int i = 0; i < n; i++)
{
scanf("%d", &a[i]);
}
for (int i = n-1 ; i >= 0; i--)
{
printf("%d ", a[i]);
}
return 0;
}- initializing
#include <stdio.h>
int main()
{
// int x = 10; // declare and initialize
// int a[5]
int a[5] = {10, 20, 23, 24, 25};
// not writting size is also ok in this case
// int a[] = {10, 20, 23, 24, 25};
for (int i = 0; i < 5; i++)
{
printf("%d ", a[i]);
}
return 0;
}-
in this case if we do not give all element only available value will be shown and empty spaces will be set 0;
-
remember this will work only for fixed size array. if we take array size from the input it will not work
-
sum of all values of array
#include<stdio.h>
int main ()
{
int x;
scanf("%d",&x);
int arr[x];
for(int i=0; i<x; i++){
scanf("%d",&arr[i]);
}
int sum=0;
for(int i=0; i<x; i++){
printf("%d ",arr[i]);
sum+=arr[i];
}
printf("\nsum=%d",sum);
return 0;
} -absolute summation
#include <stdio.h>
#include <stdlib.h> // Required for abs()
int main() {
int arr[] = {-5, 10, -3, 7, -2};
int n = sizeof(arr) / sizeof(arr[0]);
int absoluteSum = 0;
for (int i = 0; i < n; i++) {
absoluteSum += abs(arr[i]); // Convert to positive before adding
}
printf("The absolute sum is: %d\n", absoluteSum);
// Output: 27 (5 + 10 + 3 + 7 + 2)
return 0;
}
