CSE-1007 (Java Programming) Digital Assignment-1
CSE-1007 (Java Programming) Digital Assignment-1
DIGITAL ASSIGNMENT-1
Name: - Ayush Roy Slot: - L51+L52
Reg No: - 20BCE0260 Date: - 10/09/21
Code: -
public class factorial
{
public static void main (String args[])
{
int n,i,fact=1;
n=Integer.parseInt(args[0]);
for(i=1;i<=n;i++)
{
fact=fact*i;
}
System.out.println("The factorial is: "+fact);
}
}
Sample I/O: -
2) Write a program to print the multiplication table of a number.
Code: -
import java.util.*;
public class multiplication
{
public static void main (String args[])
{
Scanner sc= new Scanner(System.in);
int n,i,limit;
System.out.println("Enter the number whose table you want: ");
n=sc.nextInt();
System.out.println("Enter the number upto which you want the table: ");
limit=sc.nextInt();
for(i=1;i<=limit;i++)
{
System.out.println(n+" * "+i+" = "+(n*i));
}
}
}
Sample I/O: -
3) Write a program to check whether the given number is an Armstrong
number or not.
Code: -
import java.util.*;
public class armstrong
{
public static void main (String args[])
{
Scanner sc= new Scanner(System.in);
int n,temp,rem,sum;
System.out.println("Enter the number: ");
n=sc.nextInt();
temp=n;
sum=0;
while (temp>0)
{
rem=temp%10;
sum=sum+(int)(Math.pow(rem,3));
temp=temp/10;
}
if(n==sum)
System.out.println(n+" is an Armstrong number.");
else
System.out.println(n+" is not an Armstrong number.");
}
}
Sample I/O: -
4) Write a program to check whether the given number is a prime number
or not.
Code: -
import java.util.*;
public class prime
{
public static void main (String args[])
{
Scanner sc= new Scanner(System.in);
int n,i,count=0;
System.out.println("Enter the number: ");
n=sc.nextInt();
if(n==0||n==1)
{
System.out.println(n+" is not a Prime number.");
}
else
{
count=0;
for(i=1;i<=n;i++)
{
if(n%i==0)
count++;
}
if(count<=2)
System.out.println(n+" is a Prime number.");
else
System.out.println(n+" is not a Prime number.");
}
}
}
Sample I/O: -
5) Write a program to generate the following patterns: -
(i) 1
1 2
1 2 3
Code: -
import java.util.*;
public class pattern1
{
public static void main(String args[])
{
int i,j,n;
Scanner sc = new Scanner(System.in);
System.out.println("Enter number of rows: ");
n=sc.nextInt();
(ii) *
* *
* * *
* *
Code: -
import java.util.*;
public class pattern2
{
public static void main(String args[])
{
int n, i, j, space = 1;
System.out.print("Enter the number of rows: ");
Scanner s = new Scanner(System.in);
n = s.nextInt();
space = n - 1;
for (j = 1; j <= n; j++)
{
for (i = 1; i <= space; i++)
{
System.out.print(" ");
}
space--;
for (i = 1; i <= 2 * j - 1; i++)
{
System.out.print("*");
}
System.out.println("");
}
space = 1;
for (j = 1; j <= n - 1; j++)
{
for (i = 1; i <= space; i++)
{
System.out.print(" ");
}
space++;
for (i = 1; i <= 2 * (n - j) - 1; i++)
{
System.out.print("*");
}
System.out.println("");
}
}
}
Sample I/O: -
6) Write a program to generate the Fibonacci series.
Code: -
import java.util.*;
public class pattern2
{
public static void main(String args[])
{
int n,i,a=0,b=1,c;
System.out.print("Enter the number of terms: ");
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
Sample I/O: -
7) Write a program to sort n numbers in ascending order.
Code: -
import java.util.*;
public class ascsorting
{
public static void main(String args[])
{
int n,i,j,temp=0;
System.out.println("Enter the number of terms: ");
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
int arr[] = new int[n];
for(i=0;i<arr.length;i++)
{
for(j=i+1;j<arr.length;j++)
{
if(arr[j]<arr[i])
{
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}
Sample I/O: -
8) Write a program to search a number among n numbers using binary
search.
Code: -
import java.util.*;
public class binarysearch
{
public static void main(String args[])
{
//binary search works only on sorted arrays. So we are sorting first using bubble sort
technique.
int n,i,j,key,low,high,mid=0,flag=0,temp;
System.out.println("Enter the number of terms: ");
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
int arr[] = new int[n];
while(low<=high)
{
mid=(low+high)/2;
if(arr[mid]==key)
{
flag=1;
break;
}
else if(arr[mid]<key)
{
low=mid+1;
}
else
high=mid-1;
}
if(flag==0)
System.out.println("Element not found!");
else
System.out.println("Element is found at position "+(mid+1)+" in the sorted array");
}
}
Sample I/O: -
9) Write a program to read ‘n’ numbers and print their sum and average.
Code: -
import java.util.*;
public class sumavg
{
public static void main(String args[])
{
int n,i,sum=0;
float avg=0.0f;
System.out.println("Enter the number of terms: ");
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
int arr[] = new int[n];
avg=(float)sum/n;
System.out.println("Sum of numbers= "+sum+" and average of numbers= "+avg);
}
}
Sample I/O: -
10) Write a program that accepts a number as input and convert them to
binary, octal and hexadecimal equivalents.
Code: -
import java.util.*;
public class conversion
{
public static void main(String args[])
{
int n;
String hexa,octal,binary;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the decimal number: ");
n=sc.nextInt();
hexa=Integer.toHexString(n);
octal=Integer.toOctalString(n);
binary=Integer.toBinaryString(n);
Sample I/O: -
11) Write a menu driven program to (i) append a string (ii) insert a string
and (iii) delete a portion of the string.
Code: -
import java.util.*;
public class conversion
{
public static void main(String args[])
{
int ch;
Scanner sc = new Scanner(System.in);
System.out.println("1.APPEND 2.INSERT 3.DELETE 4.EXIT");
System.out.println("Enter your choice: ");
ch=sc.nextInt();
class transfer
{
int i,index,start,end;
Scanner sc = new Scanner(System.in);
void append()
{
System.out.println("Enter first string: ");
String s1 = new String();
sc.next();
System.out.println("Enter string you want to append to the first string: ");
String s2 = new String();
sc.next();
String s3 = new String();
s3=s1.concat(s2);
System.out.println("Appended string is : "+s3);
}
void insert()
{
System.out.println("Enter first string: ");
String originalString = new String();
originalString = sc.next();
System.out.println("Enter string to be inserted: ");
String stringInserted = new String();
stringInserted=sc.next();
System.out.println("Enter index where string is to be inserted: ");
index=sc.nextInt();
void delete()
{
System.out.println("Enter original string: ");
String s1 = new String();
s1=sc.next();
String s2 = new String();
System.out.println("Enter start and end points of deletion: ");
start=sc.nextInt();
end=sc.nextInt();
s2=s1.substring(0,start-1)+s1.substring(end,s1.length());
System.out.println("Modified string after deletion is: "+s2);
}
}
Sample I/O: -
12) Write a program to check whether a string is palindrome or not
without using functions.
Code: -
import java.util.*;
public class Palindrome
{
public static void main(String args[])
{
String str, rev = "";
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string:");
str = sc.next();
if (str.equals(rev))
System.out.println(str+" is a palindrome");
else
System.out.println(str+" is not a palindrome");
}
}
Sample I/O: -
13) Write a menu driven program to i) compare two strings ii) get the
character in the specified position iii) extract a substring iv) replace a
character with the given character v) get the position of a specified
substring/character.
Code: -
import java.util.*;
public class conversion
{
public static void main(String args[])
{
int ch;
Scanner sc = new Scanner(System.in);
System.out.println("1.COMPARE 2.CHARACTER AT SPECIFIED POSITION
3.SUBSTRING 4.REPLACE 5.POSITION OF SPECIFIED CHARACTER 6.EXIT");
System.out.println("Enter your choice: ");
ch=sc.nextInt();
class transfer
{
int i,index,start,end,pos=0;
char c,c1;
Scanner sc = new Scanner(System.in);
void compare()
{
System.out.println("Enter first string: ");
String s1 = new String();
s1=sc.next();
System.out.println("Enter second string: ");
String s2 = new String();
s2=sc.next();
if(s1.compareTo(s2)<0)
System.out.println("2nd string is larger");
else if(s1.compareTo(s2)>0)
System.out.println("1st string is larger");
else
System.out.println("Strings are same");
}
void chrspepo()
{
System.out.println("Enter the string: ");
String s1 = new String();
s1 = sc.next();
System.out.println("Enter position of required character: ");
index=sc.nextInt();
c=s1.charAt(index-1);
System.out.println("Character at specified position is: "+c);
}
void sub()
{
System.out.println("Enter original string: ");
String s = new String();
s=sc.next();
System.out.println("Enter start and end indices of extraction: ");
start=sc.nextInt();
end=sc.nextInt();
String s1 = new String();
s1=s.substring(start,end+1);
System.out.println("Substring extracted is: "+s1);
}
void replace()
{
System.out.println("Enter the string: ");
String s1 = new String();
s1 = sc.next();
String s2 = new String();
System.out.println("Enter character which you want to replace: ");
c=sc.next().charAt(0);
System.out.println("Enter replacing character: ");
c1=sc.next().charAt(0);
s2=s1.replace(c,c1);
System.out.println("Modified string is: "+s2);
}
void pospechr()
{
System.out.println("Enter the string: ");
String s1 = new String();
s1 = sc.next();
System.out.println("Enter character whose position you want: ");
c=sc.next().charAt(0);
pos=s1.indexOf(c);
System.out.println("Position of specified character is: "+(pos+1));
}
}
Sample I/O: -
14) Write a program to change the case of the letters in a string. Eg.
ABCdef -> abcDEF.
Code: -
import java.util.*;
public class topsyturvy
{
public static void main(String args[])
{
String str,newstr="";
int i;
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string:");
str = sc.next();
for(i=0;i<str.length();i++)
{
if(Character.isLowerCase(str.charAt(i)))
newstr+=Character.toUpperCase(str.charAt(i));
if(Character.isUpperCase(str.charAt(i)))
newstr+=Character.toLowerCase(str.charAt(i));
}
Sample I/O: -
15) Write a class with the following methods: -
wordCount: This method accepts a String object as an argument and
returns the number of words contained in the object.
arrayToString: This method accepts a char array as an argument and
converts it to a String object.
mostFrequent: This method accepts a String object as an argument and
returns the character that occurs the most frequently in the object.
Code: -
import java.util.*;
public class threemethods
{
public static void main(String args[])
{
String str,str2;
for(i=0;i<string.length;i++)
{
freq[i]=1;
for(j = i+1; j < string.length; j++)
{
if(string[i] == string[j] && string[i] != ' ' && string[i] != '0')
{
freq[i]++;
string[j]='0';
}
}
}
max=freq[0];
for(i = 0; i <freq.length; i++)
{
if(max < freq[i])
{
max = freq[i];
maxChar = string[i];
}
}
System.out.println("Maximum occurring character: " + maxChar);
}
}
Sample I/O: -
16) Create a class Student (Regno, Name, Branch, Year, Semester and 5
Marks). Add methods to read the student details, calculate the grade
and print the mark statement.
Code: -
import java.util.*;
public class Student
{
public static void main(String args[])
{
System.out.println("ENTER STUDENT DETAILS: ");
System.out.println("-----------------------");
details();
System.out.println();
System.out.println("ENTER MARKS DETAILS AND GET GRADE DETAILS: ");
System.out.println("-------------------------------------------");
marksgrade();
}
Sample I/O: -
17) Write a program that displays an invoice of several items. Create a
class called Item with members item_name, quantity, price and
total_cost and methods to get and set values for the members. Derive a
new class to print the bill using Item class.
Code: -
import java.util.*;
public class Item
{
static String item_name;
static float quantity,price,total_cost;
public static void main(String args[])
{
System.out.println("GET VALUES FROM USER: ");
System.out.println("----------------------");
get();
billing b1 = new billing();
b1.getCost();
System.out.println();
System.out.println("SET PREDEFINED VALUES FROM SYSTEM: ");
System.out.println("-----------------------------------");
set();
billing b2 = new billing();
b2.getCost();
System.out.println();
}
Sample I/O: -
18) Create a class Telephone with two members to hold customer’s name
and phone number. The class should have appropriate constructor, input
and display methods. Derive a class TelephoneIndex with methods to
change the name or phone number. Create an array of objects and
perform the following functions: -
a. Search for a name when the user enters a name or the first few
characters.
b. Display all of the names that match the user’s input and their
corresponding phone numbers.
c. Change the name of a customer.
d. Change the phone number of a customer.
Code: -
import java.util.*;
class Telephone
{
private String name;
private String phoneNumber;
public Telephone()
{}
public Telephone(String name, String phoneNumber)
{
this.name = name;
this.phoneNumber = phoneNumber;
}
public String getName()
{
return name;
}
public void setName(String s)
{
this.name = s;
}
public String getNumber()
{
return phoneNumber;
}
public void setNumber(String phoneNumber)
{
this.phoneNumber = phoneNumber;
}
}
Sample I/O: -
19) Create an abstract class called BankAccount with members customer
name, date of birth, address, account number, balance and member
functions to get values for the members and display it. Derive a class
SavingsAccount with member functions to perform deposit and withdraw
in the account. Write a menu driven program to create a new account,
perform withdraw, deposit and delete an account.
Code: -
import java.util.*;
abstract class BankAccount
{
String name,dob,address;
int accno,bal;
public void input()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter name of customer: ");
name=sc.nextLine();
System.out.println("Enter date of birth of customer: ");
dob=sc.nextLine();
System.out.println("Enter address of customer: ");
address=sc.nextLine();
System.out.println("Enter account number of customer: ");
accno=sc.nextInt();
System.out.println("Enter account balance of customer: ");
bal=sc.nextInt();
}
public void display()
{
System.out.println(name+"\t"+dob+"\t"+address+"\t"+accno+"\t"+bal);
}
}
case 2:
if (i == -1)
System.out.println ("\nNo accounts in database.");
else
{
System.out.print ("Enter withdrawal amount: ");
withamt= sc.nextInt();
obj[i].bal= obj[i].withdraw(withamt);
System.out.println ("\nName\tDOB\tAddress\tA/C No.\tBalance");
for (j= 0; j <= i; j++)
obj[j].display();
}
break;
case 3:
if (i == -1)
System.out.println ("\nNo accounts in database.");
else
{
System.out.print ("Enter deposition amount: ");
depoamt= sc.nextInt();
obj[i].bal= obj[i].deposit(depoamt);
System.out.println ("\nName\tDOB\tAddress\tA/C No.\tBalance");
for (j= 0; j <= i; j++)
obj[j].display();
}
break;
case 4:
if (i == -1)
System.out.println ("\nNo accounts in database");
else
{
System.out.println ("\nAccount with A/C Number \'"+obj[i].accno+"\' has been
deleted");
i--;
System.out.println ("\nName\tDOB\tAddress\tA/C No.\tBalance");
for (j= 0; j <= i; j++)
obj[j].display();
}
break;
case 5:
System.out.println ("\nFinished");
break;
default:
System.out.println ("\nInvalid choice");
}
}while (ch != 5);
}
}
Sample I/O: -
20) Create an Interface with methods add(), sub(), multiply() and
divide(). Write two classes FloatValues to perform arithmetic operations
on floating point numbers and IntegerValues on integer numbers by
implementing the interface.
Code: -
import java.util.*;
interface A
{
public void add();
public void sub();
public void multiply();
public void divide();
}
Sample I/O: -
21) Write the following two methods under an interface Number: -
// Return the reversal of an integer, i.e. reverse(456) returns 654
public static int reverse(int number)
// Return true if number is palindrome
public static boolean isPalindrome(int number)
Use the reverse method to implement isPalindrome. A number is a
palindrome if its reversal is the same as itself. Write a test program to
implement the interface Number and prompts the user to enter an integer
and reports whether the integer is a palindrome.
Code: -
import java.util.*;
interface Number
{
public abstract int reverse(int number);
public abstract boolean isPalindrome(int number);
}
Sample I/O: -
22) Write a method to implement the binary search. Use a package that
has the class sort with a method void bubble_sort(double[] array) to
perform a bubble sort
public void search(double[] array)
Write a test program that prompts the user to enter n numbers, and a
search element. Invoke this method to return the position of the search
element.
Code: -
package mypack;
public class sort
{
public void bubble_sort(double[] array)
{
int n=array.length;
double temp=0;
for(int i=0;i<n;i++)
{
for(int j=i+1; j<n; j++)
{
if(array[i] > array[j])
{
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
}
}
import java.util.*;
public class binarysearch
{
public static void main(String args[])
{
int n,i,low,high,mid=0,flag=0,temp;
double key;
System.out.println("Enter the number of terms: ");
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
double array[] = new double[n];
while(low<=high)
{
mid=(low+high)/2;
if(array[mid]==key)
{
flag=1;
break;
}
else if(array[mid]<key)
{
low=mid+1;
}
else
high=mid-1;
}
if(flag==0)
System.out.println("Element not found!");
else
System.out.println("Element is found at position "+(mid+1)+" in the sorted array");
}
}
Sample I/O: -
23) Write a program that has a class Factor with a method boolean
isFactor(int n, int m) that checks if n is a factor of m. Write another
class Divisibleby2 that derives Factor class. Override the isFactor(n,m)
method to find it is divisible by 2 or not. Write another class
Divisibleby3 that derives Factor class. Override the isFactor(n,m)
method to find it is divisible by 3 or not. Write a test method that
creates object for 2 classes. Get a number n from the user and check
whether it is divisible by 6.
Code: -
import java.util.*;
class Factor
{
boolean isFactor(int n, int m)
{
if(m%n==0)
return true;
else
return false;
}
}
Sample I/O: -