Практические вопросы для рекурсии | Комплект 6

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

Question 1 
Consider the following recursive C function. Let len be the length of the string s and num be the number of characters printed on the screen. Give the relation between num and len where len is always greater than 0. 

C++

void abc(char *s)
{
    if(s[0] == "")
        return;
  
    abc(s + 1);
    abc(s + 1);
    cout << s[0];   
}
 
// This code is contributed by shubhamsingh10

C

void abc(char *s)
{
    if(s[0] == "")
        return;
 
    abc(s + 1);
    abc(s + 1);
    printf("%c", s[0]);   
}

Java

static void abc(char *s)
{
    if(s[0] == "")
        return;
   
    abc(s + 1);
    abc(s + 1);
    System.out.print(s[0]);   
}
 
// This code is contributed by shubhamsingh10

Python3

def abc(s):
    if(len(s) == 0):
        return
     
    abc(s[1:])
    abc(s[1:])
    print(s[0])
     
# This code is contributed by shubhamsingh10

C#

static void abc(char *s)
{
    if(s[0] == "")
        return;
 
    abc(s + 1);
    abc(s + 1);
    Console.Write(s[0]);
}
 
// This code is contributed by shubhamsingh10

Javascript

<script>
//Javascript Implementation
function abc(s)
{
    if(s.length == 0)
        return;
         
    abc(s.substring(1));
    abc(s.substring(1));
    document.write(s[0]);   
}
 
// This code is contributed by shubhamsingh10
</script>

Ниже приведены отношения между num и len .

 число = 2 ^ len-1
 s [0] печатается 1 раз
s [1] печатается 2 раза
s [2] печатается 4 раза
s [i] печатается 2 ^ i раз
s [strlen (s) -1] печатается 2 ^ (strlen (s) -1) раз
всего = 1 + 2 + .... + 2 ^ (strlen (s) -1)
      = (2 ^ strlen (s)) - 1

For example, the following program prints 7 characters. 

C++

#include <bits/stdc++.h>
using namespace std;
 
void abc(char s[])
{
    if(s[0] == "")
        return;
 
    abc(s + 1);
    abc(s + 1);
    cout << s[0];
}
 
int main()
{
    abc("xyz");
    return 0;
}
//This code is contributed by shubhamsingh10

C

#include<stdio.h>
 
void abc(char *s)
{
    if(s[0] == "")
        return;
 
    abc(s + 1);
    abc(s + 1);
    printf("%c", s[0]);
}
 
int main()
{
    abc("xyz");
    return 0;
}

Java

public class GFG
{
    static void abc(String s)
    {
        if(s.length() == 0)
            return;
      
        abc(s.substring(1));
        abc(s.substring(1));
        System.out.print(s.charAt(0));
    }
 
    public static void main(String[] args) {
        abc("xyz");
    }
}
 
// This code is contributed by divyeh072019

Python3

def abc(s):
    if(len(s) == 0):
        return
     
    abc(s[1:])
    abc(s[1:])
    print(s[0],end="")
 
 
# Driver code
 
abc("xyz")
 
# This code is contributed by shubhamsingh10

C#

using System;
class GFG {
     
    static void abc(string s)
    {
        if(s.Length == 0)
            return;
             
        abc(s.Substring(1));
        abc(s.Substring(1));
        Console.Write(s[0]);
    }
 
  // Driver code
  static void Main() {
    abc("xyz");
  }
}
 
// This code is contributed by divyeshrabadiya07

Javascript

<script>
// Javascript implementation
 
function abc(s)
{
    if(s.length == 0)
        return;
 
    abc(s.substring(1));
    abc(s.substring(1));
    document.write(s[0]);
}
 
abc("xyz");
 
//This code is contributed by shubhamsingh10
</script>

Спасибо bharat nag за предложение этого решения.

вопрос 2

Выход:

 1
 2
 3
 3
 3
 3
 3

Функция main () вызывает fun (1). fun (1) печатает «1» и называет fun (fun (fun (2))). fun (2) печатает «2» и называет fun (fun (fun (3))). Таким образом, последовательность вызова функции становится fun (fun (fun (fun (fun (3))))). fun (3) печатает «3» и возвращает 3 (обратите внимание, что счетчик не увеличивается и больше не вызываются функции, как если бы условие не было истинным для счетчика 3). Таким образом, последовательность вызовов функций сводится к fun (fun (fun (fun (3)))). fun (3) снова выводит «3» и возвращает 3. Таким образом, вызов функции снова сводится к fun (fun (fun (3))), который снова выводит «3» и сокращает его до fun (fun (3)). Это продолжается, и на экране 5 раз печатается цифра «3».

Пожалуйста, напишите комментарии, если вы обнаружите, что какой-либо из ответов / кодов неверен, или вы хотите поделиться дополнительной информацией / вопросами по темам, обсужденным выше.

Вниманию читателя! Не прекращайте учиться сейчас. Освойте все важные концепции DSA с помощью самостоятельного курса DSA по приемлемой для студентов цене и будьте готовы к работе в отрасли. Чтобы завершить подготовку от изучения языка к DS Algo и многому другому, см. Полный курс подготовки к собеседованию .

Если вы хотите посещать живые занятия с отраслевыми экспертами, пожалуйста, обращайтесь к Geeks Classes Live и Geeks Classes Live USA.