Answer to Question #10457 in Java | JSP | JSF for inyang

Question #10457
Given the number n, find the sum of the first n odd numbers and print it.

1, 1, 2, 3, 5, 8, 13 ....
Print the first n numbers in the fibonacci sequence.
1
Expert's answer
2012-06-05T10:18:23-0400
import java.io.*;

public class Fibonacci {

public static void sequence(int n){
& int a0 = 0;
& int a1 = 1;
& int an;
& System.out.print(a1 + ", ");
& for (int i=1; i<=n; i++){
& an = a0 + a1;
& if (i==n){
& System.out.println(an);
& break;
& }
& System.out.print(an + ", ");
& a0 = a1;
& a1 = an;
& }
&
}

public static void main(String[] args) {
& // TODO Auto-generated method stub
& BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
& System.out.println("Enter n:");
& try {
& int n = Integer.parseInt(br.readLine());
& sequence(n);
& } catch (NumberFormatException e) {
& System.out.println("Not a number!");
& System.exit(1);
& } catch (IOException e) {
& // TODO Auto-generated catch block
& e.printStackTrace();
& }
&
}

}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
APPROVED BY CLIENTS