1

I want to make a function which will display numbers starting from 1 to 100 and 100 to 1 I am confused that how i can do this using Recursion?

I dont want to do this using any other loop. Please provide me hint and ignore my way of asking because i am new in c++ and c#.

4

8 回答 8

5
void Print100(int n)
{
   if (n > 100)
   {
       Console.WriteLine();  // cosmetic
       return;               // stop recursing
   }

   Console.WriteLine(n);     // 1-100
   Print100(n+1);            // recurse
   Console.WriteLine(n);     // 100-1, on the way out
}


void Main()
{
    Print100(1);
}
于 2012-10-22T10:01:59.497 回答
3

用于打印 1 到 100 的数字

private void number(int n)
        {
            if (n == 100)
                return;
            Response.Write(n + "<br/>");
            number(n + 1);
        }

称呼:

number(0);
于 2012-10-22T09:57:51.277 回答
3

您可以对以下内容进行递归:

public static void For<T>(
    T initializer,
    Func<T, bool> condition,
    Func<T, T> iterator,
    Action<T> action)
{
    if (!condition(initializer)) return;
    action(initializer);
    For(iterator(initializer), condition, iterator, action);
}

一到一百:

For(1, i => i <= 100, i => i + 1, i => Console.WriteLine(i));

剩下一百比一作为练习。

于 2012-10-22T09:58:59.467 回答
2

你编写一个函数,它接受两个参数,基本上是:当前数字和方向(向上或向下)。然后输出该数字,增加或减少它并再次调用相同的函数,直到达到 0。

于 2012-10-22T09:59:30.117 回答
1

您可以在 C++ 中使用此函数:

    void printNumbers(int number)
    {
       if (i >= 1) 
       {
          // 100 --> 1
          cout << number << " ";
          printNumbers(i-1);
          // 1 --> 100
          cout << number << " ";
       }
    }

用 printNumbers(100) 调用你的函数

希望这可以帮助!

于 2012-10-22T10:04:11.130 回答
0

C#

public void recurseInts( int start, int finish ){
 if( start > finish ) return;
 Console.WriteLine(start);
 Console.WriteLine(finish - start);
 recurseInts(start + 1 , finish);
}

recurseInts(0,100);
于 2012-10-22T09:59:44.583 回答
0

我认为这就是你在 C++ 中想要的

#include <iostream>
using namespace std;

void recur(int start, int end,bool asc){
    cout << start << endl;
    if(!asc && start==0)return;
    if(start == end) asc = false;
    asc?start++:start--;
    recur(start, end, asc);
}

int main(){
    recur(0, 100,true);
    system("pause");
    return 0;
}
于 2012-10-22T10:12:44.830 回答
0

复制此代码并提交您的作业:

class Program
{

    public static bool forward = false;
    public static bool stop = false;
    static void Main(string[] args)
    {
        PrintNumbers(0);
        Console.ReadLine();

    }

    private static void PrintNumbers(int i)
    {
        if (i <= 100 && !forward)
        {
            Console.WriteLine(i);
            if (i == 100)
            {
                forward = true;
            }
            PrintNumbers(i + 1);

        }
        if (i >= 0  && i < 100 && forward && !stop)
        {


            Console.WriteLine(i);

            PrintNumbers(i - 1);
            if (i==0)
            {
                stop = true;
            }

        }

    }
}
于 2012-10-22T10:19:46.023 回答