One-Dimensional Arrays in C Programming (Complete Guide with Examples)


This tutorial explains one-dimensional arrays in C, which store multiple elements of the same data type in a single variable. It covers declaration, initialization, accessing elements, and practical examples to help beginners handle collections of data efficiently.

1. What is a One-Dimensional Array

  1. An array is a collection of elements of the same data type.
  2. One-dimensional arrays store elements in a single row.
  3. Elements are accessed using an index, starting from 0.

2. Syntax


data_type array_name[size];
  1. data_type – type of elements (int, float, char, etc.)
  2. array_name – name of the array
  3. size – number of elements

Example: Declaration


int marks[5]; // integer array of 5 elements
float prices[10]; // float array of 10 elements
char name[20]; // character array

3. Array Initialization

Method 1: During Declaration


int marks[5] = {80, 85, 90, 75, 88};

Method 2: Assigning Later


int marks[5];
marks[0] = 80;
marks[1] = 85;

Method 3: Partial Initialization


int marks[5] = {80, 85}; // remaining elements = 0

4. Accessing Array Elements

Use the index to access or modify an element:


marks[0] = 95; // set first element
printf("%d", marks[0]); // print first element

5. Example Program: Input and Display Array Elements


#include <stdio.h>

int main() {
int n, i;
printf("Enter number of elements: ");
scanf("%d", &n);

int arr[n];

// Input elements
for(i = 0; i < n; i++) {
printf("Enter element %d: ", i+1);
scanf("%d", &arr[i]);
}

// Display elements
printf("Array elements: ");
for(i = 0; i < n; i++)
printf("%d ", arr[i]);

return 0;
}

Sample Output:


Enter number of elements: 5
Enter element 1: 10
Enter element 2: 20
Enter element 3: 30
Enter element 4: 40
Enter element 5: 50
Array elements: 10 20 30 40 50

6. Example Program: Sum and Average of Array Elements


#include <stdio.h>

int main() {
int n, i, sum = 0;
float avg;

printf("Enter number of elements: ");
scanf("%d", &n);

int arr[n];

for(i = 0; i < n; i++) {
printf("Enter element %d: ", i+1);
scanf("%d", &arr[i]);
sum += arr[i];
}

avg = (float)sum / n;

printf("Sum = %d\n", sum);
printf("Average = %.2f\n", avg);

return 0;
}

7. Key Points to Remember

  1. Array size must be a positive integer
  2. Indexing starts from 0
  3. Arrays can store only one data type
  4. Array elements can be input from user or initialized during declaration