Arrays in C
In C, an array is a data structure that stores a fixed-size sequential collection of elements of the same type. Each element in the array occupies a contiguous memory location, and they are accessed by their position, known as the index. Arrays are particularly useful when dealing with a collection of data elements of the same type that need to be stored and accessed efficiently.
What is an Array?
Declaration
Initialization
Indexing
Elements in an array are accessed using an index. Array indices start from 0 and go up to (size - 1). For example: numbers[0] accesses the first element, numbers[1] accesses the second element, and so on.
Example
#include <stdio.h>
int main() {
int i;
int numbers[5];
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;
printf("Array elements: ");
for (i = 0; i < 5; i++) {
printf("%d ", numbers[i]);
}
}
Array elements: 10 20 30 40 50
Explanation :
- We declare an array of integers named numbers with a size of 5.
- We initialize each element of the array with values 10, 20, 30, 40, and 50, respectively.
- We then print out all the elements of the array using a loop, iterating through each element and printing it.
problems & solutions
#include<stdio.h>
main()
{
int m[]= {25,38,49,50,70,59};
int i,s=0;
for(i=0;i<6;i++)
{
s=s+m[i];
}
printf("sum=%d\n",s);
float avg;
avg=(float)s/6;
printf("average=%f",avg);
}
sum=291
average=48.500000
#include<stdio.h>
main()
{
int m[]={68,35,19,55,91,29};
int n,i,j;
int max=m[0];
for(i=0;i<6;i++)
{
if(m[i]>max)
max=m[i];
}
printf("Max=%d",max);
}
Max=91
#include<stdio.h>
main()
{
int n,i;
printf("Enter a range=");
scanf("%d",&n);
int a[n],s[n];
for(i=0; i<n; i++)
{
printf("Enter number=");
scanf("%d",&a[i]);
}
int k=0;
for(i=n-1; i>=0; i--)
{
s[k]=a[i];
k++;
}
printf("After reverse=");
for(i=0;i<n;i++)
{
printf("%d ",s[i]);
}
}
Enter a range=4
Enter number=1
Enter number=2
Enter number=3
Enter number=4
After reverse=4 3 2 1
Conclusion
In Conclusion, arrays play a fundamental role in C programming by providing a mechanism for efficient data storage, manipulation, and access. Their importance lies in their ability to simplify programming tasks, improve memory management, and enhance code efficiency and readability.