Programming technique

I am curious as to what others think of how I went about this:

I defined a multi dimensional array, and then outputted it in the middle of a program. Instead of outputting it VIA a string, I chose to output it using programming loops, and it outputs exactly as it was declared, without the type and name.

Feedback on my form if you don't mind:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
	//multidimensional array
	int y[3][3] = {{1,2,3},{4,5,6},{7,8,9}};
	
	//output the array
	cout << "The array contains: ";
	for(int s = 0; s < 3; s++)
	{
		for(int k = 0; k < 3; k++) 
		{
			if(s == 2 && k == 2) cout << y[2][2] << "}}";
			else if(s == 0 && k == 0) cout << "{{" << y[0][0] << ",";
			else 
			{
				if(k == 0) cout << "{";
				cout << y[s][k] << ",";
				if(k == 2) cout << "\b},";
			}
		}
	}
Last edited on
Why do you have a "int z" the second loop?

Otherwise you did fine! It works just as you want it to right?
Here, I made a version stripping out some conditions just to see if you can get away without some!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
using namespace std;

int main()
{
  //multidimensional array
  int array[3][3] = {{1,2,3},{4,5,6},{7,8,9}};

  //output the array
  cout << "The array contains: {";
  for(int i = 0; i < 3; ++i)
    for(int k = 0; k < 3; ++k)
    {
      if(k == 0) cout << "{";
      cout << array[i][k] << ", ";
      if(k == 2 && i != 2) cout << "\b\b}, ";
    }

  cout << "\b\b}}" << endl;
}


Edit: More fun, It now allows you to do any size array in the output. Heres it with 4. It cuts off in console with the numbers I used, but its interesting none-the-less.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
using namespace std;

int main()
{
  const int n = 4;
  //multidimensional array
  int array[n][n] = {{1,2,3,32},{4,5,6,33},{7,8,9,34},{10,11,12,35}};

  //output the array
  cout << "The array contains: {";
  for(int i = 0; i < n; ++i)
    for(int k = 0; k < n; ++k)
    {
      if(k == 0) cout << "{";
      cout << array[i][k] << ", ";
      if(k == n-1 && i != n-1) cout << "\b\b}, ";
    }

  cout << "\b\b}}" << endl;
}

Last edited on
Of course, Thanks for pointing that out, the 'z'. I had left that in on accident, I was trying different methods of testing which number it was outputting, to put appropriate braces.

Also! Your second code is adorable, I love that :)
Last edited on
Topic archived. No new replies allowed.