Fibonacci Series
- Program that takes a positive integer as input and outputs the Fibonacci sequence up to that number.
Program
import
java.util.Scanner;
public class
Fibonacci {
private static
Scanner sc;
public static void
main(String[] args) {
int
limit,a=0,b=1,temp=0;
sc=new
Scanner(System.in);
System.out.println("Enter
the limit:");
limit=sc.nextInt();
if(limit<0)
{
System.out.println("!!Invalid
limit!!\n!!Enter a positive number!!");
return;
}
System.out.println("Fibonacci
Series is:");
if(limit==0)
{
System.out.println(+a);
}
else {
System.out.print(+a+"
"+b);
for(int
i=1;i<=limit;i++) {
temp=a+b;
if(temp<=limit)
{
System.out.print("
"+temp);
a=b;
b=temp;
}
else {
return;
}
}
}
}
}
Output
Enter
the limit:
15
Fibonacci
Series is:
0 1 1 2 3 5
8 13
Program
to print whether the number entered is a prime/odd. Use functions
Program
import
java.util.Scanner;
public class
OddOrPrime {
private static
Scanner assign;
static int flag=0;
public void
findPrime(int num) {
for(int
i=1;i<=num;i++) {
if(num%i==0)
{
flag++;
}
}
if(flag==2)
{
System.out.println(num+"
is prime");
}
else {
System.out.println(num+"
is not prime");
}
}
public void
check(int num) {
if(num%2!=0)
{
System.out.println(num+"
is an odd number");
}
else {
System.out.println(num+"
is not an odd number");
}
}
public static void
main(String[] args) {
int
num;
assign=new
Scanner(System.in);
System.out.print("Enter
a number:");
num=assign.nextInt();
OddOrPrime ob=new
OddOrPrime();
ob.check(num);
ob.findPrime(num);
}
}
Output
Enter
a number:19
19
is an odd number
19
is prime
No comments:
Post a Comment