Loops are causing mayhem in the code.

I was working on this logic to sort 2D arrays when I came across a problem. For some reason, the compiler would freeze up when it attempted to do so. I had this same exact problem with another code where it would do the exact thing.

So, I erased the code and began testing. I first checked a nested for loop, which was giving output. Using an if statement was working too. But the moment I used the second loop variable, it started freezing again. What is the issue here? Can somebody help me out?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <fstream>
using namespace std;

int main()
{

	for (int i = 0; i < 3; i++)
	{
		for (int j = 0; j < 3; j++)
		{
			if (i == 0)
			{
				cout << "It works" << endl;
				if (j == 0)
				{
					cout << "Second One works" << endl;
				}
			}
		}
	}
	cout << endl;
}
Last edited on
the code you posted is fine.
Trying to sort a true 2D container in its entirety is a pain-in-the-tuchas, simulating 2D in 1D would be an easier task.

But it is possible:
https://stackoverflow.com/questions/19237419/sorting-2d-array-c

Row-wise sorting would be easier, marginally.
it depends on how you want it sorted. if you can swap entire rows via a pointer, it saves some work for approaches where that is meaningful. If you want it strictly sorted where [0][0] < [0][1] ... -> that is where ( [N][M] < [N][M+1] or if last in a row [N+1][0]) then collapse to 1d is highly recommended. But it sounds like its not a sorting problem but a looping one... that was not demonstrated in the sample so its hard to help fix.
The output is a bit "strange," courtesy of the (il)logic of the nested if statements. Did you want something like this instead?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>

int main()
{
   for (int row { }; row < 3; row++)
   {
      if (row == 0)
      {
         std::cout << "Row " << row << " works\n";
      }

      for (int col { }; col < 3; col++)
      {
         if (col == 0)
         {
            std::cout << "Column " << col << " works\n";
         }
      }
   }
   std::cout << '\n';
}
Row 0 works
Column 0 works
Column 0 works
Column 0 works


Topic archived. No new replies allowed.