#include <iostream>
usingnamespace std;
int main()
{
int arr[10];
int n;
cout<<"Enter the number of elements of array"<<endl;
cin>>n;
cout<<"Enter the elements of array"<<endl;
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
for(int i=0;i<=n-1;i++)
{
for(int j=0;j<=n-1-i;j++)
{
if(arr[j]>arr[j+1])
{
int temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
cout<<"Elements after sorting are"<<endl;
for(int i=0;i<=n-1;i++)
{
cout<<arr[i];
}
}
int main()
{
constint MAXSZ = 10 ;
int arr[MAXSZ] ;
int n;
cout << "Enter the number of elements of array " ;
cin >> n ;
if( n > MAXSZ ) n = MAXSZ ; // *** added: limit n to size of array
// ...
Though this is fine: for(int i=0;i<=n-1;i++) (when n is a signed integer)
Prefer the canonical form that is commonly seen, one that is familiar to programmers. for( int i = 0 ; i<n ; ++i )
for eg...if i enter 5 elements..say..8 1 4 2 3...elements that i get after sorting are 0 1 2 3 4...from wheredoes this 0 cum from n why isnt 8 displayed?
for(int i=0;i<=n-1;i++)
{
for(int j=0;j<=n-1-i;j++)
{
if(arr[j]>arr[j+1]) // here is the problem
{
Actually this is a common overflow error, when i=0, then j could reach n-1-i which equals to n-1, but in the next line we compared arr[j] with arr[j+1], but j+1=(n-1)+1=n, this is a overflow since arr doesn't have this element.
Boundaries should be treated very carefully, it could cause some kind of fancy problems.