0 works

Creating an variable array in C++


dashboard+ Project

Posted by @khan #c++

Step 0: The basic syntax of defining a one-dimensional array with a fixed number of elements:

#include<iostream>                //including input/output libarary
using namespace std;
int main(){                               //starting main function
int array_name[5];                   //defining a variable array of type integer with name "array_name" and size 5.
array_name[0]=2;                   //assigning value of 2 to  first element of array "array_name"
array_name[1]=3;                   
array_name[2]=4                      // assinging values to other elements of array using their index number
array_name[3]=12;
array_name[4]=33;

return 0;
}
content_copyCopy to Clipboard

Step 1: Using the variable size of the array:

#include<iostream>                           //including input/output libarary
using namespace std;
int main(){                                            //starting main function
int size;                                                //defining a variable of type integer for size of array
int array_name[size];                   //defining a variable array of type integer with name "array_name" and size "size".
cin>>size;                                // taking input from user for  size of array

/* when you are using an array of variable size then in those cases you need to take input for array elements from the user so you can use "for" loop to take input from user*/

for (int i=0; i<size: i++){                          //defining the parameters of a for loop to get values of  array elements

           cin>> array[i];                               //taking input for each value of "i".
}


return 0;
}
content_copyCopy to Clipboard

Step 2: Using Multidimensional array:

#include<iostream>                //including input/output libarary
using namespace std;
int main(){                               //starting main function
int array_name[2][2];                   //defining a variable array of type integer with name "array_name" and size 2 by 2
                                                    // we can also use variable size for multidimensional arrays too
array_name[0][0]=5;
array_name[0][1]=23;                   //assigning values to each element of array
array_name[1][0]=3;                     //two dimentional ararys are used for defining elements of a matrix
array_name[1][1]=1
return 0;
}
content_copyCopy to Clipboard

More details:

We can create an array of a variable of fixed or variable length and it can be one dimensional or multi-dimensional depending on our requirement. For example, to save elements of a series, we use a one-dimensional array but to save elements of a matrix, we need two dimensions.

Code snippet source:

,

>> Browse more code snippets

more_vert