In: Computer Science
How to make an array without setting size?c++
cant figure this out without wanting to make a vector or set a fixed size to the numbers.
Prompt the user to ask how many numbers you wish to read. Then based on that fill out the elements of one dimensional array with integer numbers. Then sort the numbers and print the original and sorted numbers in ascending order side by side.
Ans
code:-
#include <iostream>
using namespace std;
int main()
{
int n;
cout << "Enter size of Array"<<endl;
cin>>n;
int a[n];
cout<<"Enter "<<n<<" elements"<<endl;
for(int i=0;i<n;i++)
cin>>a[i];
cout<<"Elements of Array are:"<<endl;
for(int i=0;i<n;i++)
cout<<a[i]<<" ";
cout<<endl;
//sort
for(int i=0;i<n-1;i++){
for(int j=0;j<n-i-1;j++){
if(a[j+1]<a[j]){
int temp=a[j+1];
a[j+1]=a[j];
a[j]=temp;}
}
}
cout<<"Elements of Array after sorting are:"<<endl;
for(int i=0;i<n;i++)
cout<<a[i]<<" ";
return 0;
}
Input from user store in variable then declare array with size of that variable.
If any doubt ask in the comments.