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

Assignment 2

The document contains 11 programming questions and their solutions in Java. Each question asks the student to write a Java program to perform a specific task such as moving all zeros to the end of an array, finding the k largest elements in an array, checking if a number is a palindrome, and more. For each question, the student's code and the output are provided. The last question asks the student to write a program that inputs 5 unique random numbers between 10-100 and displays them without duplicates.

Uploaded by

Aayush Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
93 views

Assignment 2

The document contains 11 programming questions and their solutions in Java. Each question asks the student to write a Java program to perform a specific task such as moving all zeros to the end of an array, finding the k largest elements in an array, checking if a number is a palindrome, and more. For each question, the student's code and the output are provided. The last question asks the student to write a program that inputs 5 unique random numbers between 10-100 and displays them without duplicates.

Uploaded by

Aayush Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 20

ASSIGNMENT-2

Name:- Aayush Kumar

Roll no.:- 12112126

Section:- CSB-06

Q1)

//Write a java program that reads an integers and then moves every zero to
the right side i.e. towards the end.

import java.util.*;

public class Q1 {
   
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int size;
        System.out.println("Enter the size of Array:- ");
        size = input.nextInt();
        int arr[] = new int[size];
        System.out.println("Enter the elements of Array:- ");
        for(int i = 0;i<size;i++) {
            arr[i] = input.nextInt();
        }
        boolean swap = true;
        while(swap){
            swap = false;
            for(int i = 0;i<size-1;i++) {
                    if(arr[i] == 0 && arr[i+1] != 0) {
                        int t = arr[i];
                        arr[i] = arr[i+1];
                        arr[i+1] = t;
                        swap = true;
                    }
            }
        }
        System.out.println("After Swapping:- ");
        System.out.print(Arrays.toString(arr));
       
    }
}

Output:-
Q2)

// Write a Java program to find the k (for given k) largest elements in a


given array.Elements in the array can be in any order. Don’t forget to check
boundary condition for k.
import java.util.*;

public class Q2 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int size;
        System.out.println("Enter the size of Array:- ");
        size = input.nextInt();
        int arr[] = new int[size];
        System.out.println("Enter the elements of Array:- ");
        for(int i = 0;i<size;i++) {
            arr[i] = input.nextInt();
        }
        System.out.println("Enter the kth element:- ");
        int key = input.nextInt();
        Arrays.sort(arr);
        System.out.println(arr[key-1]);
    }
}

Output:-

Q3)

// Write a Java program to check if a given positive number is a palindrome


or not.

import java.util.*;

public class Q3 {
    static int reverseDigits(int num)
    {
        int rev_num = 0;
        while (num > 0) {
            rev_num = rev_num * 10 + num % 10;
            num = num / 10;
        }
        return rev_num;
    }
     
    static int isPalindrome(int n)
    {
     
        int rev_n = reverseDigits(n);
        if (rev_n == n)
            return 1;
        else
            return 0;
    }
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int num;
        System.out.println("Enter the number to check palindrome or not:- ");

        num = input.nextInt();
       
        System.out.println(isPalindrome(num) == 1?"Yes, it is a palindrome
":"No, the number is not a palindrome");
       
    }    
}

Output:-

Q4)

// Write a Java program to check if an array of integers contains three


increasing adjacent numbers.
import java.util.Scanner;

public class Q4 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int size;
        System.out.println("Enter the size of Array:- ");
        size = input.nextInt();
        int arr[] = new int[size];
        System.out.println("Enter the elements of Array:- ");
        for(int i = 0;i<size;i++) {
            arr[i] = input.nextInt();
        }
        int result = 0;;
        for (int i = 0; i < size-3; i++) {
            if(arr[i] == (arr[i+1] + 1) && arr[i+1] == (arr[i+2] + 1)) {
                result = 0;
            }
        }
            if(result == 1){
                System.out.println("false");
            } else {
                System.out.println("true");
            }
    }
}

Output:-

Q5)

//Write a java program to find the number of integers within the range of two
specified numbers x & y and that are divisible by another number, p.

import java.util.Scanner;

public class Q5 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int range1,range2,p;
        System.out.println("Enter the Range to check:- ");
        range1 = input.nextInt();
        range2 = input.nextInt();
        System.out.println("Enter divisible number:- ");
        p = input.nextInt();
        if(range1%p == 0) {
            System.out.println("Total number of integers divisible are:- " +
(range2/p - range1/p + 1));
        } else {
            System.out.println("Total number of integers divisible are:- " +
(range2/p - range1/p));
        }
    }
}

