What is a One-Dimensional Array?
How To Declare a One-Dimensional Array?
- If you have created integer-type data then you can store only integer-type values.
- The size of an array must be known in advance and you cannot change this at run time.
- You can only use positive integer values to define the size of the array and floating or negative values are not allowed.
How To Initialize One-Dimensional Array?
1. Declared the data type and size of the array and you can initialize the array element inside curly brackets. The number of Elements in the brackets must be less or equal to the size of the array.
int arr[5] = {3, 4, 6, 9, 2};
2. No need to declare the array size in advance you can directly initialize the array elements inside curly brackets. The size of the array is going to depend upon the number of elements present in the brackets.
int arr[] = {23, 5, 6, 12, 1};
3. Declare the array with the number of elements you want to store in that array and then use the index value to initialize the element one by one.
int arr[5];
arr[0] = 13;
arr[1] = 5;
arr[2] = 6;
arr[3] = 7;
arr[4] = 12;
4. First declare the array with the number of elements you want to store, and then you run a for-loop and initialize the array by taking input value from the user.
int arr[6];
for(int i = 0; i < 6; i++){
cin >> arr[i];
}
(getButton) #text=(How To Pass Array to Function in C++) #icon=(link) #color=(#2339bd)
How To Traverse One-Dimensional Array?
Traversing is a process of visiting each element of the array at least once. To perform this operation we simply use a for loop that is going to run n times where n is the number of elements present in the array.
C++ Program to Traverse One-Dimensional Array
#include<iostream> using namespace std; int main(){ //Initialising 1D Array int arr[] = {31, 5, 9, 11, 2, 20}; //No. of elements present in the array int n = sizeof(arr)/sizeof(arr[0]); //Traverse array elememts for(int i = 0; i < n; i++){ cout<<arr[i]<<" "; } }
Output:
31 5 9 11 2 20
You can use the sizeof() operator to find the number of elements present in an Array. Below is the syntax for calculating this.
int num = sizeof(name_of_array)/sizeof(name_of_array[0])
No comments:
Post a Comment