Write a Java program that prompts the user for an integer and then prints out all the prime numbers up to that Integer (3)
Write a Java program that prompts the user for an integer and then prints out all the prime numbers up to that Integer (3)
prime
numbers up to that Integer
Aim:
To write a Java program that accepts a number from the user and prints all prime numbers less
than the given number.
Algorithm:
import java.util.Scanner;
class PrimeNumbers
int n;
int p;
n=s.nextInt();
for(int i=2;i<n;i++)
p=0;
for(int j=2;j<i;j++)
{
if(i%j==0)
p=1;
if(p==0)
System.out.println(i);
To write a Java program to perform matrix multiplication for two given matrices and display the
resultant matrix.
import java.util.Scanner;
row1 = scanner.nextInt();
row2 = scanner.nextInt();
col2 = scanner.nextInt();
if (col1 != row2) {
return;
// Initialize matrices
matrixA[i][j] = scanner.nextInt();
}
matrixB[i][j] = scanner.nextInt();
// Matrix multiplication
}
System.out.print(matrixC[i][j] + " ");
System.out.println();
scanner.close();
Algorithm:
1. Input Dimensions:
o Prompt the user to enter the number of rows and columns for matrices A and B.
o Ensure that the number of columns in matrix A equals the number of rows in
matrix B. If not, output an error and exit.
2. Input Matrices:
o Create two 2D arrays for matrix A and matrix B based on the provided
dimensions.
o Prompt the user to fill these arrays with integer values.
3. Initialize Result Matrix:
o Create a 2D array for the result matrix, with dimensions row1 x col2.
4. Matrix Multiplication Logic:
o Use three nested loops:
Outer loop for rows of matrix A.
Middle loop for columns of matrix B.
Inner loop to multiply elements of rows from matrix A and columns from
matrix B, and accumulate the sum in the result matrix.
5. Display Result:
o Print the elements of the resultant matrix in matrix form.
Write a Java program that displays the number of characters, lines and words in a text?
import java.util.Scanner;
int lineCount = 0;
int wordCount = 0;
int charCount = 0;
while (true) {
String line = scanner.nextLine();
// Stop input if the user types "EXIT"
if (line.equalsIgnoreCase("EXIT")) {
break;
}
// Increment line count
lineCount++;
// Increment character count (including spaces)
charCount += line.length();
// Increment word count
String[] words = line.trim().split("\\s+");
wordCount += words.length;
}
scanner.close();
}
}