Output:-

Q6)

//Write a Java program to accept two strings and test if the second string
contains the first one.
import java.util.*;

public class Q6 {
    public static boolean is_str_contains(String str1, String str2) {
        if (str1 == null || str2 == null) {
            throw new IllegalArgumentException("You can't pass null strings as
input.");
        }
        boolean ans = false;
        for (int i = 0; i < str2.length() - 1; i++) {
            if (str2.charAt(i) == str1.charAt(0)) {
                for (int j = 0; j < str1.length(); j++) {
                    if ((i + j) < str2.length() && str1.charAt(j) ==
str2.charAt(i + j) && j == str1.length() - 1) {
                        ans = true;
                        break;
                    }
                }
            }
        }
        return ans;
    }

    public static void main(String[] args) {


        Scanner input = new Scanner(System.in);

        System.out.print("Input first string: ");


        String str1 = input.nextLine();
       
        System.out.print("Input second string: ");
        String str2 = input.nextLine();
       
        System.out.println("If the second string contains the first one? " +
is_str_contains(str1, str2));
    }
}

Output:-

Q7)

//Write a Java program to read two strings from keyboard and compare them
lexicographically.
import java.util.*;

public class Q7 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter First String:- ");
        String str1 = input.nextLine();

        System.out.println("Enter Second String:- ");


        String str2 = input.nextLine();
        System.out.print("Result:- ");
        System.out.println(str1.compareTo(str2));        
    }
}

Output:-

Q8)

//Write a Java program to teset if a given string contains the specified


sequeance of char values.

import java.util.*;
public class Q7 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter First String:- ");
        String str1 = input.nextLine();

        System.out.println("Enter Second String:- ");


        String str2 = input.nextLine();
        System.out.print("Result:- ");
        System.out.println(str1.contains(str2));        
    }
}

Output:-

Q9)

//Write a Java program to trim any leading or trailing whitespace from a


given string.

import java.util.*;

public class Q7 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter First String:- ");
        String str1 = input.nextLine();

        System.out.print("Trimmed Result:- ");


        System.out.println(str1.trim());        
    }
}

Output:-

Q10)
//Write a java program that read an arbitrary number of even integers that
are in the range 2 to 100 inclusive and counts how many occurrences of each
are entered. Indicate the end of the input by entering -1. After entire input
has been processed, print all of the values that were entered by the user
along with the number of occurrences.

import java.util.*;

import javax.naming.spi.InitialContextFactoryBuilder;

public class Q10 {


    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        final int MAXINT = 100;
        final int MININT = 2;
        int[] list = new int[MAXINT+1];

        for(int i = 0;i<list.length;i++) {
            list[i] = 0;
        }
        System.out.println(("Enter the list of integers between 2 to 100"));
        System.out.println("To stop enter an integer out of the range. i.e.:-
-1");
        System.out.println("Enter Integer");
        int inclusive = input.nextInt();
        while(inclusive >= MININT && inclusive <= MAXINT) {
            list[inclusive] = list[inclusive] + 1;

            System.out.println("Enter next Integer:- ");


            inclusive = input.nextInt();
        }
        for(int i = 0;i<list.length;i++) {
            if(list[i] > 0) {
                System.out.println(i + ": " + list[i]);
            }
        }
    }
}

Output:-
Q11)

/* Use a one-dimensional array to solve the following problem:


Write an application that inputs five numbers, each between 10 and 100,
inclusive. As
each number is read, display it only if it’s not a duplicate of a number
already read.
Provide for the worst case in which all five numbers are different. Use the
smallest
possible array to solve this problem. Display the complete set of unique
values input
after the user enters each new value. */

import java.util.*;

public class Q11 {


    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        int number = 0;
        int size = 5;
       
        int arr[] = new int[size];
        System.out.println("Enter 5 elements in the Array:- ");
       
        for(int i = 0;i<size;i++) {
            arr[i] = input.nextInt();
        }

        for(int counter = 0; counter < size; counter++ )


        {
            System.out.print("Enter a number to check: ");
            number = input.nextInt();
            boolean found = false;

            for (int j = 0; j < size; j++) {


                if (number == arr[j]) {
                    found = true;
                    break;
                }
            }
            if (found) {
                System.out.printf("The number %d is already in the array.\n\
n", arr[counter]);
            } else {
                System.out.printf("The number %d is not in the array.\n\n",
number);
            }          
        }
    }
}

Output:-

Q12)

// Write a class called NumberOfSixes that represents the total number of


