1.
Write a Java program that prompts the user for an integer and then prints out all the
prime n
Program:
import java.util.Scanner;
public class PrimeNumbers{
public static void main(String arg[]){
int i,n,counter, j;
Scanner scanner = new Scanner(System.in);
System.out.println("Required packages have been imported");
System.out.println("A reader object has been defined ");
System.out.print("Enter the n value : ");
n=scanner.nextInt();
System.out.print("Prime numbers between 1 to 10 are ");
for(j=2;j<=n;j++){
counter=0;
for(i=1;i<=j;i++){
if(j%i==0){
counter++;
}
}
if(counter==2)
System.out.print(j+" ");
}
}
}
Output:
2. Write a Java program to multiply two given matrices.
public class Matrix{
public static void main(String args[]){
//creating two matrices
int a[][]={{1,1,1},{2,2,2},{3,3,3}};
int b[][]={{1,1,1},{2,2,2},{3,3,3}};
//creating another matrix to store the multiplication of two matrices
int c[][]=new int[3][3]; //3 rows and 3 columns
//multiplying and printing multiplication of 2 matrices
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
c[i][j]=0;
for(int k=0;k<3;k++)
{
c[i][j]+=a[i][k]*b[k][j];
}//end of k loop
System.out.print(c[i][j]+" "); //printing matrix element
}//end of j loop
System.out.println();//new line
}
}}
Output:
3. .Write a Java program that displays the number of characters, lines and words in a
text?
Program:
import java.io.BufferedReader;
import java.io.FileReader;
public class CountWord
{
public static void main(String[] args) throws Exception {
String line;
int count = 0;
//Opens a file in read mode
FileReader file = new FileReader("data.txt ");
BufferedReader br = new BufferedReader(file);
//Gets each line till end of file is reached
while((line = br.readLine()) != null) {
//Splits each line into words
String words[] = line.split("");
//Counts each word
count = count + words.length;
System.out.println("Number of words present in given file: " + count);
br.close();
}
}
Output
4. Generate random numbers between two given limits using Random class and print
messages according to the range of the value generated.
Program:
public class RandomNumber
{
public static void main( String args[] )
{
int min = 200;
int max = 400;
//Generate random double value from 200 to 400
System.out.println("Random value of type double between "+min+" to "+max+ ":");
double a = Math.random()*(max-min+1)+min;
System.out.println(a);
//Generate random int value from 200 to 400
System.out.println("Random value of type int between "+min+" to "+max+ ":");
int b = (int)(Math.random()*(max-min+1)+min);
System.out.println(b);
}
}
Output: