0% found this document useful (0 votes)
6 views

Array String

The document provides a comprehensive overview of arrays in C++, including their properties, declaration, initialization, and access methods. It explains both one-dimensional and two-dimensional arrays, along with examples of how to manipulate them in C++. Additionally, it covers the size calculation of arrays and the relationship between arrays and pointers.

Uploaded by

np050126
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Array String

The document provides a comprehensive overview of arrays in C++, including their properties, declaration, initialization, and access methods. It explains both one-dimensional and two-dimensional arrays, along with examples of how to manipulate them in C++. Additionally, it covers the size calculation of arrays and the relationship between arrays and pointers.

Uploaded by

np050126
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

In C++, an array is a data structure that is used to store multiple values of

similar data types in a contiguous memory location.

For example, if we have to store the marks of 4 or 5 students then we can


easily store them by creating 5 different variables but what if we want to
store marks of 100 students or say 500 students then it becomes very
challenging to create that numbers of variable and manage them. Now,
arrays come into the picture that can do it easily by just creating an array of
the required size.

Properties of Arrays in C++


 An Array is a collection of data of the same data type, stored at a
contiguous memory location.
 Indexing of an array starts from 0. It means the first element is stored at
the 0th index, the second at 1st, and so on.
 Elements of an array can be accessed using their indices.
 Once an array is declared its size remains constant throughout the
program.
 An array can have multiple dimensions.
 The size of the array in bytes can be determined by the sizeof operator
using which we can also find the number of elements in the array.
 We can find the size of the type of elements stored in an array by
subtracting adjacent addresses.
Array Declaration in C++
In C++, we can declare an array by simply specifying the data type first
and then the name of an array with its size.
data_type array_name[Size_of_array];

Example
int arr[5];
Here,
 int: It is the type of data to be stored in the array. We can also use other
data types such as char, float, and double.
 arr: It is the name of the array.
 5: It is the size of the array which means only 5 elements can be stored in
the array.

Initialization of Array in C++


In C++, we can initialize an array in many ways but we will discuss some
most common ways to initialize an array. We can initialize an array at the
time of declaration or after declaration.
1. Initialize Array with Values in C++
We have initialized the array with values. The values enclosed in curly
braces ‘{}’ are assigned to the array. Here, 1 is stored in arr[0], 2 in arr[1],
and so on. Here the size of the array is 5.
int arr[5] = {1, 2, 3, 4, 5};
2. Initialize Array with Values and without Size in C++
We have initialized the array with values but we have not declared the length
of the array, therefore, the length of an array is equal to the number of
elements inside curly braces.
int arr[] = {1, 2, 3, 4, 5};
3. Initialize Array after Declaration (Using Loops)
We have initialized the array using a loop after declaring the array. This
method is generally used when we want to take input from the user or we
cant to assign elements one by one to each index of the array. We can
modify the loop conditions or change the initialization values according to
requirements.
for (int i = 0; i < N; i++) {
arr[i] = value;
}
4. Initialize an array partially in C++
Here, we have declared an array ‘partialArray’ with size ‘5’ and with values
‘1’ and ‘2’ only. So, these values are stored at the first two indices, and at the
rest of the indices ‘0’ is stored.
int partialArray[5] = {1, 2};
5. Initialize the array with zero in C++
We can initialize the array with all elements as ‘0’ by specifying ‘0’ inside the
curly braces. This will happen in case of zero only if we try to initialize the
array with a different value say ‘2’ using this method then ‘2’ is stored at the
0th index only.
int zero_array[5] = {0};
Accessing an Element of an Array in C++
Elements of an array can be accessed by specifying the name of the array,
then the index of the element enclosed in the array subscript operator []. For
example, arr[i].
Example 1: The C++ Program to Illustrate How to Access Array
Elements
// C++ Program to Illustrate How to Access Array Elements

