C++ Arrays Explained: Syntax, Examples & Theory | Compiled By Bilal Ahmad Khan AKA Mr. BILRED | CppNotes
Understanding Arrays in C++ – Easy Guide for Beginners
By Bilal Ahmad Khan AKA Mr. BILRED
Asking Positively! Have you ever wondered WHY SHOULD WE EVEN USE ARRAYS? Like, WHY?
Look
Arrays help programmers store and manage multiple values efficiently. This guide explains arrays in C++ with simple examples.
📌 What is an Array in C++?
An array is a collection of similar data types stored in a single variable.
Instead of creating multiple variables, an array lets us store multiple values in one place.
In "mere walay alfaaz", Agar aap chaahty ho aap ziada saari values store karo, to kia phir har dafa variables define karty raho gy? NAHI Na! Phir isko solve karna he arrays k zariye! But first, understand its basic syntax
Basic SYNTAX Of Arrays
data_type array_name[size];
✅ Example:
int numbers[5] = {10, 20, 30, 40, 50};
cout << numbers[2]; // Outputs 30
📌 Importance; Why Do We Use Arrays?
- 🔹 Saves Space: No need to create separate variables.
- 🔹 Easy Data Handling: We can loop through all elements easily.
- 🔹 Fast Access: Any element can be accessed using its index.
📌 Types of Arrays in C++
1️⃣ One-Dimensional Arrays
The simplest form of arrays, like a list.
int marks[3] = {85, 90, 75};
cout << marks[1]; // Outputs 90
2️⃣ Multi-Dimensional Arrays
Used to store data in rows and columns (like a matrix).
In below code, [2] is the number of rows and [3] shows the number of columns
int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}};
cout << matrix[1][2]; // Outputs 6
📌 How to Loop Through an Array?
We can use a for loop to print all elements of an array.
✅ Example:
int numbers[5] = {10, 20, 30, 40, 50};
for (int i = 0; i < 5; i++) {
cout << numbers[i] << " ";
}
// Output: 10 20 30 40 50
📌 Memory Allocation in Arrays
C++ stores arrays in contiguous memory locations, making access faster.
Example: If arr[3] = {10, 20, 30}
, it might be stored like this:
Address | Value |
---|---|
1000 | 10 |
1004 | 20 |
1008 | 30 |
How To Use Arrays; Example Simple Program
#include
using namespace std;
int main() {
int numbers[5] = {10, 20, 30, 40, 50};
cout << "First number: " << numbers[0] << endl;
cout << "Second number: " << numbers[1] << endl;
cout << "All numbers: ";
for (int i = 0; i < 5; i++) {
cout << numbers[i] << " ";
}
return 0;
}
📌 Limitations of Arrays
- ❌ Fixed Size (Cannot grow dynamically).
- ❌ Inserting/deleting elements is slow.
- ❌ Wastes memory if not fully used.
📌 Alternative to Arrays – Vectors
If you need "dynamic arrays", use vectors instead.
#include <vector>
vector nums = {1, 2, 3};
nums.push_back(4);
push_back() adds an element to the end of the vector, unlike arrays that have a fixed size.
Try this code online: OnlineGDB
Related Topics:
Comments
Post a Comment