Append Item In Array In C++
Code snippet for how to Append Item In Array In C++ with sample and detail explanation
In this article, we will focus on how to append an item into an array in C++. This tutorial is aimed at individuals who have basic knowledge of C++ and want to understand how to manipulate arrays effectively.
Code snippet for Appending Item in Array in C++
#include<iostream>
using namespace std;
int main()
{
int arr[5] = {1, 2, 3, 4, 5};
// Append 6 into the array
arr[5] = 6;
for (int i = 0; i < 6; i++)
cout << arr[i] << " ";
return 0;
}
Code Explanation for Appending Item in Array in C++
In the code snippet above, we start by including the <iostream>
library. This header file is used for handling the input-output operations in C++. The “using namespace std” is used to save the programmer from continuously using “std” before each C++ standard library object.
#include<iostream>
using namespace std;
We then define the main function which is the entry point of our program.
int main()
{
// code
}
Inside the main function, we declare an array of integers “arr” with a size of 5 and initialize it with values 1 through 5.
int arr[5] = {1, 2, 3, 4, 5};
Next, we append an integer 6 into the array at the 6th index. Here, it’s important to note that C++ uses a 0-based index, that means the first position of the array starts at “0”.
arr[5] = 6;
After, we loop through the array printing each item on the screen. The for loop runs from i=0 till i=5 (which is less than 6).
for (int i = 0; i < 6; i++)
cout << arr[i] << " ";
Finally, our program ends returning 0 from the main function, indicating that the program has been executed successfully.
return 0;
By understanding and using this simple code snippet, you will be able to append items into arrays in C++.