README
Array
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


- taking input of array

- output of an 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 n;
scanf("%d", &n);
int a[n];
int sum = 0;
for (int i = 0; i < n; i++)
{
scanf("%d", &a[i]);
}
for (int i = 0; i < n; i++)
{
sum = sum + a[i];
}
printf("%d ", sum);
return 0;
}