In this tutorial, we will learn about arrays in C. An array stores many values of the same type under one name. The values stay in order, and each has a position number starting from zero. This makes it easy to find and use them. Programmers use arrays to handle lists, perform calculations, and organize data. Let’s see how they work with examples!
Contents:
- What are Arrays in C?
- Declaring and Initializing Arrays in C
- Accessing Elements of an Array in C
- Types of Arrays in C
- One-Dimensional Array (1D Array) in C
- Two-Dimensional Array (2D Array or Matrix) in C
- Multi-Dimensional Array in C
- Array Operations in C
- One-Dimensional vs Two-Dimensional Arrays in C
- Array and Pointers in C
- Advantages of Array in C
- Disadvantages of Array in C
- FAQs on Arrays in C
What are Arrays in C?
An array in C is a way to store multiple values of the same type in a single, organized structure. The values are kept together in memory, making it easy to access and manage them using a single variable name.
Key Features of Arrays:
- Fixed Size: You must define the size of an array when you create it, and you cannot change it later.
- Same Data Type: Every element in an array must have the same type, such as int, char, or float.
- Indexed Access: You can access each element using an index, starting from 0.
- Efficient Memory Usage: Since arrays store data in a continuous block of memory, they allow faster access than linked lists.
Declaring and Initializing Arrays in C
Declaration of an Array
In C, an array must be declared before using it. The declaration specifies the data type and the size of the array.
Syntax:
data_type array_name[size];
- data_type → Type of elements (int, float, char, etc.).
- array_name → Name of the array.
- size → Number of elements in the array.
Example:
int numbers[5]; // Declaring an array of 5 integers
Initializing an Array
Array elements can be initialized at the time of declaration or individually later.
1. Initialization at Declaration
int numbers[5] = {10, 20, 30, 40, 50}; // Initializing array with values
2. Individual Initialization
int numbers[5]; numbers[0] = 10; numbers[1] = 20; numbers[2] = 30; numbers[3] = 40; numbers[4] = 50;
Example Program
#include <stdio.h> int main() { int marks[3] = {85, 90, 78}; // Initializing an array printf("Marks in C Programming: %d\n", marks[0]); printf("Marks in Java: %d\n", marks[1]); printf("Marks in C++ Programming: %d\n", marks[2]); return 0; }
Output:
Marks in C Programming: 85 Marks in Java: 90 Marks in C++ Programming: 78
This C program shows how to use arrays. It creates an array called marks with three numbers: {85, 90, 78}. The program prints these numbers using printf. The first number is for C Programming, the second is for Java, and the third is for C++. It ends by returning 0, which means it ran successfully.
Accessing Elements of an Array in C
Once an array is declared and initialized, its elements can be accessed using indexing. Each element of an array is stored in contiguous memory locations and can be accessed using its index number, starting from 0.
Syntax:
array_name[index]
- array_name → The name of the array.
- index → The position of the element (starting from 0).
Example Program: Accessing Array Elements
#include <stdio.h> int main() { int numbers[5] = {10, 20, 30, 40, 50}; // Initializing the array // Accessing and printing elements using indexing printf("First element: %d\n", numbers[0]); printf("Second element: %d\n", numbers[1]); printf("Third element: %d\n", numbers[2]); printf("Fourth element: %d\n", numbers[3]); printf("Fifth element: %d\n", numbers[4]); return 0; }
Output:
First element: 10 Second element: 20 Third element: 30 Fourth element: 40 Fifth element: 50
Accessing Array Elements Using Loops
Instead of manually accessing each element, we can use loops to iterate through the array.
Example: Accessing Elements with a for Loop
#include <stdio.h> int main() { int numbers[5] = {5, 15, 25, 35, 45}; printf("Array elements:\n"); for(int i = 0; i < 5; i++) { // Loop through array printf("Element at index %d: %d\n", i, numbers[i]); } return 0; }
Output:
Array elements: Element at index 0: 5 Element at index 1: 15 Element at index 2: 25 Element at index 3: 35 Element at index 4: 45
Types of Arrays in C
In C programming, arrays are classified into different types based on their structure and usage. The main types of arrays in C are:
- One-Dimensional Array (1D Array)
- Two-Dimensional Array (2D Array or Matrix)
- Multi-Dimensional Array
One-Dimensional Array (1D Array) in C
A one-dimensional array is a collection of elements of the same data type stored in contiguous memory locations. It allows efficient storage and retrieval of data using an index.
Syntax of 1D Array in C
data_type array_name[size];
- data_type → Type of data (int, float, char, etc.)
- array_name → Name of the array
- size → Number of elements in the array
Declaring and Initializing a 1D Array
int numbers[5] = {10, 20, 30, 40, 50}; // Declaration and Initialization
Alternatively, you can declare an array without initialization:
int numbers[5]; // Declaration only
And assign values later:
numbers[0] = 10; numbers[1] = 20; numbers[2] = 30; numbers[3] = 40; numbers[4] = 50;
Accessing Elements of a 1D Array
Array elements are accessed using an index, which starts from 0.
#include <stdio.h> int main() { // Declaration and initialization of Sanfoundry Certification scores int scores[5] = {80, 85, 90, 95, 88}; // Displaying array elements printf("Sanfoundry Certification Exam Scores:\n"); printf("Score in Module 1: %d\n", scores[0]); printf("Score in Module 2: %d\n", scores[1]); printf("Score in Module 3: %d\n", scores[2]); printf("Score in Module 4: %d\n", scores[3]); printf("Score in Module 5: %d\n", scores[4]); return 0; }
Output:
Sanfoundry Certification Exam Scores: Score in Module 1: 80 Score in Module 2: 85 Score in Module 3: 90 Score in Module 4: 95 Score in Module 5: 88
This C program demonstrates how to use arrays. It creates an array called scores with five values: {80, 85, 90, 95, 88}. The program prints each score using printf. The scores represent results from five modules of the Sanfoundry Certification Exam. It ends by returning 0, meaning it ran successfully.
Looping Through a 1D Array
We can use loops to iterate through an array efficiently.
#include <stdio.h> int main() { // Declaration and initialization of Sanfoundry Quiz scores int scores[5] = {78, 85, 90, 88, 92}; // Displaying scores using a loop printf("Sanfoundry Quiz Scores:\n"); for(int i = 0; i < 5; i++) { printf("Score in Quiz %d: %d\n", i + 1, scores[i]); } return 0; }
Output:
Sanfoundry Quiz Scores: Score in Quiz 1: 78 Score in Quiz 2: 85 Score in Quiz 3: 90 Score in Quiz 4: 88 Score in Quiz 5: 92
This C program demonstrates how to use arrays with loops. It creates an array called scores with five values: {78, 85, 90, 88, 92}. The program uses a for loop to print each score, representing results from five Sanfoundry Quiz attempts. It ends by returning 0, meaning it ran successfully.
Two-Dimensional Array (2D Array or Matrix) in C
A Two-Dimensional Array (2D Array) is an array of arrays where data is stored in rows and columns. It is often used to represent tabular data like matrices, game boards, and exam scores.
Syntax:
data_type array_name[rows][columns];
- data_type → Type of elements (e.g., int, float, char).
- array_name → Name of the 2D array.
- rows → Number of rows.
- columns → Number of columns.
Example:
#include <stdio.h> int main() { // Declaring a 2D array for quiz scores int quizScores[3][2] = { {80, 85}, // Student 1 scores {90, 88}, // Student 2 scores {75, 78} // Student 3 scores }; // Printing quiz scores printf("Sanfoundry Quiz Scores:\n"); for (int i = 0; i < 3; i++) { for (int j = 0; j < 2; j++) { printf("Student %d, Quiz %d: %d\n", i + 1, j + 1, quizScores[i][j]); } } return 0; }
This C program demonstrates how to use a 2D array. It creates a quizScores array with three students’ scores from two quizzes: {80, 85}, {90, 88}, {75, 78}. A nested for loop prints each student’s quiz scores. The program ends by returning 0, meaning it ran successfully.
Multi-Dimensional Array in C
A Multi-Dimensional Array in C is an array that has more than one dimension, allowing the storage of data in a tabular or matrix format. The most commonly used multi-dimensional array is the 2D array (Matrix), but C supports 3D arrays and beyond.
Syntax:
data_type array_name[size1][size2]...[sizeN];
- data_type → Type of data (int, float, char, etc.)
- array_name → Name of the array
- size1, size2, …, sizeN → Number of elements in each dimension
Example:
#include <stdio.h> int main() { // Declaring a 3D array for storing scores of 2 teams in 3 rounds with 3 participants each int scores[2][3][3] = { { {85, 90, 88}, {78, 80, 85}, {90, 92, 89} }, // Team 1 scores { {75, 80, 78}, {88, 85, 90}, {92, 94, 91} } // Team 2 scores }; // Printing scores printf("Sanfoundry Coding Championship Scores:\n"); for (int team = 0; team < 2; team++) { printf("Team %d Scores:\n", team + 1); for (int round = 0; round < 3; round++) { printf(" Round %d: ", round + 1); for (int participant = 0; participant < 3; participant++) { printf("%d ", scores[team][round][participant]); } printf("\n"); } printf("\n"); } return 0; }
Output:
Sanfoundry Coding Championship Scores: Team 1 Scores: Round 1: 85 90 88 Round 2: 78 80 85 Round 3: 90 92 89 Team 2 Scores: Round 1: 75 80 78 Round 2: 88 85 90 Round 3: 92 94 91
This C program uses a 3D array to store scores for two teams, each participating in three rounds with three players. The scores array holds these values, and nested for loops display the scores for each team, round, and participant. Finally, the program returns 0, indicating successful execution.
Array Operations in C
Arrays in C allow performing various operations such as insertion, deletion, searching, updating, and traversing. These operations help manage data efficiently in different programming scenarios.
1. Traversing an Array (Displaying Elements)
#include <stdio.h> int main() { int scores[] = {85, 90, 78, 92, 88}; // Array of quiz scores int n = sizeof(scores) / sizeof(scores[0]); // Calculate number of elements printf("Sanfoundry Quiz Scores:\n"); for (int i = 0; i < n; i++) { printf("Quiz %d: %d\n", i + 1, scores[i]); } return 0; }
Output:
Sanfoundry Quiz Scores: Quiz 1: 85 Quiz 2: 90 Quiz 3: 78 Quiz 4: 92 Quiz 5: 88
This C program demonstrates how to use an array to store and display quiz scores. It declares an integer array scores with five values: {85, 90, 78, 92, 88}. The program then calculates the number of elements in the array using sizeof(scores) / sizeof(scores[0]). A for loop iterates through the array and prints each quiz score along with its corresponding quiz number.
2. Insertion in an Array
Example: Adding a New Score at a Specific Position
#include <stdio.h> int main() { // Initial array with space for 1 more element int scores[6] = {85, 90, 78, 92, 88}; int n = 5; // Current number of elements int pos = 3; // Position to insert (0-based index) int newScore = 95; // Shifting elements to the right for (int i = n; i > pos; i--) { scores[i] = scores[i - 1]; } scores[pos] = newScore; // Insert new element n++; // Increase count printf("Updated Scores:\n"); for (int i = 0; i < n; i++) { printf("%d ", scores[i]); } return 0; }
Output:
Updated Scores: 85 90 95 78 92 88
This program inserts a new score into an array by shifting elements to the right. It initializes scores with five values and creates space for one more. A loop shifts elements to make room at the specified position, then inserts the new score. Finally, it prints the updated array.
3. Deletion in an Array
#include <stdio.h> int main() { int scores[] = {85, 90, 78, 92, 88}; int n = 5; // Number of elements int pos = 2; // Position to delete (0-based index) // Shift elements to the left for (int i = pos; i < n - 1; i++) { scores[i] = scores[i + 1]; } n--; // Decrease count printf("Scores after deletion:\n"); for (int i = 0; i < n; i++) { printf("%d ", scores[i]); } return 0; }
Output:
Scores after deletion: 85 90 92 88
This program removes an element from an array by shifting elements to the left. It initializes scores with five values and selects a position to delete. A loop shifts elements to overwrite the deleted value, reducing the array size. Finally, it prints the updated scores.
4. Searching in an Array
#include <stdio.h> int main() { int scores[] = {85, 90, 78, 92, 88}; int n = 5; int key = 92; // Value to search int found = 0; for (int i = 0; i < n; i++) { if (scores[i] == key) { printf("Score %d found at position %d\n", key, i + 1); found = 1; break; } } if (!found) printf("Score not found\n"); return 0; }
Output:
Score 92 found at position 4
This program searches for a specific score in an array. It initializes scores with five values and checks each element using a loop. If the score is found, it prints its position; otherwise, it displays a “not found” message. The program stops searching once it finds the score.
5. Updating an Array
#include <stdio.h> int main() { int scores[] = {85, 90, 78, 92, 88}; int n = 5; int pos = 1; // Index to update int newScore = 95; scores[pos] = newScore; // Updating element printf("Updated Scores:\n"); for (int i = 0; i < n; i++) { printf("%d ", scores[i]); } return 0; }
Output:
Updated Scores: 85 95 78 92 88
This program updates an element in an array. It initializes scores with five values and changes the score at a specified index.
One-Dimensional vs Two-Dimensional Arrays in C
Here’s a comparison table for One-Dimensional vs Two-Dimensional Arrays in C:
Feature | One-Dimensional Array | Two-Dimensional Array |
---|---|---|
Definition | A list of elements stored in a single row or column. | A table-like structure with rows and columns. |
Declaration | int arr[5]; | int arr[3][4]; |
Storage Structure | Stores elements in a single line. | Stores elements in a grid format (rows × columns). |
Accessing Elements | Accessed using a single index (e.g., arr[2]). | Accessed using two indices (e.g., arr[1][2]). |
Usage | Used for simple lists like marks, temperatures, or prices. | Used for matrices, tables, or grids of data. |
Example | {10, 20, 30, 40, 50} | {{1, 2}, {3, 4}, {5, 6}} |
Memory Allocation | Stored in a contiguous block of memory. | Each row is stored as a separate contiguous block. |
Complexity | Easier to manage and use. | More complex, requiring nested loops for processing. |
Array and Pointers in C
In C, arrays and pointers are closely related. Since an array’s name acts as a pointer to its first element, we can use pointers to access and manipulate array elements efficiently.
Example 1: Accessing Array Elements Using Pointers
#include <stdio.h> int main() { int scores[] = {85, 90, 78, 92, 88}; int *ptr = scores; // Pointer to the first element of the array printf("Sanfoundry Quiz Scores using Pointers:\n"); for (int i = 0; i < 5; i++) { printf("Quiz %d: %d\n", i + 1, *(ptr + i)); } return 0; }
Output:
Sanfoundry Quiz Scores using Pointers: Quiz 1: 85 Quiz 2: 90 Quiz 3: 78 Quiz 4: 92 Quiz 5: 88
Example 2: Storing and Printing Strings Using an Array of Pointers
#include <stdio.h> int main() { char *subjects[] = {"C", "Java", "Python", "C++", "JavaScript"}; printf("Programming Subjects:\n"); for (int i = 0; i < 5; i++) { printf("%s\n", subjects[i]); } return 0; }
Output:
Programming Subjects: C Java Python C++ JavaScript
Advantages of Array in C
- They’re simple to use and understand.
- Arrays are very efficient for storing and accessing data.
- Arrays offer an easy way to keep track of related data items (i.e., by using indices).
- It allows you to directly access any element in the array without having to loop through all of the elements. This can improve the efficiency of your code, especially if you need to access a large number of elements.
Disadvantages of Array in C
- The size of the array must be fixed when it is created. This means that if you want to add or remove elements from the array, you must create a new array with the updated size.
- Arrays are not always efficient. If you want to find an element in an array, you must go through each element until you find the one you’re looking for.
- Inserting or deleting items from an array can be costly. This is because when you insert or delete an item from an array, all items in the array must be shifted in memory to make room for the new item or fill the gap left by the deleted item. This can take a lot of time, especially with large arrays.
FAQs on Arrays in C
1. What is an array in C?
An array is a collection of elements of the same data type stored in contiguous memory locations. It allows multiple values to be stored under a single variable name.
2. How are array elements accessed in C?
Array elements are accessed using an index, starting from 0. The first element is at index 0, the second at index 1, and so on.
3. What happens if you access an array element out of bounds?
Accessing an out-of-bounds element leads to undefined behavior, which may cause incorrect values or program crashes.
4. How do you pass an array to a function?
Instead of passing the entire array, only a pointer to its first element is passed. This allows the function to operate on the same memory without creating a copy.
5. Can you change the size of an array after declaration?
No, the size of a statically declared array cannot be changed at runtime. However, dynamic memory allocation can be used to create resizable arrays.
6. How are arrays stored in memory?
Arrays are stored in contiguous memory locations, meaning elements are placed sequentially. If an integer array starts at memory address 1000, the next element will be stored at 1004 (assuming 4-byte integers).
7. What is an array of pointers?
An array of pointers stores memory addresses instead of values. Each element in such an array is a pointer pointing to a different memory location.
8. Can you use sizeof to find the size of an array?
Yes, the total size of an array can be determined using the sizeof operator. To get the number of elements, divide the total size by the size of one element.
Key Points to Remember
Here is the list of key points we need to remember about “Arrays in C”.
- An array is a collection of values of the same type stored in contiguous memory locations.
- Arrays must be declared with a fixed size and type and can be initialized at declaration or assigned values individually.
- Elements are accessed using their index, and loops like for loops help in iteration.
- Arrays can be one-dimensional, two-dimensional (matrices), or multi-dimensional.
- Common operations on arrays include traversal, insertion, deletion, searching, and updating.
- Arrays and pointers are closely related, as the array name represents a pointer to its first element.
- Loops like for and while are used to manipulate array elements efficiently.
- Arrays are widely used in sorting, searching, mathematical computations, data storage, and implementing structures like stacks and queues.
- Apply for C Internship
- Check Computer Science Books
- Practice BCA MCQs
- Watch Advanced C Programming Videos
- Check C Books