sixes hit by an
// IPL team in a given match. The NumberOfSixes class should contain a single
integer
// as instance data, representing the number of sixes hit. Write a
constructor to initialize
// the number of sixes to zero. Write a method called setSix that increments
the value by
// one whenever a six is hit, and another method called getSix that returns
the total
// number of sixes hit so far. Finally, create a driver class called
SixTracker that creates
// a few NumberOfSixes objects and tests their methods.

/**
 * InnerQ12
 */
class NumberOfSixes {
    int sixes;
    NumberOfSixes() {
        sixes = 0;
    }
    public void setSix() {
        sixes++;
    }
    public int getSix() {
        return sixes;
    }
   
}
public class Q12 {

    public static void main(String[] args) {


        NumberOfSixes sixes = new NumberOfSixes();
        NumberOfSixes sixes2 = new NumberOfSixes();
        NumberOfSixes sixes3 = new NumberOfSixes();
       
        sixes.setSix();
        System.out.println(sixes.getSix());
    }
   
}

Output:-

Q13)

/* Design and implement a set of classes that define various types of reading
material:
books, novels, magazines, technical journals, textbooks, and so on. Include
data
values that describe various attributes of the material, such as the number
of pages
and the names of the primary characters. Include methods that are named
appropriately for each class and that print an appropriate . Create a main
driver class to instantiate and exercise several of the classes.
*/
import java.util.*;

class Novel
{
    int number_Of_Page;//
    String names_Of_Primary_Characters;//

    Novel()//
    {
        number_Of_Page = 0;
        names_Of_Primary_Characters = "";
    }

    void setPages(int num)// to hold


    {
        this.number_Of_Page = num;//  to hold
    }

    void setCharacters(String names)// to hold


    {
        this.names_Of_Primary_Characters = names;//  to hold
    }

    int getPages()// to return


    {
        return number_Of_Page;// return
    }

    String getCharacters()// to return


    {
        return names_Of_Primary_Characters;// return
    }
}

class Magazines
{
    int number_Of_Page;
    String names_Of_Primary_Characters;

    Magazines()//
    {
        number_Of_Page = 0;
        names_Of_Primary_Characters = "";
    }

    void setPages(int num)// to hold


    {
        this.number_Of_Page = num;//  to hold
    }

    void setCharacters(String names)// to hold


    {
        this.names_Of_Primary_Characters = names;//  to hold
    }

    int getPages()
    {
        return number_Of_Page;
    }

    String getCharacters()
    {
        return names_Of_Primary_Characters;
    }
}

class TechnicalJournals
{
    int number_Of_Page;
    String names_Of_Primary_Characters;

    TechnicalJournals()
    {
        number_Of_Page = 0;
        names_Of_Primary_Characters = "";
    }

    void setPages(int num)// to hold


    {
        this.number_Of_Page = num;//  to hold
    }

    void setCharacters(String names)// to hold a


    {
        this.names_Of_Primary_Characters = names;//  to hold
    }

    int getPages()// to return


    {
        return number_Of_Page;// return
    }

    String getCharacters()// to return


    {
        return names_Of_Primary_Characters;// return
    }
}

class Textbooks// Textbooks


{
    int number_Of_Page;//
    String names_Of_Primary_Characters;//

    Textbooks()//
    {
        number_Of_Page = 0;
        names_Of_Primary_Characters = "";
    }

    void setPages(int num)// to hold


    {
        this.number_Of_Page = num;//  to hold
    }

    void setCharacters(String names)// to hold


    {
        this.names_Of_Primary_Characters = names;//  to hold
    }

    int getPages()// to return


    {
        return number_Of_Page;// return
    }

    String getCharacters()// to return


    {
        return names_Of_Primary_Characters;// return
    }
}

public class Q13 // Books


{
    public static void main(String args[])//
    {
        int num, c;//
        String names;//
        Scanner obx = new Scanner(System.in); // creating Scanner cla
        System.out.println("Choose a type of book: ");// print
        System.out.println("1. Novel");// print
        System.out.println("2. Magazine");// print
        System.out.println("3. Technical Journals");// print
        System.out.println("4. Textbooks");// print
        c = obx.nextInt();//
        System.out.println("Enter number of pages:");// print
        num = obx.nextInt();//
        System.out.println("Enter names of important characters:(with
spaces)"); // print
        names = obx.next();//
        switch (c){
            case 1:
                Novel n = new Novel();
                System.out.println("****Novel****");//
                n.setPages(num);//
                n.setCharacters(names);//
                System.out.println("The number of pages are: " +
n.getPages());
                System.out.println("The important characters are:" +
n.getCharacters());
                break;//
            case 2:
                Magazines n1 = new Magazines();
                System.out.println("****Magazines****");//
                n1.setPages(num);//
                n1.setCharacters(names);//
                System.out.println("The number of pages are: " +
n1.getPages());
                System.out.println("The important characters are:" +
n1.getCharacters());
                                                                             
                break;//
            case 3:
                TechnicalJournals n2 = new TechnicalJournals();
                System.out.println("****TechnicalJournals****");
                n2.setPages(num);//
                n2.setCharacters(names);//
                System.out.println("The number of pages are: " +
n2.getPages());
                System.out.println("The important characters are:" +
n2.getCharacters());
                                                                             
                break;//
            case 4:
                Textbooks n3 = new Textbooks();
                System.out.println("****Textbooks****");
                n3.setPages(num);
                n3.setCharacters(names);
                System.out.println("The number of pages are: " +
n3.getPages());
                System.out.println("The important characters are:" +
n3.getCharacters());
                break;
            default:
                System.out.println("Thank you!");
                break;
        }
    }
}

Output:-

Q14)

import java.util.Scanner;

/*Create class SavingsAccount. Use a static variable annualInterestRate to


store the
annual interest rate for all account holders. Each object of the class
contains a private
instance variable savingsBalance indicating the amount the saver currently
has on
deposit. Provide method calculateMonthlyInterest to calculate the monthly
interest by
multiplying the savingsBalance by annualInterestRate divided by 12—this
interest
should be added to savings-Balance. Provide a static method
modifyInterestRate that
sets the annualInterestRate to a new value. Write a program to test class
SavingsAccount. Instantiate two savingsAccount objects, saving1 and saving2,
with
balances of `2000.00 and `3000.00, respectively. Set annualInterestRate to
4%, then
calculate the monthly interest for each of 12 months and print the new
balances for
both savers. Next, set the annualInterestRate to 5%, calculate the next
month’s
interest and print the new balances for both savers. */

class SavingsAccount {

    static double annualInterestRate;


    private double savingsBalance;

    public SavingsAccount(double balance) {


        savingsBalance = balance;
    }

    public double calculateMonthlyInterest() {


        return (savingsBalance * annualInterestRate) / 12;
    }

    public static void modifyInterestRate(double rate) {


        annualInterestRate = rate;
    }

    public static double getannualInterestRate() {


        return annualInterestRate;
    }

    public double getsavingsBalance() {


        return savingsBalance;
    }

public class Q14 {


    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter Amount of Savings1:- ");
        double savings1 = input.nextDouble();
       
        System.out.print("Enter Amount of Savings2:- ");
        double savings2 = input.nextDouble();
       
        System.out.print("Enter rate of interest:- ");
        int rate1 = input.nextInt();

        SavingsAccount saving1 = new SavingsAccount(savings1);


        SavingsAccount saving2 = new SavingsAccount(savings2);
        SavingsAccount.modifyInterestRate(rate1);

        System.out.println("Enter modified rate of interest:- ");


        int rate2 = input.nextInt();

        System.out.printf("Balance for Saving1 = %.2f\nBalance for Saving2 =


%.2f\nInterest Rate = %.2f\n\n",
                saving1.getsavingsBalance() +
saving1.calculateMonthlyInterest(), saving2.getsavingsBalance(),
                SavingsAccount.getannualInterestRate());

        SavingsAccount.modifyInterestRate(rate2);

        System.out.printf("New Balance for Saving1 = %.2f\nNew Balance for


Saving2 = %.2f\nInterest Rate = %.2f\n\n",
                saving1.getsavingsBalance(), saving2.getsavingsBalance(),
SavingsAccount.getannualInterestRate());
    }
}

Output:-

Q15)

/* */
class StopWatch {
    private long startTime = System.currentTimeMillis();
    private long endTime = startTime;

    public StopWatch() {
   
    }

    public long getStartTime() {


        return this.startTime;
    }

    public long getEndTime() {


        return this.endTime;
    }

    public void start() {


        this.startTime = System.currentTimeMillis();
    }

    public void stop() {


        this.endTime = System.currentTimeMillis();
    }

    public long getElapsedTime() {


        return this.endTime - this.startTime;
    }
}

public class Q15 {


    StopWatch stopWatch = new StopWatch();
    stopwatch.start();
    stopwatch.stop();

    System.out.print("Program took " + stopWatch.getElapsedTime() +


"milliseconds.")

UML Diagram

You might also like