+ 3

Java program for fibonacci series

import java.util.Scanner; public class Program { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int x = sc.nextInt(); int a = 0; int b = 1; int i=1; System.out.println(a); System.out.println(b); if(i<x){ int sum = a+b; System.out.println(sum); a=b; b=sum; i++; } } } I m not getting required output while using if loop. But when I used for loop I got it. Can anyone tell me what's wrong in this if loop

14th Dec 2021, 7:11 AM
Sonali Kala
Sonali Kala - avatar
12 Respuestas
+ 4
for loops continue to run through the set parameters, acting upon the statement each iteration. An if statement is assessed once if (i < x) -> true sum = a + b -> 0+1 -> 1
14th Dec 2021, 7:34 AM
Rik Wittkopp
Rik Wittkopp - avatar
+ 2
Shira thank u
14th Dec 2021, 9:39 AM
Sonali Kala
Sonali Kala - avatar
+ 1
Yehhh Rik Wittkopp Thank u
14th Dec 2021, 7:35 AM
Sonali Kala
Sonali Kala - avatar
+ 1
Shira ohhh when the numerator is greater we get output it as it is. that means 4%5 ...o/p.. 4 And for 5%4 ... O/p .. 1
14th Dec 2021, 10:08 AM
Sonali Kala
Sonali Kala - avatar
+ 1
I too am learning java take a look at my approach https://code.sololearn.com/clkdEHv0nl7S/?ref=app
15th Dec 2021, 11:53 AM
Harsha S
Harsha S - avatar
+ 1
"if" is not a loop it executes only one time "while" and "for" are loops. It iterates through the code block till a certain condition is not satisfied. If no terminating conditions are described, the loop runs infinitely.
15th Dec 2021, 11:56 AM
Harsha S
Harsha S - avatar
+ 1
Harsha S thanks
16th Dec 2021, 3:33 AM
Sonali Kala
Sonali Kala - avatar
0
Shira no problem... Can u explain me the last ques.. (java challenge)
14th Dec 2021, 9:55 AM
Sonali Kala
Sonali Kala - avatar
0
Shira thank you
14th Dec 2021, 10:24 AM
Sonali Kala
Sonali Kala - avatar