Java Program: class C14e1 { public static void main(String[] args) { numbersToOn
ID: 3939969 • Letter: J
Question
Java Program:
class C14e1
{
public static void main(String[] args)
{
numbersToOne(10);
}
//----------------------------------
public static void numbersToOne(int n)
{
if (n > 0)
{
System.out.println(n);
numbersToOne(n - 1);
}
}
}
Write a program that is equivalent to the program shown above, but implement numbersToOne using a while loop instead of recursion.
Also, implement the fib method shown below using a loop instead of recursion.
public static long fib(long i)
{
if (i < 2)
return 1;
return fib(i - 1) + fib(i - 2);
}
Explanation / Answer
class C14e1
{
public static void main(String[] args)
{
numbersToOne(10);
}
//----------------------------------
public static void numbersToOne(int n)
{
while(int i=n;i>=1;i--)
{
System. out.println(i);
}
}
public static void fib(long i)
{
long a=0,b=1,c=0;
System.out.println(a+" "+b);
while(c<=i)
{
c=a+b;
System.out.println(c);
a=b;
b=c;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.