Hi Everyone!
i have a small program here,i let the user choose the size of the 1D array and it's elements and if they want to print it they should press 1.. now the problem is whenever i run the program for loops don't run as intended and i get weird outputs.. what is wrong ?
#include <iostream>
usingnamespace std;
int main()
{
int a[0];
int c;
int k,j,size;
cout<<"enter the size of the array \n";
cin>>size;
for(k=0; k<size;k++)
{
cout<<"enter the element "<< k + 1<<endl;
cin>>a[k];
}
cout<<"to print the array press 1 \n";
cin>>c;
if(c == 1)
{
for(k=0;k<size;k++)
{
cout<<a[k];
cout<<" ";
}
}
return 0;
}
int a[0]; creates an array with zero elements in it, and no way to change the number. You are getting "weird output" because you are going out of bounds no matter what size the user chooses.
Your compiler should give you a warning you are out-of-bounds with the array.