Latin Square in C++

C++Server Side ProgrammingProgramming

In this tutorial, we are going to learn about the Latin square.

The latin square is a matrix (3 x 3) in the form

1 2 3

3 1 2

2 3 1

If you carefully observe the pattern of the above matrix, then you will find out that the last number of the previous row comes as the first element of the next row.

We have to write the program that generates the above matrix for the input n.

Let's see the steps to write the program for the generation of the latin square.

• Initialise the n with any number you like.
• Initialise a number with the value n + 1 call it as mid.
• Write a loop that iterates from 1 to n both inclusive.
• Assign the value of mid to a temp variable.
• Write a loop until temp reaches to the value n.
• Print the temp.
• Write a loop that iterates from 1 to mid
• Print the value.
• Decrement the value of mid by 1.

Let's see the code.

Live Demo

#include <bits/stdc++.h>
using namespace std;
void generateLatinSquare(int n) {
int mid = n + 1;
for (int i = 1; i <= n; i++) {
int temp = mid;
while (temp <= n) {
cout << temp << " ";
temp++;
}
for (int j = 1; j < mid; j++) {
cout << j << " ";
}
mid--;
cout << endl;
}
}
int main(void) {
generateLatinSquare(2);
cout << endl;
generateLatinSquare(3);
cout << endl;
generateLatinSquare(4);
cout << endl;
return 0;
}

If you run the above code, then you will get the following result.

1 2
2 1

1 2 3
3 1 2
2 3 1

1 2 3 4
4 1 2 3
3 4 1 2
2 3 4 1

Conclusion

If you have any queries in the tutorial, mention them in the comment section.

Published on 26-Jun-2021 13:52:31