#include <iostream>
using namespace std;
int main()
{

int arr[3];

// Inserting elements in an array


arr[0] = 10;
arr[1] = 20;
arr[2] = 30;

// Accessing and printing elements of the array


cout << "arr[0]: " << arr[0] << endl;
cout << "arr[1]: " << arr[1] << endl;
cout << "arr[2]: " << arr[2] << endl;

return 0;
}

Output
arr[0]: 10
arr[1]: 20
arr[2]: 30
// C++ Program to Illustrate How to Traverse an Array
#include <iostream>
using namespace std;

int main()
{

// Initialize the array


int table_of_two[10]
= { 2, 4, 6, 8, 10, 12, 14, 16, 18, 20 };

// Traverse the array using for loop


for (int i = 0; i < 10; i++) {
// Print the array elements using indexing
cout << table_of_two[i] << " ";
}

return 0;
}
Output
2 4 6 8 10 12 14 16 18 20

Example 3: The C++ Program to Illustrate How to Find the Size


of an Array
// C++ Program to Illustrate How to Find the Size of an
// Array
#include <iostream>
using namespace std;

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

// Size of one element of an array


cout << "Size of arr[0]: " << sizeof(arr[0]) << endl;

// Size of array 'arr'


cout << "Size of arr: " << sizeof(arr) << endl;

// Length of an array
int n = sizeof(arr) / sizeof(arr[0]);

cout << "Length of an array: " << n << endl;

return 0;
}
Output
Size of arr[0]: 4
Size of arr: 20
Length of an array: 5

Example 4: Illustrating the Relationship between Array and


Pointers
// C++ Program to Illustrate that Array Name is a Pointer
// that Points to First Element of the Array
#include <iostream>
using namespace std;

int main()
{
// Defining an array
int arr[] = { 1, 2, 3, 4 };

// Define a pointer
int* ptr = arr;

// Printing address of the arrary using array name


cout << "Memory address of arr: " << &arr << endl;

// Printing address of the array using ptr


cout << "Memory address of arr: " << ptr << endl;

return 0;
}
Output
Memory address of arr: 0x7fff2f2cabb0
Memory address of arr: 0x7fff2f2cabb0

Two Dimensional Array in C++


In C++, a two-dimensional
dimensional array is a grouping of elements arranged in rows
and columns. Each element is accessed using two indices: one for the row
and one for the column, which makes it easy to visualize as a table or grid.
Syntax of 2D array
data_Type array_name[n][m];
Where,
 n: Number of rows.
 m: Number of columns.

Example: The C++ Program to Illustrate the Two-Dimensional


Dimensional
Array
// c++ program to illustrate the two dimensional array
#include <iostream>
using namespace std;

int main()
{
// Declaring 2D array
int arr[4][4];

// Initialize 2D array using loop


for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
arr[i][j] = i + j;
}
}

// Printing the element of 2D array


for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
cout << arr[i][j] << " ";
}
cout << endl;
}

return 0;
}

Output
0 1 2 3
1 2 3 4
2 3 4 5
3 4 5 6

Multidimensional Array Declaration


datatypearrayName[size1][size2]…[sizeN];
where,
 datatype: Type of data to be stored in the array.
 arrayName: Name of the array.
 size1, size2,…, sizeN: Size of each dimension.
Example:
Two dimensional array: int two_d[2][4];
Three dimensional array: int three_d[2][4][8];
Size of a Multidimensional Array
The size of an array is equal to the size of the data type multiplied by the
total number of elements that can be stored in an array. We can calculate
the total number of elements in an array by multiplying the size of each
dimension of a multidimensional array.
For example:
int arr1[2][4];
 The array int arr1[2][4] can store total (2*4) = 8 elements.
 In C++ int data type takes 4 bytes and we have 8 elements in the
array ‘arr1’ of the int type.
 Total size = 4*8 = 32 bytes.
int arr2[2][4][8];
 Array int arr2[2][4][8] can store total (2*4*8) = 64 elements.
 The Total size of ‘arr2‘ = 64*4 = 256 bytes.
To verify the above calculation we can use sizeof() method to find the size of
an array.
// C++ program to verify the size of multidimensional
// arrays
#include <iostream>
using namespace std;

