Click here to Skip to main content
15,907,687 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Input
5

Output

0
1 1
2 3 5
8 13 21 34
55 89 144 233 377

Constraints
1 <= n <= 50


What I have tried:

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Main {

    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        int n = s.nextInt();
        solve(n);
    }

    public static void solve(int n)
    {
        // your code here
		
		int count=0;
		
		for(int i=0; i<=n; i++){
						int a =0;
				        int b =1;
					    int c =a+b;
			             	
				for(int j=1; j<=i; j++){
					System.out.print(c+ " ");
					     a = b;
					     b = a;
				         c = a;
				        count++;
				}
			   
			System.out.println();
		}
        
    }
}
Posted
Updated 22-Dec-22 2:34am
Comments
Richard Deeming 22-Dec-22 8:26am    
How about just for once you try providing some proper detail with your question, rather than just dumping your homework assignment and code without explanation?!

1 solution

Look at what it actually prints, and ask yourself a question:
1 
1 1 
1 1 1 
1 1 1 1 
1 1 1 1 1
"Why does it print that?"
The answer is: because "1" is what c contains each time round the loop.
So ... why? Simple: your assignment of c in the outer loop is irrelevant because you always overwrite it in the inner loop ... Think about the sequence you need to print and ask yourself another question: "Why do I need c at all?"
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900