Thread: array problem

1. array problem

Greetings,
I just got this email back from a teacher saying "the exercise asks you to show the values of all the array elements. Your output is a string of numbers with no spaces. I cannot identify the values of all the array elements. Make your output readable.

What? can you look and tell me am I wrong? I value all your input. I think its right but i am unsure of whats wrong with it?

Code:
```#include <iostream>	//cin, cout, <<, >>
#include <string>	// for strings

using namespace std;

const int LITTLE = 6,	//Word LITTLE equals 6
MEDIUM = 10,	//Word MEDIUM equals 10
BIG = 128;	//Word BIG equals 128

int i, j, n = 9,	//integers with n being initalized to number 9.
temp,
number[MEDIUM] = { 99, 33, 44, 88, 22, 11, 55, 66, 77};	//array of numbers

char ch,	// characters
letterCount[BIG];	// array BIG

typedef double LittleDouble[LITTLE];	//redefined array LITTLE to LittleDouble

LittleDouble value;

int main()
{
for (i = 0; i < n - 1; i++)	//initlaizes i = 0, n = 9, increase i.
{
for (j = i; j < n - 1; j++)	//initlaizes j = 0, n = 9, increase i.
if (number[j] > number[j + 1])
{
temp = number[j];
number[j] = number[j + 1];
number[j + 1] = temp;
}

}

cout << "this is for array number["<< j <<"] = " << number[j] << '\n'
<< "this is for array number["<< j+1 <<"] = " << number[j+1] <<'\n';
return 0;
}```

2. Obviously, you have a bad formatting, ie:

If you have the values 1 2 45 67 123 8 in your array, they are outputted like this: 1245671238, which makes it impossible to see what numbers are in there.

But I can't see why this would happen in your program, since you never print all elements. Perhaps you should move that cout into the loop?

3. Thanks Magos!

Perhaps you should move that cout into the loop?
Can i ask why we should do that? I am curious.

Can you please ellaborate further so i can better understand?
Thanks!
cj

4. Well, I assume that you want to print all elements with that cout? Then you have to place it inside a loop, otherwise it will only print the element of j:s current value (probably the last element).

5. If you want to print the contents of an array (or even a vector!), then you can use a few STL tricks to do it easilly

Code:
```#include <iostream>
#include <algorithm>

int main(int argc, char* argv[])
{

int arr[] = {1,2,3,4,5,6};

std::copy(arr,arr + (sizeof(arr)/sizeof(arr[0])),
std::ostream_iterator<int>(std::cout," "));
}```

6. Thanks everybody!

That cleared up my question?
Thanks for the help!

Popular pages Recent additions