R
Radhika Sambamurti
Hi,
I'm a relative newbie....
I've written a program to do a bubble sort. take in numbers and sort them.
My question is: at the very end of the sort() function, when I have to output the result to stdout, the only code that does this correctly is as follows:
//output of sorted array
for(i=1; i<n+1; i++)
{
cout << "value of i is: " << num_array << endl;
}
}
When i tried saying - for(i=0; i<n; i++),
the zero'th element was some hex garbage (being the address of the array i assume) and only sub[1,2,3,4] were output. So why does num_array[0] give me hex? I used gdb to debug this, but this just verifies my findings. I would like to know why.
Thank you,
Radhika
/////Code below//////////////////////////
//Sorting in ascending
#include <iostream>
using namespace std;
const int SIZE= 5;
void sort(int number[], const int SIZE); //prototype never takes array size
int main()
{
int number[SIZE] = {49,19,23,69,7};
sort(number, SIZE); //Function call with array
//always only array name
return 0;
}
///////// Function sort()
void sort(int num_array[SIZE], const int n)
{
int temp, i;
for(int k=0; k<n; k++) // outer loop
{
for(int j=0; j<n; j++) //inner loop
{
if(num_array[j] > num_array[j+1])
{
temp = num_array[j];
num_array[j] =num_array[j + 1];
num_array[j + 1] = temp;
//swapping the variables to make
//into ascending order
}
}
}
//output of sorted array
for(i=1; i<n+1; i++)
{
cout << "value of i is: " << num_array << endl;
}
}
I'm a relative newbie....
I've written a program to do a bubble sort. take in numbers and sort them.
My question is: at the very end of the sort() function, when I have to output the result to stdout, the only code that does this correctly is as follows:
//output of sorted array
for(i=1; i<n+1; i++)
{
cout << "value of i is: " << num_array << endl;
}
}
When i tried saying - for(i=0; i<n; i++),
the zero'th element was some hex garbage (being the address of the array i assume) and only sub[1,2,3,4] were output. So why does num_array[0] give me hex? I used gdb to debug this, but this just verifies my findings. I would like to know why.
Thank you,
Radhika
/////Code below//////////////////////////
//Sorting in ascending
#include <iostream>
using namespace std;
const int SIZE= 5;
void sort(int number[], const int SIZE); //prototype never takes array size
int main()
{
int number[SIZE] = {49,19,23,69,7};
sort(number, SIZE); //Function call with array
//always only array name
return 0;
}
///////// Function sort()
void sort(int num_array[SIZE], const int n)
{
int temp, i;
for(int k=0; k<n; k++) // outer loop
{
for(int j=0; j<n; j++) //inner loop
{
if(num_array[j] > num_array[j+1])
{
temp = num_array[j];
num_array[j] =num_array[j + 1];
num_array[j + 1] = temp;
//swapping the variables to make
//into ascending order
}
}
}
//output of sorted array
for(i=1; i<n+1; i++)
{
cout << "value of i is: " << num_array << endl;
}
}