Vous êtes sur la page 1sur 44

Asutosh sahoo

B115017
CSE, 5th sem
Group - A
Set I
1. WAP to swap two numbers with using and without using third variable.
Solution :-
import java.util.Scanner;
class Swap {
public static void main(String args[]) {
Scanner sc = new Scanner(Scannerystem.in);
System.out.print("Enter two integers :- ");
int a, b;
a = sc.nextInt();
b = sc.nextInt();
// swapping using 3rd variable
int temp = a;
a = b;
b = temp;
System.out.println("values after 1st swap :- " + a + " and " + b);
// swapping without using 3rd variable
a = a + b;
b = a - b;
a = a - b;
System.out.println("values after 2nd swap :- " + a + " and " +
b);
}
}
4. WAP to check whether an input character is vowel or not.
Solution :-
import java.util.Scanner;
class Vowel {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the character :- ");
char ch = sc.next().charAt(0);

if(ch == 'a' || ch =='e' || ch =='i'|| ch =='o'|| ch =='u'|| ch =='A'|| ch


=='E'|| ch =='I'|| ch =='O'|| ch =='U')
System.out.println("vowel");
else
System.out.println("Not a vowel");
}
}
16. WAP to generate pascal triangle.

Solution :-

import java.util.*;
class PascalTriangle {
public static void main(String[] args) {
System.out.println("Enter the number of lines in the pascal
triangle to be printed");
Scanner in = new Scanner(System.in);

int n = in.nextInt();
int a[][] = new int[n+1][n+1];

for (int i = 1; i <= n; i++) {


for (int j = 1; j <= i; j++) {
if (j == 1 || j == i)
a[i][j] = 1;
else
a[i][j] = a[i-1][j] + a[i-1][j-1];
}
}
System.out.println("The PascalTriangle is :- ");

for (int i = 1; i <= n; i++) {


for (int k = n; k >= i; k--) {
System.out.print(" ");
}

for (int j = 1; j <= i; j++) {


System.out.print(a[i][j]);
System.out.print(" ");
}

System.out.println();
}
}
}
32. WAP to print primary and secondry diagonal of a square matrix.
Solution :-
import java.util.Scanner;
class MatrixDiagonals {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter size of the square matrix: ");
int n = sc.nextInt();
int array[][] = new int[n][n];
System.out.println("Enter matrix elements row wise: ");
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
array[i][j] = sc.nextInt();
}
}

System.out.println("The primary diagonal elemnts are ");


for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
if(i == j)
System.out.println(array[i][j]);
}
}
System.out.println("The secondary diagonal elemnts are");
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
if((i + j) == (n - 1))
System.out.println(array[i][j]);
}
}
}
}
35. WAP to generate Hadamard Matrix.
Solution:-
// Prints the Hadamard matrix of order n. Assumes n is a power of 2.
import java.util.Scanner;
class Hadamard {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter size of a hadamard matrix: ");
int n = sc.nextInt();
boolean[][] hadamard = new boolean[n][n];

// initialize Hadamard matrix of order n


hadamard[0][0] = true;
for (int k = 1; k < n; k += k) {
for (int i = 0; i < k; i++) {
for (int j = 0; j < k; j++) {
hadamard[i+k][j] = hadamard[i][j];
hadamard[i][j+k] = hadamard[i][j];
hadamard[i+k][j+k] = !hadamard[i][j];
}
}
}

// print matrix
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (hadamard[i][j]) System.out.print("* ");
else System.out.print(". ");
}
System.out.println();
}
}
}
36. WAP to find sum of the digits of the largest and smallest number
present in the array of size m x n.
Solution :-
import java.util.Scanner;

class MinMaxArray {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("enter the size of the row :- ");
int r = sc.nextInt();
System.out.print("enter the size of column :- ");
int c = sc.nextInt();
int numbers[][] = new int[r][c];

for (int i=0;i<r ;i++ ) {


for (int j=0;j<c ;j++ ) {
numbers[i][j] = sc.nextInt();
}
}

int largest = numbers[0][0];


int smallest = numbers[0][0];
for(int i=0; i<r; i++) {
for (int j=0;j<c ;j++ ) {
if(numbers[i][j] > largest)
largest = numbers[i][j];
else
if (numbers[i][j] < smallest)
smallest = numbers[i][j];
}
}

System.out.println("Sum of digits of smallest = " +


sumdigits(smallest));
System.out.println("Sum of digits of largest = " + sumdigits(largest));
}

private static int sumdigits(int n) {


int s = 0;
while(n > 0)
{
s = s + n % 10;
n = n / 10;
}
return s;
}
}
47. WAP to count palindrome words present in the string.
Solution :-
import java.util.Scanner;

