Although, with some changes, your code may works, but as you have hardcoded the constant 5
into your code (for instance, for( j =5*i; j>(5*(i-1));j--)
has a lot of 5
inside the for
-loop), it'll be likely that the program will only print correctly when n=5
.
So, a simpler solution:
- Calculate the starting and ending value of each line
- If
i%2==1
then print the line in normal order, else print it in reverse order
Not only this solution would be shorter, it'll be more versatile if n
were to change.
Code:
#include <iostream>
void printRow(int l, int r, int mode) //function to print a line
{
if (mode == 1) {for (int i = l; i <= r; i++) {std::cout << i << " ";} std::cout << '\n';} //normal order
else if (mode == 2) {for (int i = r; i >= l; i--) {std::cout << i << " ";} std::cout << '\n';} //reverse order
}
int main()
{
std::cout << "Input N : "; int n; std::cin >> n;
for (int i = 1; i <= n; i++)
{
int l = n*(i-1)+1, r = l+n-1, mode = (i%2==0) ? 2 : 1; //calculate the starting and ending point of a line
printRow(l, r, mode); //print that line
}
}
Result:
Input N : 5
1 2 3 4 5
10 9 8 7 6
11 12 13 14 15
20 19 18 17 16
21 22 23 24 25
Result (2):
Input N : 10
1 2 3 4 5 6 7 8 9 10
20 19 18 17 16 15 14 13 12 11
21 22 23 24 25 26 27 28 29 30
40 39 38 37 36 35 34 33 32 31
41 42 43 44 45 46 47 48 49 50
60 59 58 57 56 55 54 53 52 51
61 62 63 64 65 66 67 68 69 70
80 79 78 77 76 75 74 73 72 71
81 82 83 84 85 86 87 88 89 90
100 99 98 97 96 95 94 93 92 91
Also, see Why is "using namespace std;" considered bad practice?