Java Me-1to 3
Java Me-1to 3
CLASS:-CS2
ROLL_Number:-1800293
MACHINE EXERCISE:-01
1. Write a Java program that prints all real solutions to the quadratic
equation ax2 + bx+ c=0. Read in a, b, c and use the quadratic formula.
If the discriminant b2 –4ac is negative, display a message stating that
there are no real solutions.
//Program to find roots of a quadratic equations
import java.util.*;
class Roots
{
public static void main(String args[])
{
int a,b,c,d,f=0;
Scanner scr=new Scanner(System.in);
System.out.println("\nEnter the values of a ,b ,c : ");
a=scr.nextInt();
b=scr.nextInt();
c=scr.nextInt();
d=(b*b)-(4*a*c);
if(d==0)
{
System.out.println("Roots are real and Equal");
f=1;
}
else if(d>0)
{
System.out.println("Roots are real and UnEqual");
f=1;
}
else
System.out.println("Roots are imaginary");
if(f==1)
{
float r1=(float)(-b+Math.sqrt(d))/(2*a);
float r2=(float)(-b-Math.sqrt(d))/(2*a);
System.out.println("Roots are : "+r1+" ,"+r2);
}
}
Output:
}
void rcf(int a,int b,int c,int n)
{
if(n-2>0)
{
c=a+b;
a=b;
b=c;
rcf(a,b,c,n-1);
return;
}
System.out.println("\nnth value in the series using recursive function is : "+c);
}
}
class Fibonacci
{
public static void main(String args[])
{
Function f=new Function();
int n,a=1,b=1,c=0;
Scanner scr=new Scanner(System.in);
System.out.println("\nEnter n value: ");
n=scr.nextInt();
f.nrcf(a,b,c,n);
f.rcf(a,b,c,n);
}
}
Output:
Enter n value:
10
nth value in the series using non recursive function is : 55
nth value in the series using recursive function is : 55
3. Write a Java program that prompts the user for an integer and then
prints out all prime numbers up to that integer.
Output:
Enter n value:
10
Prime numbers are :
2 3 5 7
Output:
xxxxxx
xxxxx
xxxx
xxx
xx
x
5. Write a Java program that calculate mathematical constant ‘e’ using
the formula e=1+1/2!+1/3!+........ up to 5
// A simple Java program to compute
// sum of series 1/1! + 1/2! + .. + 1/n!
import java.io.*;
class SOS {
// Driver program
public static void main (String[] args)
{
int n = 5;
System.out.println(sum(n));
}
}
Output:
1.71667
MACHINE EXERCISE:-02
Output-
AVAJ
import java.util.Scanner;
class ChkPalindrome
{
public static void main(String args[])
{
String str, rev = "";
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string:");
str = sc.nextLine();
if (str.equals(rev))
System.out.println(str+" is a palindrome");
else
System.out.println(str+" is not a palindrome");
}
}
Output-
Enter a string:
radar
radar is a palindrome
String line;
// Initializing counters
int countWord = 0;
int sentenceCount = 0;
int characterCount = 0;
int paragraphCount = 1;
int whitespaceCount = 0;
countWord += wordList.length;
whitespaceCount += countWord -1;
// [!?.:]+ is the sentence delimiter in java
String[] sentenceList = line.split("[!?.:]+");
sentenceCount += sentenceList.length;
}
}
Output-
Output-
MACHINE EXERCISE:-03
Output :
Output-
3