One-dimensional arrays help you store many values of the same type in a single list. This makes it easy to organize and use data like numbers or letters together.
0
0
One-dimensional arrays in C
Introduction
When you want to keep a list of student scores in a test.
When you need to store daily temperatures for a week.
When you want to hold a sequence of characters as a word or sentence.
When you want to process a list of items one by one.
When you want to perform calculations on a fixed number of values.
Syntax
C
/* Define an array of integers with 5 elements */ int numbers[5]; /* Define and initialize an array of characters */ char letters[4] = {'a', 'b', 'c', 'd'};
The number inside the square brackets [] tells how many items the array can hold.
Array indexes start at 0, so the first element is numbers[0].
Examples
This creates an array of 3 integers but does not set their values yet.
C
int scores[3]; // Empty array of 3 integers, values are garbage until assigned
Here, the array is created and filled with 5 prime numbers right away.
C
int primes[5] = {2, 3, 5, 7, 11}; // Array with 5 prime numbers initialized
This array holds the word "Hello" as characters, ending with '\0' to mark the end.
C
char word[6] = {'H', 'e', 'l', 'l', 'o', '\0'}; // Array holding a string with null terminator
Some compilers allow zero-length arrays as an extension, but they cannot hold any elements.
C
int emptyArray[0]; // Edge case: array with zero length (not standard in C, but allowed as a compiler extension in some compilers)
Sample Program
This program creates an array to hold temperatures for 5 days. It prints all the temperatures, changes the temperature for day 3, and prints the updated list.
C
#include <stdio.h> int main() { // Create an array of 5 integers int temperatures[5] = {23, 25, 22, 20, 24}; // Print all temperatures printf("Temperatures for the week:\n"); for (int index = 0; index < 5; index++) { printf("Day %d: %d degrees\n", index + 1, temperatures[index]); } // Change the temperature of day 3 temperatures[2] = 26; // Print updated temperatures printf("\nUpdated temperatures:\n"); for (int index = 0; index < 5; index++) { printf("Day %d: %d degrees\n", index + 1, temperatures[index]); } return 0; }
OutputSuccess
Important Notes
Accessing an array index outside its range causes undefined behavior and can crash your program.
Arrays have fixed size; you cannot change their length after creation.
Time complexity to access any element by index is O(1), which means very fast.
Summary
One-dimensional arrays store multiple values of the same type in order.
Use arrays when you need to keep and work with lists of data.
Remember array indexes start at 0 and size is fixed.