class CountPalindromes {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the string : ");
String str = sc.nextLine();
int count = 0;
String ar[] = str.split(" ");
for(String s: ar) {
if(checkPalindrome(s)) {
count++;
System.out.println(s);
}
}

System.out.println("no of palindrome words : " + count);


}
private static boolean checkPalindrome(String str) {
return str.equals(new String(new StringBuffer(str).reverse()));
}
}
48. WAP to count words that start and ends with vowel.
Solution :-
import java.util.Scanner;
class StartEndVowel {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the string : ");
String str = sc.nextLine();
int count = 0;
String ar[] = str.split(" ");

for(String s: ar) {
if(check(s)) {
count++;
System.out.println(s);
}
}

System.out.println("no of words : " + count);


}

private static boolean check(String s) {


if((s.charAt(0) == 'a' ||s.charAt(0) == 'e'||s.charAt(0) == 'i'||
s.charAt(0) == 'o'||s.charAt(0) == 'u'||s.charAt(0) == 'A'||s.charAt(0) == 'E'||
s.charAt(0) == 'I'||s.charAt(0) == 'O'||s.charAt(0) == 'U') &&
(s.charAt(s.length()-1) == 'a' ||s.charAt(s.length()-1) == 'e'||
s.charAt(s.length()-1) == 'i'||s.charAt(s.length()-1) == 'o'||
s.charAt(s.length()-1) == 'u'||s.charAt(s.length()-1) == 'A'||
s.charAt(s.length()-1) == 'E'||s.charAt(s.length()-1) == 'I'||
s.charAt(s.length()-1) == 'O'||s.charAt(s.length()-1) == 'U'))
return true;
else
return false;
}
}
50. WAP to check whether any string contains digits or not.
Solution :-
import java.util.Scanner;

class CheckDigit {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the string : ");
String str = sc.next();
boolean status = true;

for(int i=0;i<str.length();i++) {
if(Character.isDigit(str.charAt(i))) {
status = false;
break;
}
}

if(status)
System.out.println("no digits");
else
System.out.println("Contains Digit");
}
}
52. WAP to find the permutation of a string.
Solution :-
import java.util.*;
class Anagrams {
public static void main(String[] args) {
System.out.print("Enter the string whose anagrams are to be
printed :- ");
Scanner in = new Scanner(System.in);
String str = in.nextLine();
printAnagrams(str, 0, str.length() - 1);
System.out.println("");
}

public static void printAnagrams(String str, int beg, int end) {


if (beg == end)
System.out.println(str);
else {
for (int i = beg; i <= end; i++) {
str = swap(str, beg, i);
printAnagrams(str, beg+1, end);
swap(str, beg, i);
}
}
}
public static String swap(String str, int i, int j) {
char temp ;
char[] charArray = str.toCharArray();
temp = charArray[i] ;
charArray[i] = charArray[j];
charArray[j] = temp;
return String.valueOf(charArray);
}
}
55. WAP to check if a String is valid shuffle of two String? Suppose You
are given 3 strings: first, second, and third. third String is said to be a
shuffle of first and second if it can be formed by interleaving the characters
of first and second String in a way that maintains the left to right ordering
of the characters from each string. For example, given first = "abc" and
second = "def", third = "dabecf" is a valid shuffle since it preserves the
character ordering of the two strings. So, given these 3 strings write a
function that detects whether third String is a valid shuffle of first and
second String.
Solution :-
import java.io.*;
import java.util.*;
class ValidShuffle
{
public static void main(String arghs[])
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter 2 words");
String a = sc.next();
a = a + sc.next();
System.out.println("Enter the word to check with");
String b = sc.next();
if(a.length()!=b.length()) {
System.out.println("Wrong word");
}
else {
char x[]=b.toCharArray();
char y[]=a.toCharArray();
for(int i=0;i<x.length;i++)
{
for(int j=0;j<y.length;j++)
{
if(x[i]==y[j])
{ x[i]='0';
y[j]='0';
break;
}
}
}
for(int i=0;i<x.length;i++)
{
if(x[i]!='0'||y[i]!='0')
{
System.out.println("Wrong word");
System.exit(0);
}
}
System.out.println("Word matched");
}
}
}
57. Write a program to declare a square matrix A[][] of order (M x M)
where M must be greater than 3 and less than 10. Allow the user to input
positive integers into this matrix. Perform the following tasks on the
matrix:
(a) Sort the boundary elements in descending order using any standard
sorting technique and rearrange them in the matrix.
(b) Calculate the sum of the boundary elements.
(c) Display the original matrix, rearranged matrix and sum of the boundary
elements. Test your program with the sample data and some random data:
Example 1
INPUT :M = 4 9215
8 13 8 4
15 6 3 11
7 12 23 8 OUTPUT:
ORIGINAL MATRIX 9215
8 13 8 4
15 6 3 11
7 12 23 8 REARRANGED MATRIX 23 15 12 11
1 13 8 9
2638
4578
The sum of boundary elements is = 105

