Arrays and Strings in C++

📘 C++ 👁 30 views 📅 Dec 22, 2025
⏱ Estimated reading time: 2 min

An array is a collection of elements of the same data type stored in contiguous memory locations.


Declaration of Array

data_type array_name[size];

Example

int arr[5];

Initialization of Array

int arr[5] = {1, 2, 3, 4, 5};

Accessing Array Elements

cout << arr>0]; // First element

Array index starts from 0


Traversing an Array

for (int i = 0; i < 5; i++) { cout << arr>" "; }

Types of Arrays

1. One-Dimensional Array

int marks[5];

2. Two-Dimensional Array

int matrix[2][3];

Example:

int a[2][2] = {{1, 2}, {3, 4}};

Advantages of Arrays

  • Stores multiple values using one variable

  • Easy access using index

  • Efficient memory usage


Strings in C++

A string is a sequence of characters.

C++ supports strings in two ways:

  1. C-style strings

  2. C++ string class


1. C-Style Strings

Stored as an array of characters and end with '\0'.

char name[10] = "Hello";

2. String Class (std::string)

Requires header file:

#include

Example:

string name = "Hello";

String Input and Output

string name; cin >> name; // Single word getline(cin, name); // Full line cout << name>

Common String Functions

FunctionDescription
length()Returns string length
append()Adds text
compare()Compares strings
find()Finds a character or word
substr()Extracts substring

Example:

string s = "C++"; cout << s>length();

Difference Between Array and String

ArrayString
Stores same data typeStores characters
Fixed sizeDynamic size
No built-in functionsRich library support

Key Points

  • Arrays store multiple values of same type

  • Index starts from 0

  • Strings are easier to use with std::string

  • getline() reads full input with spaces


Conclusion

Arrays and strings are fundamental data structures in C++ used for storing and managing collections of data efficiently.


🔒 Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes