Tuesday, September 4, 2012

General Programing aptitude check Q&A

Printing the number series 1,2...500 without using loops

================


The alternate to loops would be recursion. While prgramming with recursion need to determine 2 things
                       1) wht needs to be done on every recursion
                        2)Wht shld be the exit condition.

So for our task,
       Ans for 1) --> print number +1
                   2) exit when number =500

Here is the java implementation of the same

public class NumberUtilities {
    public static void main(String[] args) {
            printNumbers(0);
           System.out.println();
     }
    public static void printNumbers(int num){
        System.out.print(num +" ");
        if(num==500)
            return;
        num++;
        printNumbers(num); }}

No comments:

Post a Comment