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

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

问题描述

有没有办法在不使用任何循环或条件(如if")的情况下打印从 1 到 100 的数字?我们可以很容易地使用递归,但这也有一个 if 条件.有没有办法不使用if"?也没有重复的打印语句,或包含从 1 到 100 的所有数字的单个打印语句.

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天全站免登陆