+ 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
12 ответов
+ 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
+ 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
+ 2
Shira thank u
+ 1
Yehhh Rik Wittkopp
Thank u
+ 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
+ 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
+ 1
Sonali Kala yep
+ 1
I too am learning java
take a look at my approach
https://code.sololearn.com/clkdEHv0nl7S/?ref=app
+ 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.
+ 1
Harsha S thanks
0
Shira no problem...
Can u explain me the last ques.. (java challenge)
0
Shira thank you