Solution :-
import java.util.*;
class P57 {
static void sort(int arr[], int low, int high) {
if (low < high) {
int pi = partition(arr, low, high);
sort(arr, low, pi-1);
sort(arr, pi+1, high);
}
}
static int partition(int arr[], int low, int high) {
int pivot = arr[high];
int i = (low-1);

for (int j=low; j<high; j++) {


if (arr[j] >= pivot) {
i++;
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}

int temp = arr[i+1];


arr[i+1] = arr[high];
arr[high] = temp;

return i+1;
}
public static void main(String args[]) {
int m;
Scanner scan = new Scanner(System.in);
System.out.println("enter the size of the matrix n>3 and
n<10");
m = scan.nextInt();
int a[][] = new int[m][m];
int e[] = new int[4*m-4];
System.out.println("enter elements row wise");
for(int i = 0 ;i < m;i++)
{
for(int j=0;j < m;j++)
{
a[i][j] = scan.nextInt();
}
}

int k =0;
int s =0;

for(int i=0;i<m;i++)
{
if(i==0 || i==m-1)
{
for(int j=0;j<m;j++)
{
s = s+a[i][j];
e[k] = a[i][j];
k++;
}
}
else
{
s = s + a[i][0] + a[i][m-1];
e[k] = a[i][0];
k++;
e[k] = a[i][m-1];
k++;
}

}
System.out.println("original matrix");
for(int i = 0 ;i<m;i++)
{
for(int j=0;j<m;j++)
{
System.out.print(a[i][j]+"\t");
}
System.out.println();
}
sort(e,0,4*m-5);
k=0;
System.out.println("Sum of boundary elemnts = "+s);
for(int i=0;i<m;i++)
{
a[0][i] = e[k];
k++;
}
for(int i=1;i<m;i++)
{
a[i][m-1] = e[k];
k++;
}
for(int i=m-2;i>=0;i--)
{
a[m-1][i] = e[k];
k++;
}
for(int i=m-2;i>=1;i--)
{
a[i][0] = e[k];
k++;
}
System.out.println("Sorted matrix");
for(int i = 0 ;i<m;i++)
{
for(int j=0;j<m;j++)
{
System.out.print(a[i][j]+"\t");
}
System.out.println();
}

}
}
58. Write a program to accept the year, month and the weekday name of
the 1st day of that month and generate its calendar.
Solution :-
import java.util.*;
class CalendarProgram
{
//Function to match the given month and return its maximum days
int findMaxDay(String mname, int y)
{
String months[] = {"","January", "February", "March", "April",
"May", "June",
"July", "August", "September", "October", "November",
"December"};
int D[]={0,31,28,31,30,31,30,31,31,30,31,30,31};

if((y%400==0) || ((y%100!=0)&&(y%4==0)))
{
D[2]=29;
}
int max = 0;
for(int i=1; i<=12; i++)
{
if(mname.equalsIgnoreCase(months[i]))
{
max = D[i]; //Saving maximum day of given month
}
}
return max;
}

//Function to match the given weekday name and return its weekday no.
int findDayNo(String wname)
{
String days[] = {"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday",
"Saturday"};
int f = 0;
for(int i=0; i<7; i++)
{
if(wname.equalsIgnoreCase(days[i]))
{
f = i; //Saving week day no. given day (e.g. '0' for Sunday)
}
}
return f;
}

//Function for creating the calendar


void fillCalendar(int max, int f, String mname, int y)
{
int A[][] = new int[6][7];
int x = 1, z = f;

for(int i=0;i<6;i++)
{
for(int j=f; j<7; j++)
{
if(x<=max)
{
A[i][j] = x;
x++;
}
}
f = 0;
}

for(int j=0; j<z; j++) //Adjustment to bring last (6th) row elements to
first row
{
A[0][j]=A[5][j];
}

printCalendar(A, mname, y); //Calling function to print the calendar


}
//Function for printing the calendar
void printCalendar(int A[][], String mname, int y)
{
System.out.println("\n\t----------------------------------------------------");
System.out.println("\t\t\t "+mname+" "+y);
System.out.println("\t----------------------------------------------------");
System.out.println("\tSUN\tMON\tTUE\tWED\tTHU\tFRI\tSAT");
System.out.println("\t----------------------------------------------------");

for(int i = 0; i < 5; i++)


{
for(int j = 0; j < 7; j++)
{
if(A[i][j]!=0)
System.out.print("\t "+A[i][j]);
else
System.out.print("\t ");
}

System.out.println("\n\t----------------------------------------------------");
}
}

public static void main(String args[])


{
CalendarProgram ob = new CalendarProgram();
Scanner sc = new Scanner(System.in);
System.out.print("Enter the year : ");
int y = sc.nextInt();
System.out.print("Enter the month name (e.g. January) : ");
String mname = sc.next();
System.out.print("Enter the week day name (e.g. Sunday) of 1st day
of "+mname+" : ");
String wname = sc.next();

int max = ob.findMaxDay(mname,y);


int f = ob.findDayNo(wname);
ob.fillCalendar(max,f,mname,y);
}
}
73. WAP to get distinct elements from an array by avoiding duplicate
elements.
Solution :-
import java.util.Scanner;
import java.util.Arrays;
class DistinctElement
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("enter no of elemnts in an array");
int n = sc.nextInt();
int a[] = new int[n];
System.out.println("enter elemnts");
for(int i = 0;i<n;i++)
{
a[i] = sc.nextInt();
}
Arrays.sort(a);
int res_ind = 1, ip_ind = 1;
while (ip_ind != a.length)
{
if(a[ip_ind] != a[ip_ind-1])
{
a[res_ind] = a[ip_ind];
res_ind++;
}
ip_ind++;

}
System.out.println("DistinctElement");
for(int i = 0;i<res_ind;i++)
{
System.out.println(a[i]);
}
}
}
Set II
7. WAP that illustrates java thread joins.
Solution :-
class ThreadJoin extends Thread{
public void run() {
for (int i = 0; i <= 5; i++) {
try {
Thread.sleep(500);
} catch(Exception ex) {
System.out.println(ex);
}
System.out.println(i + " " +
Thread.currentThread().getName());
}
}
public static void main(String args[]) {
ThreadJoin t1 = new ThreadJoin();
ThreadJoin t2 = new ThreadJoin();
ThreadJoin t3 = new ThreadJoin();

t1.start();

try {
t1.join();
}
catch(Exception e) {
System.out.println(e);
}

t2.start();
t3.start();
}
}
18. How to create Java URL object. Write a Program.
Solution :-
import java.net.URL;
import java.net.MalformedURLException;
class URLObject {
public static void main(String args[]) {
String link = "ftp://www.google.co.in";
try {
URL url = new URL(link);
System.out.println(url);
}
catch(MalformedURLException e) {
System.out.println(e);
}
}
}
20. How to get list of all IPs of a given Host in Java? Write a Program.
Solution :-
// Java program to find IP address of your computer
// java.net.InetAddress class provides method to get
// IP of any host name
import java.net.*;
import java.io.*;
import java.util.*;
import java.net.InetAddress;

class JavaProgram
{
public static void main(String args[]) throws Exception
{
// Returns the instance of InetAddress containing
// local host name and address
InetAddress localhost = InetAddress.getLocalHost();
System.out.println("System IP Address : " +
(localhost.getHostAddress()).trim());

// Find public IP address


String systemipaddress = "";
try
{
URL url_name = new URL("http://bot.whatismyipaddress.com");

BufferedReader sc = new BufferedReader(new


InputStreamReader(url_name.openStream()));

// reads system IPAddress


systemipaddress = sc.readLine().trim();
}
catch (Exception e)
{
systemipaddress = "Cannot Execute Properly";
}
System.out.println("Public IP Address: " + systemipaddress +"\n");
}
}
32. Write an example for inserting BLOB into table. Write a Program.
Solution :-
import java.sql.*;

class InsertBlob {

public static void main(String a[]){

Connection con = null;


try {
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.
getConnection("jdbc:oracle:thin:@localhost:1521:XE"
,"user","password");
PreparedStatement pstmt = conn.prepareStatement
("INSERT INTO t1 VALUES (?,?)");
pstmt.setInt (1, 100);
File fBlob = new File ( "image1.gif" );
FileInputStream is = new FileInputStream ( fBlob );
pstmt.setBinaryStream (2, is, (int) fBlob.length() );
pstmt.execute ();

} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
con.close();
}
}
}
33. WAP that illustrates the difference between method overloading and
method overriding.
Solution :-
class A
{
void cal(double x)
{
System.out.println("x = " + x);
}

void cal(double x, double y)


{
System.out.println("x = " + x + " y = " + y);
}
}

class B extends A
{
void cal(double x)
{
System.out.println("x = " + x * x);
}
}

class Polymorphism {
public static void main(String args[]) {
A a = new A();
B b = new B();
// overloading
a.cal(15);
a.cal(15, 20);

// overriding
a.cal(10);
b.cal(10);
}
}
The End

Vous aimerez peut-être aussi