int main()
{
// creating 2d and 3d array
int arr1[2][4];
int arr2[2][4][8];

// using sizeof() operator to get the size of the above


// arrays
cout << "Size of array arr1: " << sizeof(arr1)
<< " bytes" << endl;
cout << "Size of array arr2: " << sizeof(arr2)
<< " bytes";

return 0;
}

Output
Size of array arr1: 32 bytes
Size of array arr2: 256 bytes

Initialization of Two-Dimensional Arrays in C++


Different ways to initialize a 2D array are given below:
 Using Initializer List
 Using Loops
1. Initialize 2D array using the Initializer list
We can initialize a 2D array using an initializer list in two ways. Below is the
first method of initializing a 2D array using an initializer list.
First Method: The below array has 2 rows and 4 columns. The elements are
filled in a way that the first 4 elements are filled in the first row and the next 4
elements are filled in the second row.
int arr[2][4] = {0, 1, 2, 3, 4, 5, 6, 7};
Second Method: The below way is the cleaner way to initialize a 2D array
the nested list represents the elements in a row and the number of elements
inside it is equal to the number of columns in a 2D array. The number of
nested lists represents the number of columns.
int x[2][4] = {{0, 1, 2, 3}, {4, 5, 6, 7}};

2. Initialization of 2D array using Loops


We can also initialize 2D array using loops. To initialize 2D array we have to
use two nested loops and nested loops are equal to the dimension. For
example, to initialize a 3D array we have to use three nested loops. Let’s see
an example.
Example: In the below example we have initializes the 2D array with 1. The
outer loop is used to track rows “i=0” means the first row because of 0
indexing similarly “j=0” means the first column and combining this x [0][0]
represents the first cell of the 2D array.
int x[2][4];
for(int i = 0; i < 2; i++){
for(int j = 0; j < 4; j++){
x[i][j] = 1;
}
}
Accessing Elements of Two-Dimensional Arrays in C++
We can access the elements of a 2-dimensional array using row and column
indices. It is similar to matrix element position but the only difference is that
here indexing starts from 0.
Syntax:
array_name[i][j];
where,
 i: Index of row.
 j: Index of the column.
Example: Below is the index of elements of the second row and third
column.
int x[1][2];
Let’s understand this using code by printing elements of a 2D array.
Example of 2D Array
// c++ program to illustrate the two dimensional array
#include <iostream>
using namespace std;

int main()
{

int count = 1;

// Declaring 2D array
int array1[3][4];

// Initialize 2D array using loop


for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
array1[i][j] = count;
count++;
}
}

// Printing the element of 2D array


for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
cout << array1[i][j] << " ";
}
cout << endl;
}

return 0;
}

Output
1 2 3 4
5 6 7 8
9 10 11 12
C++ Program to Multiply Two Matrix Using Multi-

dimensional Arrays

#include <iostream>
using namespace std;

int main()
{
int a[10][10], b[10][10], mult[10][10], r1, c1, r2, c2, i, j, k;

cout << "Enter rows and columns for first matrix: ";
cin >> r1 >> c1;
cout << "Enter rows and columns for second matrix: ";
cin >> r2 >> c2;

// If column of first matrix in not equal to row of second matrix,


// ask the user to enter the size of matrix again.
while (c1!=r2)
{
cout << "Error! column of first matrix not equal to row of second.";

cout << "Enter rows and columns for first matrix: ";
cin >> r1 >> c1;

cout << "Enter rows and columns for second matrix: ";
cin >> r2 >> c2;
}

// Storing elements of first matrix.


cout << endl << "Enter elements of matrix 1:" << endl;
for(i = 0; i < r1; ++i)
for(j = 0; j < c1; ++j)
{
cout << "Enter element a" << i + 1 << j + 1 << " : ";
cin >> a[i][j];
}
// Storing elements of second matrix.
cout << endl << "Enter elements of matrix 2:" << endl;
for(i = 0; i < r2; ++i)
for(j = 0; j < c2; ++j)
{
cout << "Enter element b" << i + 1 << j + 1 << " : ";
cin >> b[i][j];
}

// Initializing elements of matrix mult to 0.


for(i = 0; i < r1; ++i)
for(j = 0; j < c2; ++j)
{
mult[i][j]=0;
}

// Multiplying matrix a and b and storing in array mult.


for(i = 0; i < r1; ++i)
for(j = 0; j < c2; ++j)
for(k = 0; k < c1; ++k)
{
mult[i][j] += a[i][k] * b[k][j];
}

// Displaying the multiplication of two matrix.


cout << endl << "Output Matrix: " << endl;
for(i = 0; i < r1; ++i)
for(j = 0; j < c2; ++j)
{
cout << " " << mult[i][j];
if(j == c2-1)
cout << endl;
}

return 0;
}
Output

