Create An Array Of Number In C++
Code snippet for how to Create An Array Of Number In C++ with sample and detail explanation
Learning to create an array of numbers in C++ is important for those wanting to dive deeper into data management within their programs. This article will provide you with a concise guide on how to proceed with this task.
Code snippet: Creating an Array in C++
Here is a simple code snippet that demonstrates how to create an array of numbers in C++:
#include<iostream>
using namespace std;
int main() {
int numbers[5] = {1, 2, 3, 4, 5};
for(int i=0; i<5; i++){
cout << numbers[i] << endl;
}
return 0;
}
Code Explanation: Creating an Array in C++
Let’s look at the code step by step and understand what’s going on exactly.
-
#include<iostream>
: This is the preprocessor directive used to include the contents of iostream file in the program. iostream is a file that contains codes of the predefined objects used for standard I/O operations. -
using namespace std;
: The namespace std is used to call out the functions that are defined within the scope of std. -
int main()
: This is the beginning of the main function which is the entry point of any C++ program. -
int numbers[5] = {1, 2, 3, 4, 5};
: This creates an array of integers. The array is named ‘numbers’ and has a size of 5. It contains five elements in which are respectively 1, 2, 3, 4, and 5. -
The loop
for(int i=0; i<5; i++){cout << numbers[i] << endl;}
is used to iterate through the array. In each iteration, we output the correspondingnumbers[i]
. Theendl
is used to insert a new line after each output to format the display. -
return 0;
: This statement terminates the main function and returns the value 0.
Here we’ve successfully created an array and displayed its contents, giving a quick tutorial on a key facet of utilizing data in C++. Practice with different array sizes and contents for better comprehension.