+ 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 Respostas
+ 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
+ 3
You have created three variables a b and i. After that u printing values of a and b . But your if condition will work only once here u need to use loop . Else your code will give sum of numbers only once and also add else clause if your condition gonna be false you can give any message
14th Dec 2021, 8:28 AM
Shira
Shira - 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
Sonali Kala int a=21 and b=8 here two variables are declared which types are int after in print statement there was written (a/++b)%3 here it will solve according to precedence so first bracket will be solve (a/++b) remember if u have pre increment or pre decrement then it will solve in the whole expression then this increase value will be use her b is incremented by 1 so now b become 9 and (a/++b)= 21/9=2 then modulo %3 ---> = 2%3 here your numerator is smaller than denominator that why the result will be 2 if numerator is greater then your remainder will be the output 3%2 =1
14th Dec 2021, 10:05 AM
Shira
Shira - 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
14th Dec 2021, 10:23 AM
Shira
Shira - 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