Make sure to subscribe to our newsletter and be the first to know the news.
Make sure to subscribe to our newsletter and be the first to know the news.
The provided Java code showcases the usage of methods within a class to display the values up to 100 and generate the Fibonacci series within the same program.
Understanding the code :
1. Display Method: The display() method prints the values from 1 to 100 using a while loop. It initializes a counter i to 1 and iterates until i reaches 100, printing each value along the way.
2. Fibonacci Method: The fibonacci() method generates the Fibonacci series up to the value of 100. It initializes n1 and n2 to 0 and 1 respectively, prints these initial values, and then continues generating the Fibonacci series until the next number exceeds 100. It uses a while loop with a condition that always evaluates to true but breaks out of the loop when the next Fibonacci number exceeds 100.
3. Main Method: In the main() method, an instance of the MethodsRunner class is created, and its fibonacci() and display() methods are invoked to display the Fibonacci series and values up to 100 respectively.
public class MethodsRunner {
public void display(){
int i=1;
while(i<=100){
System.out.println("Value: "+i);
i++;
}
}
public void fibonacci(){
int n1=0;
int n2=1;
int next=0;
System.out.print("Fibonacci Series "+n1+" , "+n2);
while (true) {
next=n1+n2;
if(next>100){
break;
}
System.out.print(" , "+next);
n1=n2;
n2=next;
}
}
public static void main(String[] args) {
MethodsRunner m=new MethodsRunner();
m.fibonacci();
m.display();
}
}
Conclusion:
In conclusion, the code demonstrates the usage of methods in Java to encapsulate and organize functionality. The display() method is responsible for printing values up to 100, while the fibonacci() method generates the Fibonacci series up to 100. By encapsulating these functionalities within methods, the code achieves modularity and readability, making it easier to understand and maintain.
Furthermore, the code illustrates the use of loops and conditional statements to control program flow. The while loop efficiently iterates through values and generates the Fibonacci series, while the conditional break statement allows for breaking out of the loop when a certain condition is met.