0% found this document useful (0 votes)
65 views

Computer Journal Programs

The document contains code for several Java programs that perform various tasks: 1) A Matrix class with methods for sorting the non-boundary elements of a matrix, displaying a matrix, and calculating the sum of diagonal elements. 2) Code to check if a given number is a Goldbach number. 3) A program to validate an input phone number using a regular expression. 4) A method to convert a Roman numeral to its decimal equivalent. 5) Code demonstrating basic arithmetic operations by taking numeric input from the user. 6) A program that reads text from one file and writes it to another file.

Uploaded by

28-Shreya Thokal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
65 views

Computer Journal Programs

The document contains code for several Java programs that perform various tasks: 1) A Matrix class with methods for sorting the non-boundary elements of a matrix, displaying a matrix, and calculating the sum of diagonal elements. 2) Code to check if a given number is a Goldbach number. 3) A program to validate an input phone number using a regular expression. 4) A method to convert a Roman numeral to its decimal equivalent. 5) Code demonstrating basic arithmetic operations by taking numeric input from the user. 6) A program that reads text from one file and writes it to another file.

Uploaded by

28-Shreya Thokal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 30

COMPUTER JOURNAL

Q1)
import java.util.*;
class Matrix
{
// sorting non boundary elements problem
public static int[] bubbleSort( int a[] )
{
int temp;
for(int i=0; i < a.length-1;i++){
for(int x=0;x < a.length-i-1;x++)
{
if(a[x+1] < a[x]){
temp=a[x];
a[x] = a[x+1];
a[x+1] = temp;
}
}
}
return a;
}

public static void displayMatrix(int A[][]){


for( int row = 0 ; row < A.length; row++ ){
for( int col = 0 ; col < A[ row ].length ; col++ )
{
System.out.print( "\t" + A[ row ][ col ]);
}
System.out.println();
}
}

public static int displayMatrixDiagonals(int A[][]){


int sumOfDiagonals=0;
for( int row = 0 ; row < A.length; row++ ){
for( int col = 0 ; col < A[ row ].length ; col++ )
{
System.out.print( "\t" );
if( row == col || row == A.length - 1 - col )
{
System.out.print(A[ row ][ col ]);
sumOfDiagonals += A[ row ][ col ];
}
else
{
System.out.print( " " );
}
}
System.out.println();
}
return sumOfDiagonals;
}

public static void main( String args[] )


{
Scanner sc = new Scanner( System.in );
System.out.print( "INPUT : " );
int M = sc.nextInt();
if( M > 3 && M < 10 ){
int A[][] = new int[M][M];
int n[] = new int[ M*M - 2*M - 2*(M-2) ];
int i=0;
for( int row = 0 ; row < M; row++ )
{
for( int col = 0 ; col < M ; col++ )
{
A[ row ][ col ] = sc.nextInt();
//check for non-border elements
if( row > 0 && row < M-1 && col > 0 && col < M-
1)
{
//store non border elements in array n
n[ i++ ] = A[ row ][ col ];
System.err.print(row+", "+col+"\t");
}

}
}
System.out.println( "ORIGINAL MATRIX : " );
displayMatrix( A );
//sort the array n
n = bubbleSort( n );
//display(n);
i=0;
for( int row = 1 ; row < M - 1 ; row++ )
{
for( int col = 1 ; col < M - 1 ; col++ )
{
A[ row ][ col ] = n[ i++ ];
}
}

System.out.println( "REARRANGED MATRIX : " );


displayMatrix( A );
System.out.println( "DIAGONAL ELEMENTS : " );
int sumOfDiagonals = displayMatrixDiagonals(A);
System.out.println( "SUM OF DIAGONAL ELEMENTS = "
+ sumOfDiagonals );
}
else
{
System.out.println( "OUTPUT: THE SIZE OF THE
MATRIX IS OUT OF RANGE" );
}
}
}

Q2)

import java.util.Scanner;
public class GoldbachNumber
{
public static void main(String args[])
{
//Taking the number as input from the user using
scanner class
Scanner scan = new Scanner(System.in);
System.out.print("Enter a number : ");
int num = scan.nextInt();
int temp;
boolean flag = false;
// Checks if the number is above 4 then goes into the
loop
if(num>4)
{
// Runs a loop from 3 to the num until the break
condition is met
for(int i = 3; i<num; i+=2)
{
// Checks whether the current number is prime else
goes out
if(isPrime(i))
{
// Finds the other number and checks if it is prime
number
temp = num - i;
if(isPrime(temp))
{
flag = true;
break;
}
}
}
}
if(flag)
{
System.out.println(num+" is a Goldbach number");
}
else
{
System.out.println(num+" is Not a Goldbach
number");
}
}
// Function to check for prime
static boolean isPrime(int num)
{
int iter = 2;
boolean flag = true;
while (num > iter)
{
if (num % iter == 0)
{
flag = false;
break;
}
iter++;
}
return flag;
}
}

Q3)

