Write a function that will take an integer argument say n. n ranges from 2 <= n <= 100
The function would not take any argument from the user. the function should print the pattern according to the value of n.
Let's say if
n = 3 so output should be.
1*2*3
7*8*9
4*5*6
n = 4
1*2*3*4
9*10*11*12
13*14*15*16
5*6*7*8
n = 5
1*2*3*4*5
11*12*13*14*15
21*22*23*24*25
16*17*18*19*20
6*7*8*9*10
and so on. . .
Without using STL Stack
void showPattern(int n)
{
int *arr = (int*)malloc(n * sizeof(int));
int toggle = 1;
int k;
int top = -1;
for (int i = 0; i < n; i++) {
k = i*n + 1;
if (toggle) {
for (int j = 0; j < n; j++) {
if (k < n || k%n)
cout << k << "*";
else
cout << k;
k++;
}
cout << endl;
toggle = 0;
}
else {
top++;
arr[top] = i;
toggle = 1;
}
}
while (top != -1) {
k = arr[top] * n + 1;
for (int i = 0; i < n; i++) {
if (k < n || k%n)
cout << k << "*";
else
cout << k;
k++;
}
cout << endl;
top--;
}
}
Using STL Stack
void showPattern(int n)
{
stack <int> stk;
int itr, toggle = 1;
for (int i = 0; i < n; i++) {
if (toggle) {
itr = i*n + 1;
for (int j = 0; j < n; j++) {
if (itr < n || itr%n) {
cout << itr << "*";
}
else {
cout << itr;
}
}
cout << endl;
toggle = 0;
}
else {
stk.push(i);
toggle = 1;
}
}
int i;
while (!stk.empty()) {
itr = stk.top()*n + 1;
stk.pop();
for (int j = 0; j < n; j++) {
if (itr < n || itr%n) {
cout << itr << "*";
}
else {
cout << itr;
}
}
cout << endl;
}
}
n. And then decreasing from 1 (if n is even) or 2 (if n is odd) less thann. So firstly, do I need to find out whether the number is even or odd? \$\endgroup\$ns. You just print the odd lines starting at1until you hit some limit (n/2?) with a simpleforloop and then the even values fromn/2starting atn/2(rounded down?) until you reach 0 with a secondforloop. You just need to try to not make off-by-1 errors and test your solution properly. \$\endgroup\$itr, that is, ifnis (say 5) so the first number in a row will ben*itr+1, which is 1*2*3*4*5, that meansitris 0, so the starting is from 0 and changing as (ifnis 5) 0, 2, 4, 3, 1. So the maximum limit is that even number which is less thann(4 in this case) so we can't say it isn/2as if we taken = 4so it will change as 0,2,3,1. So here it isn/1, so it depends on whether the number is even or odd. \$\endgroup\$