Print a pattern without using any loop - GeeksforGeeks
Given a number n, print following pattern without using any loop.
We can use two print statements. First one before recursive call that prints all decreasing sequence. Second one after the recursive call to print increasing sequence.
Read full article from Print a pattern without using any loop - GeeksforGeeks
Given a number n, print following pattern without using any loop.
Input: n = 16 Output: 16, 11, 6, 1, -4, 1, 6, 11, 16 Input: n = 10 Output: 10, 5, 0, 5, 10
We basically first reduce 5 one by one until we reach a negative or 0. After we reach 0 or negative, we one one add 5 until we reach n.
The code uses a flag variable to indicate whether we are moving toward 0 or we are moving toward back to n.// Recursive function to print the pattern.
// n indicates input value
// m indicates current value to be printed
// flag indicates whether we need to add 5 or
// subtract 5. Initially flag is true.
void
printPattern(
int
n,
int
m,
bool
flag)
{
// Print m.
cout << m <<
" "
;
// If we are moving back toward the n and
// we have reached there, then we are done
if
(flag ==
false
&& n ==m)
return
;
// If we are moving toward 0 or negative.
if
(flag)
{
// If m is greater, then 5, recur with true flag
if
(m-5 > 0)
printPattern(n, m-5,
true
);
else
// recur with false flag
printPattern(n, m-5,
false
);
}
else
// If flag is false.
printPattern(n, m+5,
false
);
}
We can use two print statements. First one before recursive call that prints all decreasing sequence. Second one after the recursive call to print increasing sequence.
// Recursive function to print the pattern without any extra
// variable
void
printPattern(
int
n)
{
// Base case (When n becomes 0 or negative)
if
(n ==0 || n<0)
{
cout << n <<
" "
;
return
;
}
// First print decreasing order
cout << n <<
" "
;
printPattern(n-5);
// Then print increasing order
cout << n <<
" "
;
}