The question asks you to travel around a 4x3 matrix in a inward spiraling path verifying that each set of two numbers can be added or subtracted to get the next number in the path - where the first value of each set of two numbers is the result of the previous operation.
If this is the matrix:
a b c d
e f g h
i j k l
Then the path is:
a b c d h l k j i e f g h
And the algorithm is:
a +- b = c
c +- d = h
h +- l = k
k +- j = i
i +- e = f
f +- g = h
If those are all equal then it is a valid sequence. Otherwise you print "invalid sequence"
So you could just make the program into one huge if statement:
if( (a + b == c || a - b == c) &&
(c + d == h || c - d == h) &&
(h + l == k || h - l == k) &&
(k + j == i || k - j == i) &&
(i + e == f || i - e == f) &&
(f + g == h || f - g == h) )
{
// print the path
}
else
{
// print "invalid sequence"
}
If you do that you don't need any loops or anything.
But like @macroland said, you could convert the 2D matrix to a 1D matrix. How to do this isn't the most obvious thing to do because it isn't as easy as top to bottom, left to right but it is relatively straight forward after you think of a method. The most stright forward way I can think of is to hard code the path taken like this:
int a[3][4] = {{ 2, 3, 5, 8 },
{ 5, 2, 5, -3 },
{ 7, 0, 7, 10 }};
int b[13]; // the output array
int x[13] = {0,1,2,3,3,3,2,1,0,0,1,2,3};
int y[13] = {0,0,0,0,1,2,2,2,2,1,1,1,1};
for(int i=0;i<13;i++) b[i]=a[y[i]][x[i]];
That of course relies on the fact you know it is always a 4x3 matrix. If you do that you get something equivalent to this:
int b[13] = { 2, 3, 5, 8, -3, 10, 7, 0, 7, 5, 2, 5, -3 };
Then you can easily make a single for loop that checks that each operation in the path works.
If it isn't always a 4x3 matrix you can change the code to dynamically create the path instead of hard coding it so this approach could be made to work with any size matrix - the one huge if statement approach really couldn't.
I do have a full solution if you need to see if but you specifically asked that it not be included.
Edit:
Now that it has been a while, here is the complete program that I made in case it is helpful to someone else:
#include <sstream>
#include <iostream>
int a[3][4] = {{ 2, 3, 5, 8},
{ 5, 2, 5,-3},
{ 7, 0, 7,10}};
int b[13];
void convert_array()
{
int x[13] = {0,1,2,3,3,3,2,1,0,0,1,2,3};
int y[13] = {0,0,0,0,1,2,2,2,2,1,1,1,1};
for(int i=0;i<13;i++) b[i]=a[y[i]][x[i]];
}
int main()
{
std::stringstream s;
convert_array();
s << b[0];
for(int i=1;i<12;i+=2)
{
if(b[i-1]+b[i]==b[i+1])
s << " + " << b[i] << " = " << b[i+1];
else if(b[i-1]-b[i]==b[i+1])
s << " - " << b[i] << " = " << b[i+1];
else
{
std::cout << "invalid sequence" << std::endl;
break; // return 1;
}
}
std::cout << s.str() << std::endl;
return 0;
}