Help

Hi Why i get a[0]=55? I sorted arrays then i want to unite them in m[20] array i get correct numbers but at last i checked a[j] and it gives me first element 55 wich i dont know how and why.

int main()
{
int a[10] = { 1 , -5 , 20 , -2 , 4 , 75 , -3 , 85 , 9 , 21 };
int b[10]={ 13 , -1 , 10 , -22 , 14 , 45 , -6 , 55 , 11 , 41 };
int m[20];
int i, j, temp, temp2, x;
cout << "pirveli" << endl;
for(i=0;i<10;i++)
{
for(j=0;j<10;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
for(j=0;j<10;j++)
{
cout<<a[j] << " " << endl;
}
for(i=0;i<10;i++)
{
for(j=0;j<10-i;j++)
{
if(b[j]>b[j+1])
{
temp=b[j];
b[j]=b[j+1];
b[j+1]=temp;
}
}
}
cout<< "meore \n";
for(j=0;j<10;j++)
{
cout<< b[j] << " " << endl;
}
cout << " sirobaa" << endl;
for(j=0;j<10;j++)
{
cout<<a[j] << " " << endl;
}


return 0;
}
Last edited on
When j is 9 you read a[10]

That location is off the end of your array. There could be any value in it.

Do not read a[10]
dont undertand y i know that array start from 0 to 9 and j<10 not j<=10 why first element is different and how it correct?
if(a[j]>a[j+1])
If j is 9 you access a[10]
omg last for loop for a[j] shows incorect numbers can you correct code? thank you
j<9
@Georg31
At C++ you don't need to fiddle with error prone arrays/pointers. Here a solution using c++ standard library facilities:
1
2
3
4
5
6
7
8
9
10
11
#include <array>
#include <iostream>
#include <algorithm>

int main()
{
    std::array<int,10> a{ 13 , -1 , 10 , -22 , 14 , 45 , -6 , 55 , 11 , 41 };
    std::sort(a.begin(), a.end());  // That's the standard way sorting stuff at C++
    for (auto & val : a) std::cout << val << " ";
   
}
Topic archived. No new replies allowed.