Enter rows and column for first matrix: 3


2
Enter rows and column for second matrix: 3
2
Error! column of first matrix not equal to row of second.

Enter rows and column for first matrix: 2


3
Enter rows and column for second matrix: 3
2

Enter elements of matrix 1:


Enter elements a11: 3
Enter elements a12: -2
Enter elements a13: 5
Enter elements a21: 3
Enter elements a22: 0
Enter elements a23: 4

Enter elements of matrix 2:


Enter elements b11: 2
Enter elements b12: 3
Enter elements b21: -9
Enter elements b22: 0
Enter elements b31: 0
Enter elements b32: 4

Output Matrix:
24 29
6 25

Add Two Matrices using Multi-dimensional


Arrays
#include <iostream>
using namespace std;

int main()
{
int r, c, a[100][100], b[100][100], sum[100][100], i, j;

cout << "Enter number of rows (between 1 and 100): ";


cin >> r;
cout << "Enter number of columns (between 1 and 100): ";
cin >> c;

cout << endl << "Enter elements of 1st matrix: " << endl;

// Storing elements of first matrix entered by user.


for(i = 0; i < r; ++i)
for(j = 0; j < c; ++j)
{
cout << "Enter element a" << i + 1 << j + 1 << " : ";
cin >> a[i][j];
}

// Storing elements of second matrix entered by user.


cout << endl << "Enter elements of 2nd matrix: " << endl;
for(i = 0; i < r; ++i)
for(j = 0; j < c; ++j)
{
cout << "Enter element b" << i + 1 << j + 1 << " : ";
cin >> b[i][j];
}

// Adding Two matrices


for(i = 0; i < r; ++i)
for(j = 0; j < c; ++j)
sum[i][j] = a[i][j] + b[i][j];

// Displaying the resultant sum matrix.


cout << endl << "Sum of two matrix is: " << endl;
for(i = 0; i < r; ++i)
for(j = 0; j < c; ++j)
{
cout << sum[i][j] << " ";
if(j == c - 1)
cout << endl;
}

return 0;
}
Output

Enter number of rows (between 1 and 100): 2


Enter number of columns (between 1 and 100): 2

Enter elements of 1st matrix:


Enter element a11: -4
Enter element a12: 5
Enter element a21: 6
Enter element a22: 8

Enter elements of 2nd matrix:


Enter element b11: 3
Enter element b12: -9
Enter element b21: 7
Enter element b22: 2

Sum of two matrix is:


-1 -4
13 10

Strings in C++
C++ strings are sequences of characters stored in a char array. Strings are
used to store words and text. They are also used to store data, such as
numbers and other types of information. Strings in C++ can be defined either
using the std::string class or the C-style character arrays.
std::string Class
These are the new types of strings that are introduced in C++ as std::string
class defined inside <string> header file. This provides many advantages
over conventional C-style strings such as dynamic size, member functions,
etc.
Syntax:
std::string str("GeeksforGeeks");
Example:
// C++ program to create std::string objects
#include <iostream>
using namespace std;

int main()
{

string str("GeeksforGeeks");
cout << str;
return 0;
}
Output
GeeksforGeeks

