显示从1到100的数字,没有循环或条件 [英] Display numbers from 1 to 100 without loops or conditions

查看:202
本文介绍了显示从1到100的数字,没有循环或条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在不使用任何循环或条件如if的情况下从1到100打印数字?
我们可以轻松地使用递归,但这又有一个if条件。有没有办法不使用if?也没有重复的打印语句,或包含1到100之间所有数字的单个print语句。

Is there a way to print numbers from 1 to 100 without using any loops or conditions like "if"? We can easily do using recursion but that again has an if condition. Is there a way to do without using "if" as well? Also no repetitive print statements, or a single print statement containing all the numbers from 1 to 100.

Java中的解决方案更可取。

A solution in Java is preferable.

推荐答案

伪代码。使用一个数组在100个被捕获的元素之后强制执行异常。

Pseudo code. Uses an array to force an exception after 100 elements which is caught and does nothing.

function r(array a, int index){
    a[index] = a[index-1]+1
    print a[index]
    r(a, index+1)
}

try{
    array a;
    a.resize(101)
    r(a, 1)
}catch(OutOfBoundsException){
}

编辑

Java代码:

EDIT
Java code:

public void printTo100(){
    int[] array = new int[101];
    try{
        printToArrayLimit(array, 1);
    }catch(ArrayIndexOutOfBoundsException e){
    }
}
public void printToArrayLimit(int[] array, int index){
    array[index] = array[index-1]+1;
    System.out.println(array[index]);
    printToArrayLimit(array, index+1);
}

这篇关于显示从1到100的数字,没有循环或条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