import java.util.Scanner;
public class cellularphone
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter your Phone number: ");
String phone = sc.next();
//Regular expression to accept valid phone number
String regex = "\\d{10}";
//Matching the given phone number with regular
expression
boolean result = phone.matches(regex);
if(result)
{
System.out.println("Given phone number is valid");
} else
{
System.out.println("Given phone number is not valid");
}
}
}

Q4)
public class RomanNumberToDecimal
{
public static int toDecimal(String str) {
int len = str.length();

/**
* adding an random char just to be used by the next
char to eliminated
* unnecessary out of index checks
*/
str = str + " ";
int result = 0;
for (int i = 0; i < len; i++) {
char ch = str.charAt(i);
/** the next char is needed in case the number is
using subtractive pattern */
char nextChar = str.charAt(i + 1);

/** if ch is M add 1000 - definitely not part of


subtractive pattern */
if (ch == 'M') {
result += 1000;
/** if ch is C - possible part of subtractive pattern */
} else if (ch == 'C') {
if (nextChar == 'M') {
result += 900;
/** Additionally increasing the index by 1 as the
subtractive pattern was used */
i++;
} else if (nextChar == 'D') {
result += 400;
/** Additionally increasing the index by 1 as the
subtractive pattern was used */
i++;
} else {
result += 100;
}
/** if ch is D add 500 - definitely not part of
subtractive pattern */
} else if (ch == 'D') {
result += 500;
/** if ch is X - possible part of subtractive pattern */
} else if (ch == 'X') {
if (nextChar == 'C') {
result += 90;
/** Additionally increasing the index by 1 as the
subtractive pattern was used */
i++;
} else if (nextChar == 'L') {
result += 40;
/** Additionally increasing the index by 1 as the
subtractive pattern was used */
i++;
} else {
result += 10;
}
/** if ch is L add 50 - definitely not part of subtractive
pattern */
} else if (ch == 'L') {
result += 50;
/** if ch is V add 5 - definitely not part of subtractive
pattern */
} else if (ch == 'V') {
result += 5;
/** if ch is I - possible part of subtractive pattern */
} else if (ch == 'I') {
if (nextChar == 'X') {
result += 9;
/** Additionally increasing the index by 1 as the
subtractive pattern was used */
i++;
} else if (nextChar == 'V') {
result += 4;
/** Additionally increasing the index by 1 as the
subtractive pattern was used */
i++;
} else {
result += 1;
}
}
}
return result;
}

public static void main(String[] args) {


System.out.println("Roman number to decimal
conversion example");
System.out.println();
String rn1 = "MCMLXXXII";
int dec1 = toDecimal(rn1);
System.out.println(rn1 + " converts to " + dec1);

String rn2 = "MMXVII";


int dec2 = toDecimal(rn2);
System.out.println(rn2 + " converts to " + dec2);
}
}

Q6)_
import java.util.Scanner;
public class pseudoArithmeticOperation
{

public static void main(String[] args)


{

// Create scanner class object


Scanner in = new Scanner(System.in);

// Input two numbers from user


System.out.println("Enter first number :");
int num1 = in.nextInt();
System.out.println("Enter second number :");
int num2 = in.nextInt();

// Perform arithmetic operations.


int sum = num1 + num2;
int difference = num1 - num2;
int product = num1 * num2;
int quotient = num1 / num2;
int modulo = num1 % num2;

// Print result to console.


System.out.println("Sum : " + sum);
System.out.println("Difference : " + difference);
System.out.println("Product : " + product);
System.out.println("Quotient : " + quotient);
System.out.println("Modulo : " + modulo);
}
}

Q7)
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class ReadTextFileWriteToAnother
{

public static void main(String[] args) {


//create input and output stream objects
FileInputStream inStream = null;
FileOutputStream outStream = null;

try {
//Files objects
File inputFile = new File("D:\\examples\\input.txt");
File outFile = new File("D:\\examples\\out.txt");

//Intialize input and output streams


inStream = new FileInputStream(inputFile);
outStream = new FileOutputStream(outFile);

//The buffer size for reading data


byte[] buffer = new byte[1024];
int length;
//Copy data to another file
while ((length = inStream.read(buffer)) > 0) {
outStream.write(buffer, 0, length);
}

// Closing the input/output file streams


inStream.close();
outStream.close();

System.out.println("Written Content to another file.");

} catch (IOException e) {
e.printStackTrace();
}
}
}

