Распечатать выкройку без использования петель

Опубликовано: 21 Января, 2022

Учитывая число n, печатайте по шаблону без использования цикла.

Примеры :

 Ввод: n = 16
Выход: 16, 11, 6, 1, -4, 1, 6, 11, 16

Ввод: n = 10
Выход: 10, 5, 0, 5, 10

В основном мы сначала уменьшаем 5 один за другим, пока не достигнем отрицательного значения или 0. После того, как мы достигнем 0 или отрицательного значения, мы добавляем 5, пока не достигнем n.
Источник: вопрос об интервью Microsoft.

Мы настоятельно рекомендуем вам щелкнуть здесь и попрактиковаться, прежде чем переходить к решению.

The idea is to use recursion. It is an interesting question to try on your own. 
Below is the Code. The code uses a flag variable to indicate whether we are moving toward 0 or we are moving toward the back to n. 

C++

// C++ program to print pattern that first reduces 5 one
// by one, then adds 5. Without any loop
#include <iostream>
using namespace std;
 
// 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);
}
 
// Recursive function to print the pattern
// variance where m is the input int32 value
void PrintPattern(int m)
{
    if (m > 0)
    {
        cout << m << " ";
        PrintPattern(m - 5);
    }
 
    cout << m << " ";
}
 
// Driver Program
int main()
{
    int n = 16;
    //printPattern(n, n, true);
    PrintPattern(n);
    return 0;
}

Java

// Java program to print pattern that first reduces 5 one
// by one, then adds 5. Without any loop
import java.io.*;
 
class GFG {
     
    // 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.
    static void printPattern(int n, int m, boolean flag)
    {
         
        // Print m.
        System.out.print(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);
    }
 
    // Driver Program
    public static void main(String[] args)
    {
        int n = 16;
        printPattern(n, n, true);
    }
}
// This code is contributed by vt_m

Python3

# Python program to print pattern
# that first reduces 5 one by one,
# then adds 5. Without any loop.
 
# 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.
def printPattern(n, m, flag):
     
    # Print m.
    print(m)
     
    # If we are moving back
    # toward the n and we
    # have reached there,
    # then we are done
    if flag == False and 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)
 
# Driver Code
n = 16
printPattern(n, n, True)
 
# This code is contributed
# by HrushikeshChoudhary

C#

// C# program to print pattern that first reduces 5 one
// by one, then adds 5. Without any loop
using System;
 
class GFG {
     
    // 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.
    static void printPattern(int n, int m, bool flag)
    {
         
        // Print m.
        Console.Write(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);
    }
 
    // Driver Program
    public static void Main()
    {
        int n = 16;
        printPattern(n, n, true);
    }
}
// This code is contributed by vt_m

PHP

<?php
// PHP program to print pattern
// that first reduces 5 one by one,
// then adds 5. Without any loop
 
// 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.
function printPattern($n, $m, $flag)
{
    // Print m.
    echo $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);
     
    // recur with false flag
    else
        printPattern($n, $m - 5, false);
    }
     
    // If flag is false.
    else
        printPattern($n, $m + 5, false);
}
 
// Driver Code
$n = 16;
printPattern($n, $n, true);
 
// This code is conntributed by m_kit
?>

Javascript

<script>
 
// Javascript program to print pattern that
// first reduces 5 one by one, then adds 5.
// Without any loop
 
// 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.
function printPattern(n, m, flag)
{
     
    // Print m.
    document.write(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);
             
        // Recur with false flag
        else
            printPattern(n, m - 5, false);
    }
     
    // If flag is false.
    else
        printPattern(n, m + 5, false);
}
 
// Driver code
let n = 16;
printPattern(n, n, true);
 
// This code is contributed by divyeshrabadiya07
 
</script>

Выход :

16, 11, 6, 1, -4, 1, 6, 11, 16

Как напечатать шаблон выше без дополнительной переменной и цикла?
Вышеупомянутая программа отлично работает и выводит желаемое, но использует дополнительные переменные. Мы можем использовать два оператора печати. Первый перед рекурсивным вызовом, который печатает всю убывающую последовательность. Второй после рекурсивного вызова последовательности увеличения печати.

Below is the implementation of the idea.

C++

// C++ program to print pattern that first reduces 5 one
// by one, then adds 5. Without any loop an extra variable.
#include <iostream>
using namespace std;
 
// 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 << " ";
}
 
// Driver Program
int main()
{
    int n = 16;
    printPattern(n);
    return 0;
}

Java

// Java program to print pattern that first
// reduces 5 one by one, then adds 5.
// Without any loop an extra variable.
 
import java.io.*;
 
class GFG {
     
    // Recursive function to print the
    // pattern without any extra variable
    static void printPattern(int n)
    {
         
        // Base case (When n becomes 0 or
        // negative)
        if (n == 0 || n < 0) {
             
            System.out.print(n + " ");
             
            return;
        }
 
        // First print decreasing order
        System.out.print(n + " ");
         
        printPattern(n - 5);
 
        // Then print increasing order
        System.out.print(n + " ");
    }
 
    // Driver Program
    public static void main(String[] args)
    {
         
        int n = 16;
         
        printPattern(n);
    }
}
 
// This code is contributed by vt_m

Python3

# Python3 program to print pattern that
# first reduces 5 one by one, then adds 5.
# Without any loop an extra variable.
 
# Recursive function to print the pattern
# without any extra variable
def printPattern(n):
 
    # Base case (When n becomes 0 or negative)
    if (n == 0 or n < 0):
        print(n, end = ", ")
        return
     
    # First print decreasing order
    print(n, end = ", ")
    printPattern(n - 5)
 
    # Then print increasing order
    print(n, end = ", ")
 
# Driver Code
n = 16
printPattern(n)
 
# This code is contributed by
# Mohit kumar 29

C#

// C# program to print pattern that first
// reduces 5 one by one, then adds 5.
// Without any loop an extra variable.
 
using System;
 
class GFG {
     
    // Recursive function to print the
    // pattern without any extra variable
    static void printPattern(int n)
    {
         
        // Base case (When n becomes 0 or
        // negative)
        if (n == 0 || n < 0) {
             
            Console.Write(n + " ");
             
            return;
        }
 
        // First print decreasing order
   &