⬅️ Previous
🧠 What is a 1D Array?
A 1D (one-dimensional) array is a list of elements stored in continuous memory locations. All elements must be of the same data type.
📌 Syntax of 1D Array in C
data_type array_name[size];
Example:
int numbers[5]; // Declares an integer array of size 5
✅ Initializing a 1D Array
1. Declaration + Initialization
int numbers[5] = {10, 20, 30, 40, 50};
2. Declaration first, then input later
int numbers[5];
numbers[0] = 10;
numbers[1] = 20;
// and so on...
🧪 Full Example: Input & Output from a 1D Array
#include <stdio.h>
int main() {
int i;
int numbers[5];
// Input values from user
printf("Enter 5 numbers:\n");
for(i = 0; i < 5; i++) {
printf("Element %d: ", i);
scanf("%d", &numbers[i]);
}
// Display values
printf("\nYou entered:\n");
for(i = 0; i < 5; i++) {
printf("Element at index %d = %d\n", i, numbers[i]);
}
return 0;
}
🎯 Sample Output:
Enter 5 numbers:
Element 0: 12
Element 1: 25
Element 2: 33
Element 3: 47
Element 4: 59
You entered:
Element at index 0 = 12
Element at index 1 = 25
Element at index 2 = 33
Element at index 3 = 47
Element at index 4 = 59
🧮 Common Operations on 1D Arrays
1. Sum of all elements:
int sum = 0;
for(i = 0; i < 5; i++) {
sum += numbers[i];
}
printf("Sum = %d\n", sum);
2. Find largest element:
int max = numbers[0];
for(i = 1; i < 5; i++) {
if(numbers[i] > max) {
max = numbers[i];
}
}
printf("Maximum = %d\n", max);
🔚 Summary Table
Topic | Details |
---|---|
Data type | Must be the same for all items |
Index starts | From 0 |
Access | array[index] |
Use | Grouping similar data (e.g. marks, prices) |