Q8)
import java.util.Scanner;
public class CircularPrime
{
public static boolean isPrime(int num)
{
int c = 0;

for (int i = 1; i <= num; i++)


{
if (num % i == 0)
{
c++;
}
}

return c == 2;
}

public static int getDigitCount(int num)


{
int c = 0;
while (num != 0)
{
c++;
num /= 10;
}

return c;
}

public static void main(String args[])


{
Scanner in = new Scanner(System.in);
System.out.print("ENTER INTEGER TO CHECK (N): ");
int n = in.nextInt();

if (n <= 0)
{
System.out.println("INVALID INPUT");
return;
}
boolean isCircularPrime = true;
if (isPrime(n))
{
System.out.println(n);
int digitCount = getDigitCount(n);
int divisor = (int)(Math.pow(10, digitCount - 1));
int n2 = n;
for (int i = 1; i < digitCount; i++)
{
int t1 = n2 / divisor;
int t2 = n2 % divisor;
n2 = t2 * 10 + t1;
System.out.println(n2);
if (!isPrime(n2))
{
isCircularPrime = false;
break;
}
}
}
else
{
isCircularPrime = false;
}

if (isCircularPrime)
{
System.out.println(n + " IS A CIRCULAR PRIME.");
}
else
{
System.out.println(n + " IS NOT A CIRCULAR PRIME.");
}
}
}

Q9)
class Merge2SortedArrays
{
public static void main(String[] args)
{
int arr1[]={4,6, 9, 20, 56};
int arr2[]={1, 7, 25, 45, 70};
int[] result=merge(arr1, arr2);
for (int j=0; j<result.length;j++)
System.out.print(result[j]+ " ");
}

static int[] merge(int[] arr1, int[] arr2)


{
int arr1_Length=arr1.length;
int arr2_Length=arr2.length;
int[] result = new int[arr1_Length + arr2_Length];
int i=0, j = 0;

for(int k = 0 ; k< (arr1_Length + arr2_Length);k++)


{
//If arr1 is empty, copy the elements of the array arr2 to the
result array .
//When i equals the length of array arr1 , copy the remaining
elements in the array arr2 to result
if ( i >= arr1_Length ) //for step1 & 4
{
result[k] = arr2[j];
j ++;
}
//If arr2 is empty, copy the elements of the array arr1 to the
result array .
//When j equals the length of array arr2 , copy the remaining
elements in the array arr1 to result
else if ( j >= arr2_Length) // For step 2 &amp; 4
{
result[k] = arr1[i];
i ++;
}
else
{

if ( arr1[i] < arr2[j]) // step 3


{
result[k] = arr1[i];
i ++;
}
else
{
result[k] = arr2[j];
j ++;
}
}
}
return result;
}
}

Q10)
import java.io.*;
class Pendulum_Array
{
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.print("\nEnter number of elements: ");
// Inputting the number of elements
int n = Integer.parseInt(br.readLine());
int A[]=new int[n]; //original array
int B[]=new int[n]; //array for storing the result
/*Inputting the Array*/
for(int i=0; i<n; i++)
{
System.out.print("Enter Element "+(i+1)+": ");
A[i] = Integer.parseInt(br.readLine());
}
/*Sorting the Inputted Array in Ascending Order*/
int t=0;
for(int i=0; i<n-1; i++)
{
for(int j=i+1; j<n; j++)
{
if(A[i]>A[j])
{
t=A[i];
A[i]=A[j];
A[j]=t;
}
}
}
/*Printing the Sorted Array*/
System.out.println("\nThe Sorted Array Is");
for(int i=0; i<n; i++)
{
System.out.print(A[i]+" ");
}
int mid = (n-1)/2;
//finding index of middle cell
int x = 1, lim = n-1-mid;
/*'x' is for accessing elements of array A[] and 'lim' is
* for the number of times we have to make this to-and-
fro movement*/
/* Pendulum Arrangement Starts Here */
B[mid]=A[0]; //putting the minimum element in the
middle cell
for(int i=1; i<=lim; i++)
{
if((mid+i)<n) //going to the right side
{
B[mid+i]=A[x++];
}
if((mid-i)>=0) //going to the left side
{
B[mid-i]=A[x++];
}
}
/*Printing the Result*/
System.out.println("\n\nThe Result Is");
for(int i=0; i<n; i++)
{
System.out.print(B[i]+" ");
}
}
}

You might also like