One more way we can make strings that have the same character repeating
again and again.
Syntax:
std::string str(number,character);
Example:
#include <iostream>
using namespace std;

int main()
{
string str(5, 'g');
cout << str;
return 0;
}
Output:
ggggg

Ways to Define a String in C++


Strings can be defined in several ways in C++. Strings can be accessed from
the standard library using the string class. Character arrays can also be used
to define strings. String provides a rich set of features, such as searching
and manipulating, which are commonly used methods. Despite being less
advanced than the string class, this method is still widely used, as it is more
efficient and easier to use. Ways to define a string in C++ are:
 Using String keyword
 Using C-style strings
1. Using string Keyword
It is more convenient to define a string with the string keyword instead of
using the array keyword because it is easy to write and understand.
Syntax:
string s = "GeeksforGeeks";
string s("GeeksforGeeks");
Example:
// C++ Program to demonstrate use of string keyword
#include <iostream>
using namespace std;

int main()
{

string s = "GeeksforGeeks";
string str("GeeksforGeeks");

cout << "s = " << s << endl;


cout << "str = " << str << endl;

return 0;
}

Output
s = GeeksforGeeks
str = GeeksforGeeks

2. Using C-style strings


Using C-style string libraries functions such as strcpy(), strcmp(), and strcat()
to define strings. This method is more complex and not as widely used as
the other two, but it can be useful when dealing with legacy code or when
you need performance.
char s[] = {'g', 'f', 'g', '\0'};
char s[4] = {'g', 'f', 'g', '\0'};
char s[4] = "gfg";
char s[] = "gfg";
Example:
// C++ Program to demonstrate C-style string declaration
#include <iostream>
using namespace std;

int main()
{

char s1[] = { 'g', 'f', 'g', '\0' };


char s2[4] = { 'g', 'f', 'g', '\0' };
char s3[4] = "gfg";
char s4[] = "gfg";

cout << "s1 = " << s1 << endl;


cout << "s2 = " << s2 << endl;
cout << "s3 = " << s3 << endl;
cout << "s4 = " << s4 << endl;

return 0;
}

Output
s1 = gfg
s2 = gfg
s3 = gfg
s4 = gfg

How to Take String Input in C++


String input means accepting a string from a user. In C++. We have different
types of taking input from the user which depend on the string. The most
common way is to take input with cin keyword with the extraction operator
(>>) in C++. Methods to take a string as input are:
 cin
 getline
 stringstream
1. Using Cin
The simplest way to take string input is to use the cin command along with
the stream extraction operator (>>).
Syntax:
cin>>s;
Example:
// C++ Program to demonstrate string input using cin
#include <iostream>
using namespace std;

int main() {

string s;

cout<<"Enter String"<<endl;
cin>>s;

cout<<"String is: "<<s<<endl;


return 0;
}

Output
Enter String
String is:
Output:
Enter String
GeeksforGeeks
String is: GeeksforGeeks
2. Using getline
The getline() function in C++ is used to read a string from an input stream. It
is declared in the <string> header file.
Syntax:
getline(cin,s);
Example:
// C++ Program to demonstrate use of getline function
#include <iostream>
using namespace std;

int main()
{

string s;
cout << "Enter String" << endl;
getline(cin, s);
cout << "String is: " << s << endl;
return 0;
}

Output
Enter String
String is:
Output:
Enter String
GeeksforGeeks
String is: GeeksforGeeks
3. Using stringstream
The stringstream class in C++ is used to take multiple strings as input at
once.
Syntax:
stringstream stringstream_object(string_name);
Example:
// C++ Program to demonstrate use of stringstream object
#include <iostream>
#include <sstream>
#include<string>

using namespace std;

int main()
{

string s = " GeeksforGeeks to the Moon ";


stringstream obj(s);
// string to store words individually
string temp;
// >> operator will read from the stringstream object
while (obj >> temp) {
cout << temp << endl;
}
return 0;
}

Output
GeeksforGeeks
to
the
Moon

You might also like