Home

Learn Programming & Prepare for NPTEL Exams... Swayam Solver is your one-stop destination for NPTEL exam preparation.

NPTEL Programming In Java Programming Assignment July-2024 Swayam

NPTEL Programming In Java Programming Assignment July-2024 Swayam

 

NPTEL » Programming in Java


  Please scroll down for latest Programs. ðŸ‘‡ 


Week 01 : Programming Assignment 1

Due on 2024-08-08, 23:59 IST

Write a Java program to print the area and perimeter of a rectangle.

Select the Language for this assignment. 
File name for this program : 
1
import java.util.Scanner;
2
public class W01_P1 { 
3
   public static void main(String[] strings) {
4
       double width ;
5
       double height;
6
7
       Scanner in = new Scanner(System.in);
8
       width = in.nextDouble();
9
       height = in.nextDouble();
10
// Calculate the perimeter of the rectangle
11
double perimeter = 2 * ( width + height );
12
13
// Calculate the area of the rectangle
14
double area = width * height ;
0
// Print the calculated perimeter using placeholders for values
1
       System.out.printf("Perimeter is 2*(%.1f + %.1f) = %.2f\n", height, width, perimeter);
2
3
// Print the calculated area using placeholders for values
4
       System.out.printf("Area is %.1f * %.1f = %.2f", width, height, area);    
5
   }
6
}
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
5.6 8.5
Perimeter is 2*(8.5 + 5.6) = 28.20\n
Area is 5.6 * 8.5 = 47.60
Perimeter is 2*(8.5 + 5.6) = 28.20\n
Area is 5.6 * 8.5 = 47.60
Passed





Private Test cases used for EvaluationStatus
Test Case 1
Passed



Week 01 : Programming Assignment 2

Due on 2024-08-08, 23:59 IST

Write a Java program and compute the sum of an integer's digits.

Your last recorded submission was on 2024-07-22, 08:13 IST
Select the Language for this assignment. 
File name for this program : 
1
import java.util.Scanner;
2
public class W01_P2 {
3
    public static void main(String[] args) {
4
        Scanner input = new Scanner(System.in);
5
6
        // Prompt the user to input an integer
7
        //System.out.print("Input an integer: ");
8
9
        // Read the integer from the user
10
        long n = input.nextLong();
11
12
        // Calculate and display the sum of the digits
13
        System.out.print("The sum of the digits is: " + sumDigits(n));
14
    }
15
// Calculate the sum of the digits by defining a sumDigits() function
16
// This should return the sum
17
public static int sumDigits(long n){
18
  int sum = 0;
19
  while( n!=0 )
20
  {
21
    sum += n%10;
22
    n/=10;
23
  }
24
  return sum;
25
}
0
}
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
00020
The sum of the digits is: 2
The sum of the digits is: 2
Passed





Private Test cases used for EvaluationStatus
Test Case 1
Passed



Week 01 : Programming Assignment 3

Due on 2024-08-08, 23:59 IST

Write a Java program to display n terms of natural numbers and their sum.

(Remember to match the output given exactly, including the spaces and new lines)

(passed with presentation error means you will get full marks)

Your last recorded submission was on 2024-07-22, 08:19 IST
Select the Language for this assignment. 
File name for this program : 
1
import java.util.Scanner;
2
3
public class W01_P3 {
4
5
  public static void main(String[] args)
6
7
  {
8
    int i, n, sum = 0;
9
      Scanner in = new Scanner(System.in);
10
      // System.out.print("Input number: ");
11
      n = in.nextInt();
12
    System.out.printf("The first %d natural numbers are : \n",n);
13
// Use loop to display n natural numbers
14
//sum the natural numbers up to n.
15
for ( i = 1; i <=n ; i++)
16
{
17
  System.out.println(i);
18
  sum +=i;
19
}
0
System.out.printf("The Sum of Natural Number upto %d terms : %d",n,sum);
1
  }
2
}
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
5
The first 5 natural numbers are : \n
1\n
2\n
3\n
4\n
5\n
The Sum of Natural Number upto 5 terms : 15
The first 5 natural numbers are : \n
1\n
2\n
3\n
4\n
5\n
The Sum of Natural Number upto 5 terms : 15
Passed





Private Test cases used for EvaluationStatus
Test Case 1
Passed



Week 01 : Programming Assignment 4

Due on 2024-08-08, 23:59 IST

Write a Java program to make such a pattern like a right angle triangle with the number increased by 1.

(Remember to match the output given exactly, including the spaces and new lines)

(Ignore presentation errors for this and all future programming assignments)
(passed with presentation error means you will get full marks)

for n=3:

2 3

4 5 6

Select the Language for this assignment. 
File name for this program : 
1
import java.util.Scanner;
2
3
public class W01_P4 {
4
5
  public static void main(String[] args)
6
7
  {
8
    int i, j, n, k = 1;
9
10
    //System.out.print("Input number of rows : ");
11
12
    Scanner in = new Scanner(System.in);
13
    n = in.nextInt();
14
//use nested for loop for printing pattern like a right angle triangle with the number increased by 1.
15
for( i = 1 ; i <= n ; i++)
16
{
17
  for( j = 1; j <= i ; j++)
18
  {
19
    System.out.print(k + " ");
20
    k++;
21
  }
22
  System.out.print("\n");
23
}
0
}
1
}
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
4
1 \n
2 3 \n
4 5 6 \n
7 8 9 10
1 \n
2 3 \n
4 5 6 \n
7 8 9 10 \n
Passed after ignoring Presentation Error





Private Test cases used for EvaluationStatus
Test Case 1
Passed



Week 01 : Programming Assignment 5

Due on 2024-08-08, 23:59 IST

Write a Java program to convert an integer number to a binary number.

Select the Language for this assignment. 
File name for this program : 
1
import java.util.Scanner;
2
3
public class W01_P5 {
4
    public static void main(String args[]) {
5
        // Declare variables to store decimal number, quotient, and an array for binary
6
        // digits
7
        int dec_num, quot, i = 1, j;
8
        int bin_num[] = new int[100];
9
10
        // Create a Scanner object to read input from the user
11
        Scanner scan = new Scanner(System.in);
12
13
        // Prompt the user to input a decimal number
14
        // System.out.print("Input a Decimal Number: ");
15
        dec_num = scan.nextInt();
16
17
        // Initialize the quotient with the decimal number
18
        quot = dec_num;
19
// Convert the decimal number to binary and store binary digits
20
for( ; quot!=0; i++){
21
  bin_num[i] = quot%2;
22
  quot/=2;
23
}
0
// Display the binary representation of the decimal number
1
        System.out.print("Binary number is: ");
2
        for (j = i - 1; j > 0; j--) {
3
            System.out.print(bin_num[j]);
4
        }
5
        //System.out.print("\n");
6
    }
7
}
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
47
Binary number is: 101111
Binary number is: 101111
Passed





Private Test cases used for EvaluationStatus
Test Case 1
Passed





Week 02 : Programming Assignment 1

Due on 2024-08-08, 23:59 IST

Complete the code segment to call the method  display() of class Former first and then call display() method of class Latter.

Your last recorded submission was on 2024-07-27, 11:52 IST
Select the Language for this assignment. 
File name for this program : 
1
// This is the class named Former
2
class Former {
3
    // This is a method in class Former
4
    public void display() {
5
        System.out.println("This is Former Class.");
6
    }
7
}
8
9
// This is the class named Latter
10
class Latter {
11
    // This is a method in class Latter
12
    public void display() {
13
        System.out.print("This is Latter Class.");
14
    }
15
}
16
17
public class W02_P1 {
18
    public static void main(String[] args) {
19
// Write your code to create objects and call methods
20
Former f = new Former();
21
f.display();
22
Latter l = new Latter();
23
l.display();
0
}
1
}
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
NA
This is Former Class.\n
This is Latter Class.
This is Former Class.\n
This is Latter Class.
Passed





Private Test cases used for EvaluationStatus
Test Case 1
Passed



Week 02 : Programming Assignment 2

Due on 2024-08-08, 23:59 IST

Create a class Student with private attributes for name and age.

Use a constructor to initialize these attributes and provide public getter methods to access them.

In the main method, an instance of Student is created and the student's details are printed.

 

Guideline to Solve:

§ Define the Student class with private attributes.

§ Use a constructor to initialize the attributes.

§ Implement getter methods for the attributes.

Follow the naming convetion used in the Fixed code.

Your last recorded submission was on 2024-07-27, 11:59 IST
Select the Language for this assignment. 
File name for this program : 
1
import java.util.Scanner;
2
class Student {
3
// Write the definition of the class here
4
// Create 2 private variables name and age
5
  String name;
6
  int age;
7
// Create a constructor 
8
  Student(String name, int age){
9
    this.name = name;
10
    this.age = age;
11
  }
12
// Create getName() and getAge() functions
13
  public String getName(){
14
    return name;
15
  }
16
  public int getAge(){
17
    return age;
18
  }
19
}
0
class W02_P2 {
1
  public static void main(String[] args) {
2
    Scanner scanner = new Scanner(System.in);
3
4
    // Read input
5
    // System.out.print("Enter name: ");
6
    String name = scanner.nextLine();
7
    // System.out.print("Enter age: ");
8
    int age = scanner.nextInt();
9
10
    // Create Student object
11
    Student student = new Student(name, age);
12
13
    // Print student details
14
    System.out.println("Student Name: " + student.getName());
15
    System.out.print("Student Age: " + student.getAge());
16
17
    scanner.close();
18
  }
19
}
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
Alice
20
Student Name: Alice\n
Student Age: 20
Student Name: Alice\n
Student Age: 20
Passed




Private Test cases used for EvaluationStatus
Test Case 1
Passed



Week 02 : Programming Assignment 3

Due on 2024-08-08, 23:59 IST

Create a class Rectangle with attributes length and width.

Provide two constructors: one with no parameters (default to 1) and

another with parameters to initialize the attributes.

Use the this keyword to avoid name space collision.

Create a getArea() function that returns the area of the rectangle.

 

Guideline to Solve:

§ Define the Rectangle class with attributes and constructors.

§ Define a default Rectangle constructor that inializes length and width to 1.

§ Use the this keyword in the parameterized constructor.

§ Define a getArea() funtion that returns the area of there rectangle

Follow the naming convetion used in the Fixed code.

Your last recorded submission was on 2024-07-27, 12:22 IST
Select the Language for this assignment. 
File name for this program : 
1
import java.util.Scanner;
2
class Rectangle {
3
// Write the definition of the class here
4
// Create 2 private variables 
5
  double length;
6
  double width;
7
// Create a default constructor 
8
  Rectangle(){
9
    length = 1;
10
    width = 1;
11
  }
12
// Create a parameterised constructor
13
  Rectangle( double length, double width){
14
    this.length = length;
15
    this.width = width;
16
  }
17
// Create getLength(), getWidth() and getArea() functions
18
  public double getLength(){
19
    return length;
20
  }
21
  public double getWidth(){
22
    return width;
23
  }
24
  public double getArea(){
25
    return length*width;
26
  }
27
}
0
class W02_P3 {
1
    public static void main(String[] args) {
2
        Scanner scanner = new Scanner(System.in);
3
4
        // Read input
5
        // System.out.print("Enter length: ");
6
        double length = scanner.nextDouble();
7
        // System.out.print("Enter width: ");
8
        double width = scanner.nextDouble();
9
10
        // Create Rectangle objects
11
        Rectangle rect1 = new Rectangle();
12
        Rectangle rect2 = new Rectangle(length, width);
13
14
        // Print rectangle dimensions
15
        System.out.print("Default Rectangle: L, W, A : ");
16
        System.out.println(rect1.getLength() + ", " + rect1.getWidth() + ", " + rect1.getArea());
17
        System.out.print("Parameterised Rectangle: L, W, A : ");
18
        System.out.print(rect2.getLength() + ", " + rect2.getWidth() + ", " + rect2.getArea());
19
20
        scanner.close();
21
    }
22
}
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
2.5 
3.5
Default Rectangle: L, W, A : 1.0, 1.0, 1.0\n
Parameterised Rectangle: L, W, A : 2.5, 3.5, 8.75
Default Rectangle: L, W, A : 1.0, 1.0, 1.0\n
Parameterised Rectangle: L, W, A : 2.5, 3.5, 8.75
Passed




Private Test cases used for EvaluationStatus
Test Case 1
Passed



Week 02 : Programming Assignment 4

Due on 2024-08-08, 23:59 IST

Create a class Circle that encapsulates the properties of a circle.

The class should have a private field for the radius, a constructor to initialize the radius, and methods to calculate the area and circumference of the circle.

NOTE: use Math.PI for PI calculations (DO NOT USE 22/7)

 

Guideline to Solve:

§ Define the Circle class with attributes and constructors.

§ Use the this keyword in the parameterized constructor.

§ Define a getArea() funtion that returns the area of there Circle (use Math.PI)

§ Define a getCircumference() funtion that returns the circumference of there Circle (use Math.PI)

Follow the naming convetion used in the Fixed code.

Select the Language for this assignment. 
File name for this program : 
1
import java.util.Scanner;
2
// Define the circle class here
3
class Circle{
4
  private double radius;
5
  
6
  Circle(double radius){
7
    this.radius = radius;
8
  }
9
  public double calculateArea(){
10
    return( Math.PI * radius * radius);
11
  }
12
  public double calculateCircumference(){
13
    return( 2 * Math.PI * radius);
14
  }
15
}
0
public class W02_P4 {
1
    public static void main(String[] args) {
2
        Scanner scanner = new Scanner(System.in);
3
        // System.out.print("Enter radius: ");
4
        double radius = scanner.nextDouble();
5
6
        // Create circle object
7
        Circle circle = new Circle(radius);
8
9
        // Calculate and print area
10
        double area = circle.calculateArea();
11
        // Print area to 2 decimal places
12
        System.out.printf("Area: %.2f\n", area);
13
14
        // Calculate and print circumference
15
        double circumference = circle.calculateCircumference();
16
        // Print circumference to 2 decimal places
17
        System.out.printf("Circumference: %.2f", circumference);
18
        scanner.close();
19
    }
20
}
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
5.0
Area: 78.54\n
Circumference: 31.42
Area: 78.54\n
Circumference: 31.42
Passed




Private Test cases used for EvaluationStatus
Test Case 1
Passed



Week 02 : Programming Assignment 5

Due on 2024-08-08, 23:59 IST

Complete the code by creating the constructor and the getter functions for a class Dog as defined below.

Select the Language for this assignment. 
File name for this program : 
1
import java.util.Scanner;
2
3
// Class Declaration
4
public class Dog {
5
    // Instance Variables
6
    private String name;
7
    private String breed;
8
    private int age;
9
    private String color;
10
// Create the constructor
11
Dog( String name, String breed, int age, String color){
12
  this.name = name;
13
  this.breed = breed;
14
  this.age = age;
15
  this.color = color;
16
}
17
// Create the getter functions
18
public String getName(){
19
  return name;
20
}
21
public String getBreed(){
22
  return breed;
23
}
24
public int getAge(){
25
  return age;
26
}
27
public String getColor(){
28
  return color;
29
}
0
public static void main(String[] args) {
1
        Scanner scanner = new Scanner(System.in);
2
        
3
        String name = scanner.nextLine();
4
        String breed = scanner.nextLine();
5
        int age = scanner.nextInt();
6
        String color = scanner.next();
7
        
8
        Dog tommy = new Dog(name, breed, age, color);
9
        
10
        System.out.println("Hi my name is: " + tommy.getName());
11
        System.out.println("My breed is: " + tommy.getBreed());
12
        System.out.println("My age is: " + tommy.getAge());
13
        System.out.print("My color is: " + tommy.getColor());
14
        
15
        scanner.close();
16
    }
17
}
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
Tommy
German Shepard
2
Black
Hi my name is: Tommy\n
My breed is: German Shepard\n
My age is: 2\n
My color is: Black
Hi my name is: Tommy\n
My breed is: German Shepard\n
My age is: 2\n
My color is: Black
Passed




Private Test cases used for EvaluationStatus
Test Case 1
Passed




Week 03 : Programming Assignment 1

Due on 2024-08-15, 23:59 IST

Create a class Department having a method getCourses that prints "These are the department's courses". It will have two subclasses, ComputerScience and MechanicalEngineering, each having a method with the same name that prints specific courses for the respective departments.Call the method by creating an object of each of the three classes.

(Remember to match the output given exactly, including the spaces and new lines)

(passed with presentation error means you will get full marks)

Select the Language for this assignment. 
File name for this program : 
1
class Department {
2
  public void getCourses() {
3
    System.out.println("These are the department's courses");
4
  }
5
}
6
// Create two subclasses, ComputerScience and MechanicalEngineering, each having a method with the same name getCourse() that prints specific courses for the respective departments.
7
class ComputerScience extends Department{
8
  public void getCourses() {
9
    System.out.println("Courses: Data Structures, Algorithms, Operating Systems");
10
  }
11
}
12
13
class MechanicalEngineering extends Department{
14
  public void getCourses() {
15
    System.out.println("Courses: Thermodynamics, Fluid Mechanics, Heat Transfer");
16
  }
17
}
0
class W03_P1 {
1
  public static void main(String[] args) {
2
    ComputerScience cs = new ComputerScience();
3
    MechanicalEngineering me = new MechanicalEngineering();
4
    cs.getCourses();
5
    me.getCourses();
6
  }
7
}
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
NA
Courses: Data Structures, Algorithms, Operating Systems\n
Courses: Thermodynamics, Fluid Mechanics, Heat Transfer
Courses: Data Structures, Algorithms, Operating Systems\n
Courses: Thermodynamics, Fluid Mechanics, Heat Transfer\n
Passed after ignoring Presentation Error





Private Test cases used for EvaluationStatus
Test Case 1
Passed



Week 03 : Programming Assignment 2

Due on 2024-08-15, 23:59 IST

There are two class cls1 and cls2 which is subclass of cls1.  cls1 having a method "add" which add two numbers. Create two method inside cls2 which will take 2 parameters as input i.e. a and b and print the sum , multiplication and sum of their squares i.e (a^2) + (b2).

(Remember to match the output given exactly, including the spaces and new lines)

(passed with presentation error means you will get full marks)

Select the Language for this assignment. 
File name for this program : 
1
import java.util.Scanner;
2
class cls1
3
{
4
    void add(int p,int q)
5
    {
6
        System.out.println(p+q);
7
    }
8
}
9
//Create subclass cls2 of cls1 which perform task of multiplication and sum of squares of passing two parameters.
10
class cls2 extends cls1{
11
  void mul(int p,int q)
12
    {
13
        System.out.println(p*q);
14
    }
15
  void task(int p,int q)
16
    {
17
        add(p*p,q*q);
18
    }
19
}
0
public class W03_P2{
1
    public static void main(String args[])
2
    {
3
        Scanner sc=new Scanner(System.in);
4
    
5
        cls2 obj=new cls2();
6
        int a=sc.nextInt();
7
        int b=sc.nextInt();
8
        //String tilde=sc.next();
9
        obj.add(a,b);
10
        obj.mul(a,b);
11
        obj.task(a,b);
12
    
13
    }
14
}
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
2
4
6\n
8\n
20
6\n
8\n
20\n
Passed after ignoring Presentation Error





Private Test cases used for EvaluationStatus
Test Case 1
Passed



Week 03 : Programming Assignment 3

Due on 2024-08-15, 23:59 IST

Write a program to print the factorial of a number by defining a recursive method named 'Factorial'.

Factorial of any number n is represented by n! and is equal to 1*2*3*....*(n-1)*n. E.g.-

4! = 1*2*3*4 = 24

3! = 3*2*1 = 6

2! = 2*1 = 2

Also,

1! = 1

0! = 0

Select the Language for this assignment. 
File name for this program : 
1
import java.util.Scanner;
2
class W03_P3{
3
//Create recursive method to find factorial of a number
4
5
static long factorial(int x){
6
  if(x == 0 || x == 1 )
7
    return 1;
8
  else 
9
    return x * factorial(x -1);
10
}
0
public static void main(String[] args) {
1
        Scanner in = new Scanner(System.in);
2
        int x;
3
        x = in.nextInt();
4
        System.out.print(factorial(x));   
5
  }
6
}
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
5
120
120
Passed





Private Test cases used for EvaluationStatus
Test Case 1
Passed


Week 03 : Programming Assignment 4

Due on 2024-08-15, 23:59 IST

Write a program to take integer inputs from user until he/she presses q ( Ask to press q to quit after every integer input ). Print average and product of all numbers.

(Remember to match the output given exactly, including the spaces and new lines)

(passed with presentation error means you will get full marks)

Your last recorded submission was on 2024-08-06, 12:39 IST
Select the Language for this assignment. 
File name for this program : 
1
import java.util.*;
2
3
public class W03_P4{
4
public static void main(String[] args) {
5
6
String choice = "";
7
Scanner input = new Scanner(System.in);
8
// Add your code
9
int x;
10
int product = 1;
11
float avg = 0;
12
int count = 0;
13
do{
14
  if(input.hasNextInt()) {
15
    x = input.nextInt();
16
    product*=x;
17
    avg +=x;
18
    count++;
19
  }
20
  else
21
    choice="q";
22
}while(choice!="q");
23
System.out.println("Product is: " + product);
24
System.out.print("Average is: " + avg/count);
0
}
1
}
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
2
4
5
6
8
1
q
Product is: 1920\n
Average is: 4.3333335
Product is: 1920\n
Average is: 4.3333335
Passed





Private Test cases used for EvaluationStatus
Test Case 1
Passed



Week 03 : Programming Assignment 5

Due on 2024-08-15, 23:59 IST

Write a Java program to create a class called Employee with methods called work() and getSalary(). Create a subclass called HRManager that overrides the work() method and adds a new method called addEmployee().

(Remember to match the output given exactly, including the spaces and new lines)

(passed with presentation error means you will get full marks)

Your last recorded submission was on 2024-08-06, 13:20 IST
Select the Language for this assignment. 
File name for this program : 
1
class Employee {
2
    private final int salary;
3
4
    public Employee(int salary) {
5
        this.salary = salary;
6
    }
7
8
    public void work() {
9
        System.out.println("working as an employee!");
10
    }
11
12
    public int getSalary() {
13
        return salary;
14
    }
15
}
16
// Create a subclass called HRManager that overrides the work() method and adds a new method called addEmployee().
17
class HRManager extends Employee{
18
  public HRManager(int salary) {
19
        super(salary);
20
    }
21
  public void work() {
22
        System.out.println("\nManaging employees");
23
    }
24
  public void addEmployee() {
25
        System.out.print("\nAdding new employee!");
26
    }
27
}
0
class W03_P5 {
1
    public static void main(String[] args) {
2
        Employee emp = new Employee(40000);
3
        HRManager mgr = new HRManager(70000);
4
5
        emp.work();
6
        System.out.println("Employee salary: " + emp.getSalary());
7
8
        mgr.work();
9
        System.out.println("Manager salary: " + mgr.getSalary());
10
        mgr.addEmployee();
11
    }
12
}
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
NA
working as an employee!\n
Employee salary: 40000\n
\n
Managing employees\n
Manager salary: 70000\n
\n
Adding new employee!
working as an employee!\n
Employee salary: 40000\n
\n
Managing employees\n
Manager salary: 70000\n
\n
Adding new employee!
Passed





Private Test cases used for EvaluationStatus
Test Case 1
Passed




Week 04 : Programming Assignment 1

Due on 2024-08-22, 23:59 IST

Complete the code segment to swap two numbers using call by object reference.

Your last recorded submission was on 2024-08-13, 08:27 IST
Select the Language for this assignment. 
File name for this program : 
1
//Prefixed Fixed code
2
import java.util.Scanner;
3
class Question {   //Define a class Question with two elements e1 and e2.
4
  Scanner sc = new Scanner(System.in);
5
int e1 = sc.nextInt();  //Read e1
6
int e2 = sc.nextInt();  //Read e2
7
}
8
public class W04_P1 {
9
// Define static method swap()to swap the values of e1 and e2 of class Question.
10
public static void swap(Question t){
11
  int temp = t.e1;
12
    t.e1 = t.e2;
13
    t.e2 = temp;
14
}
0
public static void main(String[] args) {
1
    Question t = new Question();
2
    System.out.println("Before Swap: " + t.e1 + " " + t.e2);
3
    swap(t);
4
    System.out.print("After Swap: " + t.e1 + " " + t.e2);
5
  }
6
}
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
5 10
Before Swap: 5 10\n
After Swap: 10 5
Before Swap: 5 10\n
After Swap: 10 5
Passed



Week 04 : Programming Assignment 2

Due on 2024-08-22, 23:59 IST

1 - Problem Statement:      

Define a class Point with members

§ private double x;

§ private double y;

and methods:

§ public Point(double x, double y){}  // Constructor to create a new point?

§ public double slope(Point p2){} // Function to return the slope of the line formed from current Point and another Point
(Assume that input will always be chosen so that slope will never be infinite)

Your last recorded submission was on 2024-08-13, 08:46 IST
Select the Language for this assignment. 
File name for this program : 
1
import java.util.Scanner;
2
//Complete the code segment to define a class Point with parameter x,y and method skope() for calculating slope between two points.
3
// Note: Pass objectsof type class Point as argument in slope() method.
4
class Point{
5
  private double x;
6
  private double y;
7
  
8
  public Point(double x, double y){
9
    this.x = x;
10
    this.y = y;
11
  }
12
  public double slope(Point p2){
13
    return ((this.y - p2.y) / (this.x - p2.x));
14
  }
15
}
0
public class W04_P2{         
1
   public static void main(String[] args) {
2
        Scanner sc = new Scanner(System.in);
3
        double x1 = sc.nextDouble();
4
        double y1 = sc.nextDouble();
5
        double x2 = sc.nextDouble();
6
        double y2 = sc.nextDouble();
7
        Point p1 = new Point(x1, y1);
8
        Point p2 = new Point(x2, y2);
9
        
10
        System.out.print("Slope: "+p1.slope(p2));
11
    }
12
}
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
0 0
1 1
Slope: 1.0
Slope: 1.0
Passed


Week 04 : Programming Assignment 3

Due on 2024-08-22, 23:59 IST

This program to exercise the create static and non-static methods. A partial code is given, you have to define two methods, namely sum( ) and multiply( ). These methods have been called to find the sum and product of two numbers. Complete the code segment as instructed.  

Select the Language for this assignment. 
File name for this program : 
1
import java.util.Scanner;
2
3
class QuestionScope {
4
//Create the method sum() to find the sum of two numbers.
5
//Create the static method multiply() to find the product of two numbers.
6
public int sum(int n1, int n2) {
7
  return n1+n2;
8
}
9
public static int multiply(int n1, int n2) {
10
  return n1*n2;
11
}
0
}
1
2
public class W04_P3 {
3
    public static void main(String[] args) {
4
        Scanner sc = new Scanner(System.in);
5
        int n1 = sc.nextInt();
6
        int n2 = sc.nextInt();
7
        int sum = 0, prod = 0;
8
        QuestionScope st = new QuestionScope(); // Create an object to call non-
9
                                                // static method
10
        sum = st.sum(n1, n2); // Call the method
11
        prod = QuestionScope.multiply(n1, n2);  // Create an object to call
12
                                                 // static method
13
        System.out.println("Sum: "+sum);
14
        System.out.print("Product: "+prod);
15
        sc.close();
16
    }
17
}
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
5 10
Sum: 15\n
Product: 50
Sum: 15\n
Product: 50
Passed



Week 04 : Programming Assignment 4

Due on 2024-08-22, 23:59 IST

The program in this assignment is attempted to print the following output:

 

-----------------OUTPUT-------------------

This is large

This is medium

This is small

This is extra-large

-------------------------------------------------

 

However, the code is intentionally with some bugs in it. Debug the code to execute the program successfully.

Select the Language for this assignment. 
File name for this program : 
1
interface ExtraLarge{
2
    String extra = "This is extra-large";
3
    //public static void display(); //commented function declaration
4
}
5
6
class Large {
7
    public void Print() {
8
        System.out.println("This is large"); //semi-colon here
9
    }
10
}
11
 
12
class Medium extends Large {
13
    public void Print() {
14
          super.Print();  //removed 'super.' from here
15
        System.out.println("This is medium");
16
    }
17
}
18
class Small extends Medium {
19
    public void Print() {
20
        super.Print(); //removed semi-colon from here
21
        System.out.println("This is small");
22
    //removed a curly bracket from here
23
  }
24
}
0
class W04_P4 implements ExtraLarge{
1
    public static void main(String[] args) {
2
        Small s = new Small();
3
        s.Print();
4
        W04_P4 q = new W04_P4();
5
        q.display();
6
    }
7
    public void display(){
8
        System.out.print(extra);
9
    }
10
}
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
NA
This is large\n
This is medium\n
This is small\n
This is extra-large
This is large\n
This is medium\n
This is small\n
This is extra-large
Passed



Week 04 : Programming Assignment 5

Due on 2024-08-22, 23:59 IST

Consider First n even numbers starting from zero(0).Complete the code segment to calculate sum of  all the numbers divisible by 3 from 0 to n. Print the sum.
Example:

 

Input: n = 5

 

-------

0 2 4 6 8

Even number divisible by 3:0 6

sum:6

Select the Language for this assignment. 
File name for this program : 
1
// Prefixed Fixed Code:
2
import java.util.Scanner;
3
4
public class W04_P5 {
5
    public static void main(String[] args) {
6
        Scanner sc = new Scanner(System.in);
7
        int n = sc.nextInt();
8
        int sum = 0;
9
// Use for or while loop to sum first n positive even numbers starting from 0 which are
10
// divisible by 3.
11
for(int i=0; i<2*n; i=i+2)
12
  if(i%3==0)
13
    sum+=i;
0
System.out.print("Sum: "+sum);// Suffixed Fixed Code:
1
        sc.close();
2
    }
3
}
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
6
Sum: 6
Sum: 6
Passed



Week 05 : Programming Assignment 1

Due on 2024-08-29, 23:59 IST
Write a program to create a method that takes an integer as a parameter and throws an exception if the number is odd.
Your last recorded submission was on 2024-08-17, 23:41 IST
Select the Language for this assignment. 
File name for this program : 
1
import java.util.*;
2
3
class IllegalArgumentException extends Exception {
4
  public IllegalArgumentException(String message) {
5
    super(message);
6
  }
7
}
8
9
public class W05_P1 {
10
    public static void main(String[] args) {
11
     // int n = 18;
12
      Scanner input = new Scanner(System.in);
13
      int n=input.nextInt();
14
      trynumber(n);
15
    }
16
// write a function to check an integer as a parameter and throws an exception if the number is odd
17
public static void trynumber(int n){
18
  try {
19
      checkEvenNumber(n);
20
    } catch (IllegalArgumentException e) {
21
      System.out.print(e.getMessage());
22
    }
23
}
24
25
26
public static void checkEvenNumber(int number) throws IllegalArgumentException {
27
  if ( number % 2 == 1)
28
    throw new IllegalArgumentException("Error: " + number + " is odd.");
29
  else
30
    System.out.print(number + " is even.");
31
}
0
}
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
7
Error: 7 is odd.
Error: 7 is odd.
Passed
Test Case 2
8
8 is even.
8 is even.
Passed





Private Test cases used for EvaluationStatus
Test Case 1
Passed


Week 05 : Programming Assignment 2

Due on 2024-08-29, 23:59 IST

Write a program to create an interface Searchable with a method search(String keyword) that searches for a given keyword in a text document.
Create two classes Document and WebPage that implement the Searchable interface and provide their own implementations of the search() method.

Your last recorded submission was on 2024-08-18, 00:07 IST
Select the Language for this assignment. 
File name for this program : 
1
import java.util.Scanner;
2
interface Searchable {
3
    // Declare the abstract method "search" that classes implementing this interface must provide
4
    boolean search(String keyword);
5
}
6
// Declare the Document class and WebPage class, which implements the Searchable interface
7
class Document implements Searchable{
8
  public boolean search(String keyword){
9
    return true; // dummy statement
10
  }
11
}
12
13
class WebPage implements Searchable{
14
  
15
  String url;
16
  String title;
17
  
18
  WebPage(String url, String title){
19
    this.url = url;
20
    this.title = title;
21
  }
22
  public boolean search(String keyword){
23
    return title.contains(keyword);
24
  }
25
}
0
public class W05_P2 {
1
    public static void main(String[] args) {
2
        // Create an instance of the Document class with a sample content
3
   Scanner in = new Scanner(System.in);
4
        String text = in.nextLine();
5
        String document = text;
6
        String str = in.nextLine();
7
8
        // Search for a keyword in the document and store the result
9
        boolean documentContainsKeyword = document.contains(str);
10
11
        // Print whether the document contains the keyword
12
System.out.println("Document contains keyword: " +str+ " "+documentContainsKeyword);
13
// Create an instance of the WebPage class with a sample URL and HTML content
14
        WebPage webPage = new WebPage("https://onlinecourses.nptel.ac.in", "This is a NPTEL online course webpage.");
15
16
        // Search for a keyword in the webpage and store the result
17
        boolean webPageContainsKeyword = webPage.search("webpage");
18
19
        // Print whether the webpage contains the keyword
20
        System.out.print("Webpage contains keyword 'webpage': " + webPageContainsKeyword);
21
    }
22
}
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
You are a hard working person.
student
Document contains keyword: student false\n
Webpage contains keyword 'webpage': true
Document contains keyword: student false\n
Webpage contains keyword 'webpage': true
Passed





Private Test cases used for EvaluationStatus
Test Case 1
Passed


Week 05 : Programming Assignment 3

Due on 2024-08-29, 23:59 IST
Write a  program to create a method that takes a string as input and throws an exception if the string does not contain vowels.
(Note: Check both upper and lower case vowels)
Your last recorded submission was on 2024-08-18, 00:24 IST
Select the Language for this assignment. 
File name for this program : 
1
import java.util.Scanner;
2
3
class NoVowelsException extends Exception {
4
  public NoVowelsException(String message) {
5
    super(message);
6
  }
7
}
8
9
public class W05_P3 {
10
    public static void main(String[] args) {
11
      Scanner input = new Scanner(System.in);
12
      try {
13
        String text = input.nextLine();
14
15
        System.out.println("Original string: " + text);
16
        checkVowels(text);
17
        System.out.print("String contains vowels.");
18
      } catch (NoVowelsException e) {
19
        System.out.print("Error: " + e.getMessage());
20
      }
21
    }
22
// create a method that takes a string as input and throws an exception if the string does not contain vowels.
23
public static void checkVowels(String a) throws NoVowelsException {
24
  boolean flag = false;
25
  for ( int i = 0 ; i < a.length() ; i++){
26
        char c = a.charAt(i);
27
        if ( c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' || 
28
            c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U')
29
          flag = true;
30
      }
31
  if ( flag == false )
32
    throw new NoVowelsException("String does not contain any vowels.");
33
}
0
}
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
Fly by my crypt
Original string: Fly by my crypt\n
Error: String does not contain any vowels.
Original string: Fly by my crypt\n
Error: String does not contain any vowels.
Passed





Private Test cases used for EvaluationStatus
Test Case 1
Passed



Week 05 : Programming Assignment 4

Due on 2024-08-29, 23:59 IST
Write a  program to create an interface Flyable with a method called fly_obj().
Create three classes Spacecraft, Airplane, and Helicopter that implement the Flyable interface.
Implement the fly_obj() method for each of the three classes.

(Remember to match the output given exactly, including the spaces and new lines)

(passed with presentation error means you will get full marks)


Your last recorded submission was on 2024-08-18, 00:30 IST
Select the Language for this assignment. 
File name for this program : 
1
interface Flyable {
2
    // Declare the abstract method "fly_obj" that classes implementing this interface must provide
3
    void fly_obj();
4
}
5
// Declare the Spacecraft class, Airplane class, Helicopter class which implements the Flyable interface
6
// Implement the "fly_obj" method required by the Flyable interface
7
class Spacecraft implements Flyable{
8
  public void fly_obj(){
9
    System.out.println("Spacecraft is flying");
10
  }
11
}
12
class Airplane implements Flyable{
13
  public void fly_obj(){
14
    System.out.println("Airplane is flying");
15
  }
16
}
17
class Helicopter implements Flyable{
18
  public void fly_obj(){
19
    System.out.println("Helicopter is flying");
20
  }
21
}
0
public class W05_P4 {
1
    public static void main(String[] args) {
2
        // Create an array of Flyable objects, including a Spacecraft, Airplane, and Helicopter
3
        Flyable[] flyingObjects = {new Spacecraft(), new Airplane(), new Helicopter()};
4
5
        // Iterate through the array and call the "fly_obj" method on each object
6
        for (Flyable obj : flyingObjects) {
7
            obj.fly_obj();
8
        }
9
    }
10
}
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
NA
Spacecraft is flying\n
Airplane is flying\n
Helicopter is flying
Spacecraft is flying\n
Airplane is flying\n
Helicopter is flying\n
Passed after ignoring Presentation Error





Private Test cases used for EvaluationStatus
Test Case 1
Passed


Week 05 : Programming Assignment 5

Due on 2024-08-29, 23:59 IST
Write a program to create an interface Playable with a method play() that takes no arguments and returns void.
Create three classes Football, Volleyball, and Basketball that implement the Playable interface and override the play() method to play the respective sports.

(Remember to match the output given exactly, including the spaces and new lines)
(passed with presentation error means you will get full marks)
Select the Language for this assignment. 
File name for this program : 
1
interface Playable {
2
    // Declare the abstract method "play" that classes implementing this interface must provide
3
    void play();
4
}
5
// Declare the Volleyball, Basketball, Football class, which implements the Playable interface
6
class Volleyball implements Playable{
7
  public void play(){
8
    System.out.println("Playing volleyball");
9
  }
10
}
11
class Basketball implements Playable{
12
  public void play(){
13
    System.out.println("Playing basketball");
14
  }
15
}
16
class Football implements Playable{
17
  public void play(){
18
    System.out.println("Playing football");
19
  }
20
}
0
public class W05_P5 {
1
    public static void main(String[] args) {
2
        // Create instances of Playable objects for football, volleyball, and basketball
3
        Playable football = new Football();
4
        Playable volleyball = new Volleyball();
5
        Playable basketball = new Basketball();
6
7
        // Call the "play" method on each Playable object to play different sports
8
        football.play();
9
        volleyball.play();
10
        basketball.play();
11
    }
12
}
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
NA
Playing football\n
Playing volleyball\n
Playing basketball
Playing football\n
Playing volleyball\n
Playing basketball\n
Passed after ignoring Presentation Error





Private Test cases used for EvaluationStatus
Test Case 1
Passed





Week 06 : Programming Assignment 1

Due on 2024-09-05, 23:59 IST
An interface Number is defined in the following program. 
You have to declare a class A, which will implement the interface Number.
Note that the method findSqr(n) will return the square of the number n.
Your last recorded submission was on 2024-08-26, 17:49 IST
Select the Language for this assignment. 
File name for this program : 
1
import java.util.Scanner;
2
3
interface Number {
4
    int findSqr(int i);  // Returns the square of n
5
}
6
//Create a class A which implements the interface Number.
7
class A implements Number{
8
  public int findSqr(int i){
9
    return i*i;
10
  }
11
}
0
public class W06_P1{ 
1
        public static void main (String[] args){ 
2
          A a = new A();   //Create an object of class A
3
           // Read a number from the keyboard
4
           Scanner sc = new Scanner(System.in);  
5
           int i = sc.nextInt();
6
           System.out.print(a.findSqr(i)); 
7
    } 
8
}
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
12
144
144
Passed




Week 06 : Programming Assignment 2

Due on 2024-09-05, 23:59 IST
This program is to find the GCD (greatest common divisor) of two integers writing a recursive function findGCD(n1,n2).
Your function should return -1, if the argument(s) is(are) negative number(s).
Your last recorded submission was on 2024-08-26, 18:10 IST
Select the Language for this assignment. 
File name for this program : 
1
import java.util.Scanner;
2
3
interface GCD {
4
    public int findGCD(int n1,int n2);
5
}
6
//Create a class B, which implements the interface GCD
7
class B implements GCD{
8
  public int findGCD(int n1,int n2){
9
    if ( n1 < 0 || n2 < 0 )
10
      return(-1);
11
    else if ( n2 == 0 )
12
      return n1;
13
    else if ( n1 > n2 )
14
      return findGCD(n2,n1%n2);
15
    else
16
      return findGCD(n1,n2%n1);
17
      }
18
}
0
public class W06_P2{ 
1
        public static void main (String[] args){ 
2
          B a = new B();   //Create an object of class B
3
            // Read two numbers from the keyboard
4
            Scanner sc = new Scanner(System.in);  
5
            int p1 = sc.nextInt();
6
           int p2 = sc.nextInt();
7
            System.out.print(a.findGCD(p1,p2)); 
8
    } 
9
}
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
20 30
10
10
Passed



Week 06 : Programming Assignment 3

Due on 2024-09-05, 23:59 IST
Complete the code segment to print the following using the concept of extending the Thread class in Java:
-----------------OUTPUT-------------------
Thread is Running.
-------------------------------------------------
Your last recorded submission was on 2024-08-26, 18:15 IST
Select the Language for this assignment. 
File name for this program : 
1
// Write the appropriate code to extend the Thread class to complete the class W06_P3.
2
class W06_P3 extends Thread{
3
  public void run(){
4
        System.out.print("Thread is Running.");
5
    }
0
public static void main(String args[]){  
1
2
        // Creating object of thread class
3
        W06_P3 thread=new W06_P3();  
4
5
                // Start the thread
6
        thread.start();
7
    }  
8
}
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   



Private Test cases used for EvaluationStatus
Test Case 1
Passed



Week 06 : Programming Assignment 4

Due on 2024-09-05, 23:59 IST
Execution of two or more threads occurs in a random order. The keyword 'synchronized' in Java is used to control the execution of thread in a strict sequence. In the following, the program is expected to print some numbers. Do the necessary use of 'synchronized' keyword, so that, the program prints the output in the following order:  
-----------------OUTPUT------------------- (this line should not to be printed)
5
10
15
20
25
100
200
300
400
500
-------------------------------------------------(this line should not to be printed)


(Remember to match the output given exactly, including the spaces and new lines)
(passed with presentation error means you will get full marks)
Your last recorded submission was on 2024-08-26, 18:18 IST
Select the Language for this assignment. 
File name for this program : 
1
class Execute{
2
// fix the code below to get the desired output
3
synchronized void print(int n){
4
   for(int i=1;i<=5;i++){  
5
     System.out.println(n*i);  
6
     try{  
7
      Thread.sleep(400);  
8
     }catch(Exception e){
9
        System.out.println(e);
10
     }  
11
   }
12
 }
0
} // Ending Execute class
1
2
class Thread1 extends Thread{  
3
    Execute t;  
4
    Thread1(Execute t){  
5
        this.t=t;  
6
    }  
7
    public void run(){  
8
        t.print(5);  
9
    } 
10
}  
11
12
class Thread2 extends Thread{  
13
    Execute t;  
14
    Thread2(Execute t){  
15
        this.t=t;  
16
    }  
17
    public void run(){  
18
        t.print(100);  
19
    }  
20
}  
21
  
22
public class W06_P4{  
23
    public static void main(String args[]){  
24
        Execute obj = new Execute();//only one object  
25
        Thread1 t1=new Thread1(obj);  
26
        Thread2 t2=new Thread2(obj);  
27
        t1.start();  
28
        t2.start();  
29
    }  
30
}
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   



Private Test cases used for EvaluationStatus
Test Case 1
Passed



Week 06 : Programming Assignment 5

Due on 2024-09-05, 23:59 IST
Add necessary codes to print the following:

-----------------OUTPUT-------------------
Name of thread 't':Thread-0
New name of thread 't':NPTEL
Thread is running.
-------------------------------------------------
Hint: Use the setName() function
Your last recorded submission was on 2024-08-26, 18:21 IST
Select the Language for this assignment. 
File name for this program : 
1
class W06_P5 extends Thread{  
2
  public void run(){  
3
    System.out.print("Thread is running.");  
4
  }  
5
 public static void main(String args[]){  
6
    W06_P5 t=new W06_P5();  
7
    System.out.println("Name of thread 't':"+ t.getName());
8
// Write the necessary code below...
9
t.setName("NPTEL");
10
t.start();
0
System.out.println("New name of thread 't':"+ t.getName());  
1
 }  
2
}
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   



Private Test cases used for EvaluationStatus
Test Case 1
Passed





Week 07 : Programming Assignment 1

Due on 2024-09-12, 23:59 IST
Write a Java program to find longest word in given input.
Select the Language for this assignment. 
File name for this program : 
1
import java.util.Scanner;
2
3
public class W07_P1 {
4
//code for print the longest word.
5
public static String findLongestWord(String text) {
6
  String longest = "";
7
  String[] arrOfStr = text.split(" ");
8
  for (String a : arrOfStr)
9
      if ( a.length() >= longest.length() )
10
        longest = a;
11
  return longest;
12
}
0
public static void main(String[] args) {
1
        Scanner scanner = new Scanner(System.in);
2
3
        // Prompt user to enter text
4
       // System.out.println("Enter some text:");
5
        String text = scanner.nextLine();
6
7
        // Close the scanner
8
        scanner.close();
9
10
        // Call the method to find the longest word
11
        String longestWord = findLongestWord(text);
12
13
        // Print the longest word found
14
        System.out.print("The longest word in the text is: " + longestWord);
15
    }
16
}
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
Believe in yourself
The longest word in the text is: yourself
The longest word in the text is: yourself
Passed



Week 07 : Programming Assignment 2

Due on 2024-09-12, 23:59 IST

Write a program to print Swastika Pattern in Java. 

Input is 2 numbers. 

R

(Rows and Columns)

 

For Example:

 

Input:

5

5

 

Output:

* ***

* *

*****

  * *

*** *

 

NOTE: Do not print any spaces between the ‘*’

Output should match exactly as specified by the question

(Remember to match the output given exactly, including the spaces and new lines)

(passed with presentation error means you will get full marks)


Your last recorded submission was on 2024-09-01, 14:00 IST
Select the Language for this assignment. 
File name for this program : 
1
import java.util.Scanner;  
2
class W07_P2  
3
{  
4
    // main() method start  
5
    public static void main (String[] args)  
6
    {  
7
        int rows, cols;  
8
        Scanner sc = new Scanner(System.in);  
9
     //   System.out.println("Please enter odd numbers for rows and colums to get perfect Swastika.");  
10
       // System.out.println("Enter total rows");  
11
        rows = sc.nextInt();  
12
       //System.out.println("Enter total colums");  
13
        cols = sc.nextInt();  
14
          
15
        // close Scanner class  
16
        sc.close();  
17
          
18
        // call swastika() method that will design Swastika for the specified rows and cols  
19
        swastika(rows, cols);  
20
    }  
21
static void swastika(int rows, int cols)  
22
{
23
// program to print Swastika Pattern in Java.
24
// NOTE: Do not print any spaces between the '*'
25
// Output should match exactly as specified by the question
26
int rmid = rows/2 +1;
27
int cmid = cols/2 +1;
28
for ( int i = 1; i <= rows ; i++)
29
{
30
  for ( int j = 1; j <= cols ; j++ )
31
  {
32
    if ( i == rmid )
33
      System.out.print("*");
34
    else if ( j == cmid )
35
      System.out.print("*");
36
    else if ( j == 1 && i < rmid || j == cols && i > rmid)
37
      System.out.print("*");
38
    else if ( i == 1 && j > cmid || i == rows && j < cmid )
39
      System.out.print("*");
40
    else if ( i > 1 && i < rmid && j > cmid )
41
      continue;
42
    else
43
      System.out.print(" ");
44
  }
45
  System.out.print("\n");
0
}
1
}
2
}
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
7
9
*   *****\n
*   *\n
*   *\n
*********\n
    *   *\n
    *   *\n
*****   *
*   *****\n
*   *\n
*   *\n
*********\n
    *   *\n
    *   *\n
*****   *\n
Passed after ignoring Presentation Error



Week 07 : Programming Assignment 3

Due on 2024-09-12, 23:59 IST

Write a program to remove all occurrences of an element from array in Java.

Your last recorded submission was on 2024-09-01, 13:39 IST
Select the Language for this assignment. 
File name for this program : 
1
import java.util.*;
2
3
public class W07_P3 {
4
5
    public static void main(String[] args) {
6
        Scanner scanner = new Scanner(System.in);
7
            // Input array
8
      //  System.out.print("Enter the number of elements in the array: ");
9
        int n = scanner.nextInt();
10
        int[] array = new int[n];
11
12
       // System.out.println("Enter the elements of the array:");
13
        for (int i = 0; i < n; i++) {
14
            array[i] = scanner.nextInt();
15
        }
16
17
        // Element to remove
18
    //    System.out.print("Enter the element to remove: ");
19
        int elementToRemove = scanner.nextInt();
20
21
        // Close the scanner
22
        scanner.close();
23
24
        // Removing element and printing result
25
        System.out.println("Original Array: " + Arrays.toString(array));
26
        array = removeAll(array, elementToRemove);
27
        System.out.print("Array after removing " + elementToRemove + ": " + Arrays.toString(array));
28
    }
29
// program to remove all occurrences of an element from array in Java.
30
static int[] removeAll(int[] arr, int elementToRemove){
31
  int count = 0;
32
  for(int i=0; i<arr.length; i++)
33
    if(arr[i]==elementToRemove)
34
      count++;
35
  int new_arr[] = new int[arr.length-count];
36
  int j = 0;
37
  for(int i=0; i<arr.length; i++)
38
    if(arr[i]!=elementToRemove)
39
      new_arr[j++] = arr[i];
40
  return new_arr;
41
  }
0
}
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
5
12 23 34 23 45  
23
Original Array: [12, 23, 34, 23, 45]\n
Array after removing 23: [12, 34, 45]
Original Array: [12, 23, 34, 23, 45]\n
Array after removing 23: [12, 34, 45]
Passed



Week 07 : Programming Assignment 4

Due on 2024-09-12, 23:59 IST

Write a program to compute the sum of all prime numbers in a given range.
The range value will be positive.

Follow the naming convention as given in the main method of the suffix code.

Your last recorded submission was on 2024-09-01, 13:10 IST
Select the Language for this assignment. 
File name for this program : 
1
import java.util.Scanner;
2
3
public class W07_P4{
4
//Code to create function primesum(), compute the sum of all prime numbers in a given range.
5
public static int primeSum(int x, int y){
6
  int sum = 0;
7
  for(int n=x;n<=y;n++){
8
    int r = 1;
9
    for(int i=n/2;i>1;i--){
10
      r=n%i;
11
      if(r==0)
12
        break;
13
    }
14
    if(r!=0)
15
      sum+=n;
16
  }
17
  return sum;
18
}
0
public static void main(String[] args)
1
    {
2
       Scanner sc = new Scanner(System.in);
3
       int x=sc.nextInt();
4
       int y=sc.nextInt();
5
        
6
        System.out.print(primeSum(x, y));
7
    }
8
}
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
4
13
36
36
Passed



Week 07 : Programming Assignment 5

Due on 2024-09-12, 23:59 IST

Code to create two threads, one printing even numbers and the other printing odd numbers.

§ The PrintNumbers class is declared, and it implements the Runnable interface. This interface is part of Java's concurrency support and is used to represent a task that can be executed concurrently by a thread.

§ Create a constructor of this class that takes two private instance variables (start and end) to represent the range of numbers that will be printed by the thread.

§ Create a run method that is required by the Runnable interface and contains the code that will be executed when the thread is started. In this case, it should prints odd numbers within the specified range (start to end) using a for loop.

§ Hint: Thread.currentThread().getName() returns the name of the currently executing thread, which is useful for identifying which thread is printing the numbers.

Follow the naming convention as given in the main method of the suffix code.

(Remember to match the output given exactly, including the spaces and new lines)

(passed with presentation error means you will get full marks)

Select the Language for this assignment. 
File name for this program : 
1
import java.util.Scanner;
2
class PrintNumbers implements Runnable {
3
//Create a constructor of this class that takes two private parameters (start and end) and initializes the instance variables with the provided values.
4
//Create Run() method
5
int start;
6
int end;
7
8
PrintNumbers(int start, int end){
9
  this.start = start;
10
  this.end = end;
11
}
12
13
@Override
14
public void run() {
15
  for (int i = start; i <= end; i= i+2) {
16
    System.out.println(Thread.currentThread().getName() + ": " + i);
17
  }
18
}
0
}
1
class W07_P5{
2
    //Code to create two threads, one printing even numbers and the other printing odd numbers
3
    public static void main(String[] args) {
4
        Scanner scanner = new Scanner(System.in);
5
        //System.out.print("Enter the starting value for even numbers: ");
6
        int evenStart = scanner.nextInt();
7
       // System.out.print("Enter the ending value for even numbers: ");
8
        int evenEnd = scanner.nextInt();
9
       // System.out.print("Enter the starting value for odd numbers: ");
10
        int oddStart = scanner.nextInt();
11
       // System.out.print("Enter the ending value for odd numbers: ");
12
        int oddEnd = scanner.nextInt();
13
        Thread evenThread = new Thread(new PrintNumbers(evenStart, evenEnd), "EvenThread");
14
        Thread oddThread = new Thread(new PrintNumbers(oddStart, oddEnd), "OddThread");
15
16
        evenThread.start();
17
try {
18
            Thread.sleep(1000);
19
        } catch (InterruptedException e) {
20
            e.printStackTrace();
21
        }
22
        oddThread.start();
23
        scanner.close();
24
    }
25
}
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
2
10
3
7
EvenThread: 2\n
EvenThread: 4\n
EvenThread: 6\n
EvenThread: 8\n
EvenThread: 10\n
OddThread: 3\n
OddThread: 5\n
OddThread: 7
EvenThread: 2\n
EvenThread: 4\n
EvenThread: 6\n
EvenThread: 8\n
EvenThread: 10\n
OddThread: 3\n
OddThread: 5\n
OddThread: 7\n
Passed after ignoring Presentation Error





Week 08 : Programming Assignment 1

Due on 2024-09-19, 23:59 IST

Complete the code segment to print the current year. Your code should compile successfully.

Note: In this program, you are not allowed to use any import statement. Use should use predefined class Calendar defined in java.util package.


Select the Language for this assignment. 
File name for this program : 
1
public class W08_P1 { 
2
    public static void main(String args[]){
3
        int year; // integer type variable to store year    
4
// An object of Calendar class 
5
java.util.Calendar current;
6
// Use getInstance() method to initialize the Calendar object.
7
current = java.util.Calendar.getInstance();
0
year = current.get(current.YEAR);
1
System.out.println("Current Year: "+year);
0
~~~THERE IS SOME INVISIBLE CODE HERE~~~
0
}
1
}
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
NA
Current Year: 2024\n
Current Month: 8
Current Year: 2024\n
Current Month: 8
Passed



Week 08 : Programming Assignment 2

Due on 2024-09-19, 23:59 IST

Complete the code segment to call the default method in the interface First and Second.

Your last recorded submission was on 2024-09-10, 12:52 IST
Select the Language for this assignment. 
File name for this program : 
1
interface First{ 
2
    // default method 
3
    default void show(){ 
4
        System.out.println("Default method implementation of First interface."); 
5
    } 
6
} 
7
  
8
interface Second{ 
9
    // Default method 
10
    default void show(){ 
11
        System.out.print("Default method implementation of Second interface."); 
12
    } 
13
} 
14
  
15
// Implementation class code 
16
class W08_P2 implements First, Second{ 
17
 // Overriding default show method 
18
    public void show(){
19
// use super keyword to call the show method of First interface 
20
First.super.show();
21
22
// use super keyword to call the show method of Second interface
23
Second.super.show();
0
} 
1
  
2
    public static void main(String args[]){ 
3
        W08_P2 q = new W08_P2(); 
4
        q.show(); 
5
    } 
6
}
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 



Private Test cases used for EvaluationStatus
Test Case 1
Passed



Week 08 : Programming Assignment 3

Due on 2024-09-19, 23:59 IST

Modify the code segment to print the following output.

 

-----------------OUTPUT------------------- (this line should not be printed)

Circle: This is Shape1

Circle: This is Shape2

------------------------------------------------- (this line should not be printed)


(Remember to match the output given exactly, including the spaces and new lines)
(passed with presentation error means you will always get full marks)

Your last recorded submission was on 2024-09-10, 12:53 IST
Select the Language for this assignment. 
File name for this program : 
1
// Interface ShapeX is created
2
interface ShapeX {
3
 public String base = "This is Shape1";
4
 public void display1();
5
}
6
7
// Interface ShapeY is created which extends ShapeX
8
interface ShapeY extends ShapeX {
9
 public String base = "This is Shape2";
10
 public void display2();
11
}
12
13
// Class ShapeG is created which implements ShapeY
14
class ShapeG implements ShapeY {
15
 public String base = "This is Shape3";
16
 //Overriding method in ShapeX interface
17
  public void display1() {
18
  System.out.println("Circle: " + ShapeX.base);
19
 }
20
 // Override method in ShapeY interface
21
  public void display2(){
22
  System.out.println("Circle: " + ShapeY.base);
23
}
24
}
0
// Main class Question 
1
public class W08_P3{
2
 public static void main(String[] args) {
3
  //Object of class shapeG is created and display methods are called.
4
  ShapeG circle = new ShapeG();
5
  circle.display1();
6
  circle.display2();
7
 }
8
}
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 



Private Test cases used for EvaluationStatus
Test Case 1
Passed



Week 08 : Programming Assignment 4

Due on 2024-09-19, 23:59 IST

Complete the code segment to execute the following program successfully. You should import the correct package(s) and/or class(s) to complete the code.

(Note: there is no error in the given fixed code, there is a way to print without using “System”)

(Hint: Use Static import)

Your last recorded submission was on 2024-09-10, 12:55 IST
Select the Language for this assignment. 
File name for this program : 
1
// Import the required package(s) and/or class(es)
2
import java.util.*;
3
import static java.lang.System.out;
0
// main class is created
1
public class W08_P4{
2
  public static void main(String[] args) {
3
    // Scanner object is created
4
    Scanner scanner = new Scanner(System.in);
5
     // Read String input using scanner class
6
    String courseName = scanner.nextLine(); 
7
     // Print the scanned String
8
    out.print("Course: " + courseName); 
9
  }
10
}
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
Programming in JAVA
Course: Programming in JAVA
Course: Programming in JAVA
Passed



Week 08 : Programming Assignment 5

Due on 2024-09-19, 23:59 IST

In the following program, there may be multiple exceptions.

You have to complete the code using ONLY ONE try-catch block to handle all the possible exceptions.

For example, if user’s input is 1, then it will throw and catch “java.lang.NullPointerException“.
(Hint: Try to catch the exception and print it)

(NOTE: DO NOT USE MORE THAN ONE TRY CATCH, there may be a penalty if you use more than one try catch block)

Your last recorded submission was on 2024-09-10, 12:57 IST
Select the Language for this assignment. 
File name for this program : 
1
import java.util.Scanner;
2
public class W08_P5{
3
      public static void main (String   args[ ] ) {
4
        Scanner scan = new Scanner(System.in);
5
          int i=scan.nextInt();
6
          int j;
7
// Put the following code under try-catch block to handle exceptions
8
try {
9
        switch (i) {
10
        case 0 : 
11
            int zero = 0; 
12
            j = 92/ zero;       
13
            break;
14
        case 1: 
15
            int b[ ] = null; 
16
            j = b[0] ;  
17
            break;
18
        default:
19
            System.out.print("No exception");
20
     }
21
 }
22
            // catch block          
23
        catch (Exception e) {       
24
           System.out.print(e) ;
25
        }
0
}
1
}
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
5
No exception
No exception
Passed
Test Case 2
1
java.lang.NullPointerException
java.lang.NullPointerException
Passed
Test Case 3
0
java.lang.ArithmeticException: / by zero
java.lang.ArithmeticException: / by zero
Passed



Week 09 : Programming Assignment 1

Due on 2024-09-26, 23:59 IST

Write a Java program to display the number rhombus structure.

Input: n=2
Output:
  1
212
  1

(the output shown with the public test case has no spaces in the beginning,
its a fault of the swayam portal as it removes whitespaces before and after the output
you can write your program normally including spaces and it will be correct)

(passed with presentation error means you will always get full marks)

Your last recorded submission was on 2024-09-14, 10:21 IST
Select the Language for this assignment. 
File name for this program : 
1
import java.util.Scanner;
2
class W09_P1 {
3
  public static void main(String args[]) 
4
    {
5
        Scanner in = new Scanner(System.in);
6
        //System.out.print("Input the number:  ");
7
        int n = in.nextInt();
8
// program to display the number rhombus structure
9
for ( int i = 1; i <= n ; i++)
10
{
11
  for ( int j = n; j >= 1 ; j-- )
12
  {
13
    if ( j > i )
14
      System.out.print(" ");
15
    else
16
      System.out.print(j);
17
  }
18
  for ( int j = 2; j <= n ; j++ )
19
  {
20
    if ( j > i )
21
      System.out.print("");
22
    else
23
      System.out.print(j);
24
  }
25
  System.out.print("\n");
26
}
27
for ( int i = n-1; i >= 1 ; i--)
28
{
29
  for ( int j = n; j >= 1 ; j-- )
30
  {
31
    if ( j > i )
32
      System.out.print(" ");
33
    else
34
      System.out.print(j);
35
  }
36
  for ( int j = 2; j <= n ; j++ )
37
  {
38
    if ( j > i )
39
      System.out.print("");
40
    else
41
      System.out.print(j);
42
  }
43
  System.out.print("\n");
44
}
0
}
1
}
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
4
1\n
  212\n
 32123\n
4321234\n
 32123\n
  212\n
   1
   1\n
  212\n
 32123\n
4321234\n
 32123\n
  212\n
   1\n
Passed after ignoring Presentation Error



Week 09 : Programming Assignment 2

Due on 2024-09-26, 23:59 IST

Write a Java program to create an abstract class Person with abstract methods eat(), sleep() and exercise().
Create subclasses Athlete and LazyPerson that extend the Person class and implement the respective methods to describe how each person eats, sleeps and exercises.
Override the respective method in each subclass.

Your last recorded submission was on 2024-09-14, 10:50 IST
Select the Language for this assignment. 
File name for this program : 
1
abstract class Person {
2
    public abstract void eat();
3
    public abstract void sleep();
4
    public abstract void exercise();
5
  }
6
// Create subclasses Athlete and LazyPerson that extend the Person class and implement the respective methods to describe how each person eats, sleeps and exercises.
7
class Athlete extends Person {
8
  public void eat() {
9
    System.out.println("Athlete: Include foods full of calcium, iron, potassium, and fiber.");
10
  }
11
  public void sleep() {
12
    System.out.println("Athlete: sleeps for 8 hours.");
13
  }
14
  public void exercise() {
15
    System.out.println("Athlete: Training allows the body to gradually build up strength and endurance, improve skill levels and build motivation, ambition and confidence.");
16
  }
17
}
18
class LazyPerson extends Person {
19
  public void eat() {
20
    System.out.println("Couch Potato: Eating while watching TV also prolongs the time period that we're eating.");
21
  }
22
  public void sleep() {
23
    System.out.println("Couch Potato: sleeps for 12 hours.");
24
  }
25
  public void exercise() {
26
    System.out.println("Couch Potato: Rarely exercising or being physically active.");
27
  }
28
}
0
public class W09_P2 {
1
    public static void main(String[] args) {
2
      Person athlete = new Athlete();
3
      Person lazyPerson = new LazyPerson();
4
      athlete.eat();
5
      athlete.exercise();
6
      athlete.sleep();
7
      lazyPerson.eat();
8
      lazyPerson.exercise();
9
      lazyPerson.sleep();
10
    }
11
  }
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
NA
Athlete: Include foods full of calcium, iron, potassium, and fiber.\n
Athlete: Training allows the body to gradually build up strength and endurance, improve skill levels and build motivation, ambition and confidence.\n
Athlete: sleeps for 8 hours.\n
Couch Potato: Eating while watching TV also prolongs the time period that we're eating.\n
Couch Potato: Rarely exercising or being physically active.\n
Couch Potato: sleeps for 12 hours.
Athlete: Include foods full of calcium, iron, potassium, and fiber.\n
Athlete: Training allows the body to gradually build up strength and endurance, improve skill levels and build motivation, ambition and confidence.\n
Athlete: sleeps for 8 hours.\n
Couch Potato: Eating while watching TV also prolongs the time period that we're eating.\n
Couch Potato: Rarely exercising or being physically active.\n
Couch Potato: sleeps for 12 hours.\n
Passed after ignoring Presentation Error



Week 09 : Programming Assignment 3

Due on 2024-09-26, 23:59 IST

Write a Java program to create a base class Shape with methods draw() and calculateArea().
Create two subclasses Circle and Cylinder.
Override the draw() method in each subclass to draw the respective shape.
In addition, override the calculateArea() method in the Cylinder subclass to calculate and return the total surface area of the cylinder.

(Remember to match the output given exactly, including the spaces and new lines)
(passed with presentation error means you will always get full marks)

Select the Language for this assignment. 
File name for this program : 
1
import java.util.Scanner;
2
abstract class Shape {
3
    public abstract void draw();
4
  
5
    public abstract double calculateArea();
6
  }
7
// Create two subclasses Circle and Cylinder and implement required method.
8
class Circle extends Shape {
9
  private double radius;
10
  
11
  Circle(double radius){
12
    this.radius = radius;
13
  }
14
  
15
  public double calculateArea(){
16
    return( Math.PI * radius * radius);
17
  }
18
  
19
  public void draw(){
20
    System.out.println("Drawing a circle");
21
  }
22
}
23
class Cylinder extends Shape {
24
  private double radius;
25
  private double height;
26
  
27
  
28
  Cylinder(double radius, double height){
29
    this.radius = radius;
30
    this.height = height;
31
  }
32
  
33
  public double calculateArea(){
34
    return( 2 * Math.PI * radius * ( radius + height) );
35
  }
36
  
37
  public void draw(){
38
    System.out.println("Drawing a cylinder");
39
  }
40
}
0
public class W09_P3{
1
    public static void main(String[] args) {
2
      Scanner in = new Scanner(System.in);
3
      int radius = in.nextInt();
4
      int height = in.nextInt();
5
6
      Shape circle = new Circle(radius);
7
      Shape cylinder = new Cylinder(radius, height);
8
  
9
      drawShapeAndCalculateArea(circle);
10
      drawShapeAndCalculateArea(cylinder);
11
    }
12
  
13
    public static void drawShapeAndCalculateArea(Shape shape) {
14
      shape.draw();
15
      double area = shape.calculateArea();
16
      System.out.printf("Area: %.4f%n", area);
17
    }
18
  }
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
2
3
Drawing a circle\n
Area: 12.5664\n
Drawing a cylinder\n
Area: 62.8319
Drawing a circle\n
Area: 12.5664\n
Drawing a cylinder\n
Area: 62.8319\n
Passed after ignoring Presentation Error



Week 09 : Programming Assignment 4

Due on 2024-09-26, 23:59 IST

Write a Java program to create a class called "ElectronicsProduct" with attributes for product ID, name, and price.
Implement methods to apply a discount and calculate the final price.
Create a subclass " WashingMachine" that adds a warranty period attribute and a method to extend the warranty.

Select the Language for this assignment. 
File name for this program : 
1
import java.util.Scanner;
2
class ElectronicsProduct {
3
    // Attributes for the product ID, name, and price
4
    private String productId;
5
    private String name;
6
    private double price;
7
8
    // Constructor to initialize the ElectronicsProduct object
9
    public ElectronicsProduct(String productId, String name, double price) {
10
        this.productId = productId;
11
        this.name = name;
12
        this.price = price;
13
    }
14
15
    // Method to apply a discount to the product price
16
    public void applyDiscount(double discountPercentage) {
17
        // Calculate the discount amount
18
        double discountAmount = price * discountPercentage / 100;
19
        // Subtract the discount amount from the original price
20
        price -= discountAmount;
21
    }
22
23
    // Method to calculate the final price after discount
24
    public double getFinalPrice() {
25
        // Return the current price which may have been discounted
26
        return price;
27
    }
28
29
    // Getter for product ID
30
    public String getProductId() {
31
        return productId;
32
    }
33
34
    // Getter for name
35
    public String getName() {
36
        return name;
37
    }
38
39
    // Getter for price
40
    public double getPrice() {
41
        return price;
42
    }
43
}
44
//Define the WashingMachine subclass that extends ElectronicsProduct
45
class WashingMachine extends ElectronicsProduct {
46
  public int warrantyPeriod;
47
  
48
  WashingMachine ( String productId, String name, double price, int warrantyPeriod) {
49
    super(productId,name,price);
50
    this.warrantyPeriod = warrantyPeriod;
51
  }
52
  
53
  public void applyDiscount(double discountPercentage) {
54
    super.applyDiscount(discountPercentage);
55
    System.out.println("Discount applied to Washing Machine: " + getName());
56
  }
57
  
58
  public int getWarrantyPeriod() {
59
    return warrantyPeriod;
60
  }
61
  public void extendWarranty(int months) {
62
    warrantyPeriod += months;
63
  }
64
}
0
public class W09_P4{
1
    public static void main(String[] args) {
2
        // Create an ElectronicsProduct object
3
        ElectronicsProduct product = new ElectronicsProduct("WM123", "Washing Machine", 1.00);
4
        // Apply a discount and display the final price
5
        product.applyDiscount(10);
6
        //System.out.println("Product ID: " + product.getProductId());
7
        //System.out.println("Name: " + product.getName());
8
        //System.out.println("Price after discount: $" + product.getFinalPrice());
9
        //System.out.println();
10
11
        // Create a WashingMachine object
12
        Scanner in = new Scanner(System.in);
13
14
        String productId = in.nextLine();     
15
        String name = in.nextLine();
16
        int price = in.nextInt();
17
        int warrantyPeriod = in.nextInt();
18
        
19
        int discountPercentage = in.nextInt();
20
21
        WashingMachine washingMachine = new WashingMachine(productId,name,price,warrantyPeriod);
22
        // Apply a discount and display the final price
23
        washingMachine.applyDiscount(discountPercentage);
24
        System.out.println("Product ID: " + washingMachine.getProductId());
25
        System.out.println("Name: " + washingMachine.getName());
26
        System.out.println("Price after discount: $" + washingMachine.getFinalPrice());
27
        // Display the warranty period
28
        System.out.println("Warranty period: " + washingMachine.getWarrantyPeriod() + " months");
29
30
        // Extend the warranty period and display the new warranty period
31
        washingMachine.extendWarranty(12);
32
        System.out.print("Warranty period after extension: " + washingMachine.getWarrantyPeriod() + " months");
33
    }
34
}
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
w34
whirlpool
800
12
10
Discount applied to Washing Machine: whirlpool\n
Product ID: w34\n
Name: whirlpool\n
Price after discount: $720.0\n
Warranty period: 12 months\n
Warranty period after extension: 24 months
Discount applied to Washing Machine: whirlpool\n
Product ID: w34\n
Name: whirlpool\n
Price after discount: $720.0\n
Warranty period: 12 months\n
Warranty period after extension: 24 months
Passed



Week 09 : Programming Assignment 5

Due on 2024-09-26, 23:59 IST

Write a Java program to find the length of the longest sequence of zeros in binary representation of an integer.

Your last recorded submission was on 2024-09-14, 11:43 IST
Select the Language for this assignment. 
File name for this program : 
1
import java.util.Scanner;
2
public class W09_P5{
3
// find the length of the longest sequence of zeros in binary representation of an integer.
4
public static int maxZeros(int n) {
5
  int maxlength = 0;
6
  String s = Integer.toBinaryString(n);
7
  for (int i = 0; i < s.length(); i++) {
8
    int local_length = 0;
9
    if (s.charAt(i) == '0'){
10
      local_length++;
11
      for (int j = i+1; j < s.length(); j++) {
12
        if (s.charAt(j) == '0')
13
          local_length++;
14
        else {
15
          i = j - 1;
16
          break;
17
        }
18
      }
19
    }
20
    if (local_length > maxlength)
21
      maxlength = local_length;
22
  }
23
  return maxlength;
24
}
0
public static void main(String args[]) {
1
                Scanner in = new Scanner(System.in);
2
3
                int n = in.nextInt();
4
                System.out.print(maxZeros(n));
5
6
        }
7
  
8
}
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
12546
6
6
Passed





Private Test cases used for EvaluationStatus
Test Case 1
Passed




Week 10 : Programming Assignment 1

Due on 2024-10-03, 23:59 IST

Complete the code fragment to read three integer inputs from keyboard and find the sum and store the result in the variable "sum".
NOTE: Name the class W10_P1 and the file W10_P1.java

(Remember to match the output given exactly, including the spaces and new lines)
(passed with presentation error means you will always get full marks)

Your last recorded submission was on 2024-09-26, 18:58 IST
Select the Language for this assignment. 
File name for this program : 
1
//Write the appropriate code to read 3 integer inputs from keyboard and find their sum.
2
// name the class W10_P1 and the file W10_P1.java
3
import java.util.*;
4
        public class W10_P1{ 
5
        public static void main (String[] args){ 
6
            
7
             int i,n=0,sum=0;
8
             Scanner inr = new Scanner(System.in);
9
        for (i=0;i<3;i++)
10
        {
11
            n = inr.nextInt();
12
            
13
        sum =sum+n;
14
            }
15
System.out.print(sum);
16
  }
17
}
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
1
2
3
6
6
Passed



Week 10 : Programming Assignment 2

Due on 2024-10-03, 23:59 IST

A byte char array is initialized.

You have to enter an index value "n".

According to index your program will print the byte and its corresponding char value.

Complete the code segment to catch the exception in the following, if any.

On the occurrence of such an exception, your program should print “Error: Exception occoured”.

If there is no such exception, it will print the required output.

Your last recorded submission was on 2024-09-26, 18:54 IST
Select the Language for this assignment. 
File name for this program : 
1
import java.util.*;
2
public class W10_P2 {  
3
    public static void main(String[] args) { 
4
       try{ 
5
       byte barr[]={'N','P','T','E','L','-','J','A','V','A','J','U',
6
       'L','-','N','O','C','C', 'S','\n'};
7
          Scanner inr = new Scanner(System.in);
8
        int n = inr.nextInt();
9
// Write the appropriate code to get specific indexed byte value and its corresponding char value.
10
String s2 = new String(barr,n,1);
11
System.out.println(barr[n]);
12
System.out.print(s2);
13
}// End of try block
14
catch (Exception e){
15
// print the required message here
16
  System.out.print("Error: Exception occoured");
17
        }
0
}  
1
}
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
1
80\n
P
80\n
P
Passed
Test Case 2
4
76\n
L
76\n
L
Passed
Test Case 3
24
Error: Exception occoured
Error: Exception occoured
Passed



Week 10 : Programming Assignment 3

Due on 2024-10-03, 23:59 IST

A string is read from the keyboard and is assigned to variable "s1". Your program should print the "number of vowels in s1”. However, if your input is other than "String" data type it will print "0".

Your last recorded submission was on 2024-09-26, 18:56 IST
Select the Language for this assignment. 
File name for this program : 
1
import java.io.*;
2
import java.util.*;
3
public class W10_P3{  
4
    public static void main(String[] args) { 
5
      int c=0;
6
         try{
7
            InputStreamReader r=new InputStreamReader(System.in);  
8
            BufferedReader br=new BufferedReader(r);  
9
            String s1 = br.readLine();
10
//Complete the code segment to count the number of vowels in the string "s1"
11
for(int i=0;i<s1.length();i++){  
12
          char s2=s1.charAt(i);
13
          if(s2=='e' || s2=='E'|| s2=='a' || s2=='A' || s2=='i' || s2=='I' || s2=='o' || s2=='O' || s2=='u' || s2=='U') 
14
         {
15
           c=c+1;
16
             }    
17
         } 
18
 System.out.print(c); 
19
       }
20
       catch (Exception e){
21
         System.out.print(e);
22
        }
0
} // end of main
1
} // end of class
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
ram
1
1
Passed
Test Case 2
aaA
3
3
Passed
Test Case 3
10
0
0
Passed



Week 10 : Programming Assignment 4

Due on 2024-10-03, 23:59 IST

A string "s1" is already initialized. You have to read the index "n".

Complete the code segment to catch the exception in the following, if any.

On the occurrence of such an exception, your program should print “exception occur”.

If there is no such exception, your program should replace the char ‘a’ at the index value "n" of the "s1",

then it will print the modified string.

Your last recorded submission was on 2024-09-26, 18:57 IST
Select the Language for this assignment. 
File name for this program : 
1
import java.util.*;
2
public class W10_P4 {  
3
    public static void main(String[] args) { 
4
       try{
5
           String s1="NPTELJAVA"; 
6
            Scanner inr = new Scanner(System.in);
7
          int n = inr.nextInt();
8
          char c='a';
9
//Replace the char in string "s1" with the char "a" at index "n" and print the modified string.
10
byte[] barr=s1.getBytes();   
11
          
12
                byte b1 = (byte) c;
13
                barr[n]=b1;
14
        System.out.print(new String(barr));
0
}
1
       catch (Exception e){
2
          System.out.print("exception occur");
3
        }      
4
    }  
5
}
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
-1
exception occur
exception occur
Passed
Test Case 2
e
exception occur
exception occur
Passed
Test Case 3
4
NPTEaJAVA
NPTEaJAVA
Passed



Week 10 : Programming Assignment 5

Due on 2024-10-03, 23:59 IST

Complete the code below with a catch statement to print the following if the denominator (b) is zero

print “Cannot Divide by ZERO”

Your last recorded submission was on 2024-09-26, 19:01 IST
Select the Language for this assignment. 
File name for this program : 
1
import java.util.Scanner;
2
3
public class W10_P5 {
4
5
    public static void main(String[] args) {
6
        int a, b;
7
        Scanner input = new Scanner(System.in);
8
        // Read any two values for a and b.
9
        // Get the result of a/b;
10
        int result;
11
12
        a = input.nextInt();
13
        b = input.nextInt();
14
        input.close();
15
        // try block to divide two numbers and display the result
16
        try {
17
            result = a / b;
18
            System.out.print(result);
19
        }
20
// catch block to catch the Error
21
catch (ArithmeticException e) {
22
            System.out.print("Cannot Divide by ZERO");
23
        }
0
catch (Exception e) {
1
            System.out.println("Exception Occoured");
2
   }
3
  }
4
}
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
6 
3
2
2
Passed
Test Case 2
1 
0
Cannot Divide by ZERO
Cannot Divide by ZERO
Passed




Week 11 : Programming Assignment 1

Due on 2024-10-10, 23:59 IST

The following code needs some package to work properly.

Write appropriate code to

§ import the required package(s) in order to make the program compile and execute successfully.

Hint: use static import

(NOTE: Ignore the fixed hidden code)

Select the Language for this assignment. 
File name for this program : 
1
import java.util.Scanner;
2
//Import required packages
3
import java.sql.*;
0
public class W11_P1 {
1
    public static void main(String args[]) {
2
        try {
3
            Connection conn = null;
4
            Statement stmt = null;
5
            String DB_URL = "jdbc:sqlite:/tempfs/db";
6
            System.setProperty("org.sqlite.tmpdir", "/tempfs");
0
~~~THERE IS SOME INVISIBLE CODE HERE~~~
0
} catch (Exception e) {
1
            System.out.println(e);
2
        }
3
    }
4
}
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
0
true
true
Passed



Week 11 : Programming Assignment 2

Due on 2024-10-10, 23:59 IST

Write the JDBC codes needed to create a Connection interface using the DriverManager class and the variable DB_URL.  Check whether the connection is successful using 'isValid(timeout)' method to generate the output, which is either 'true' or 'false'.

 

Note the following points carefully:

§ Name the connection object as conn only.

§ Use timeout value as 1.

Select the Language for this assignment. 
File name for this program : 
1
import java.sql.*;
2
import java.util.Scanner;
3
public class W11_P2 {
4
    public static void main(String args[]) {
5
        try {
6
              Connection conn = null;
7
              Statement stmt = null;
8
              String DB_URL = "jdbc:sqlite:/tempfs/db";
9
              System.setProperty("org.sqlite.tmpdir", "/tempfs");
10
// Open a connection and check connection status
11
conn = DriverManager.getConnection(DB_URL);
12
System.out.print(conn.isValid(1));
0
~~~THERE IS SOME INVISIBLE CODE HERE~~~
0
conn.close();
1
        } catch (Exception e) {
2
            System.out.println(e);
3
        }
4
    }
5
}
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
0
true
true
Passed



Week 11 : Programming Assignment 3

Due on 2024-10-10, 23:59 IST

Due to some mistakes in the below code, the code is not compiled/executable.

Modify and debug the JDBC code to make it execute successfully.

Select the Language for this assignment. 
File name for this program : 
1
~~~THERE IS SOME INVISIBLE CODE HERE~~~
2
// Fix bugs in the code, DO NOT ADD or DELETE ANY LINE
3
import java.sql.*;
4
import java.util.Scanner;
5
6
public class W11_P3 {
7
    public static void main(String args[]) {
8
        try {
9
              Connection conn = null;
10
              Statement stmt = null;
11
              String DB_URL = "jdbc:sqlite:/tempfs/db";
12
              System.setProperty("org.sqlite.tmpdir", "/tempfs");
13
              conn = DriverManager.getConnection(DB_URL);
14
              conn.close();
15
              System.out.print(conn.isClosed());
0
~~~THERE IS SOME INVISIBLE CODE HERE~~~
0
} catch (Exception e) {
1
            System.out.println(e);
2
        }
3
    }
4
}
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
0
true
true
Passed



Week 11 : Programming Assignment 4

Due on 2024-10-10, 23:59 IST

Complete the code segment to create a new table named ‘STUDENTS’ in SQL database using the following information.

Column

UID

Name

Roll

Age

Type

Integer

Varchar (45)

Varchar (12)

Integer

Select the Language for this assignment. 
File name for this program : 
1
import java.sql.*;
2
import java.lang.*;
3
public class W11_P4 {
4
    public static void main(String args[]) {
5
        try {
6
              Connection conn = null;
7
              Statement stmt = null;
8
              String DB_URL = "jdbc:sqlite:/tempfs/db";
9
              System.setProperty("org.sqlite.tmpdir", "/tempfs");
10
            
11
              // Open a connection
12
              conn = DriverManager.getConnection(DB_URL);
13
              stmt = conn.createStatement();
14
// The statement containing SQL command to create table "STUDENTS"
15
String CREATE_TABLE_SQL="CREATE TABLE STUDENTS (UID INT, Name VARCHAR(45), Roll VARCHAR(12), Age INT);";
16
// Execute the statement containing SQL command below this comment
17
stmt.executeUpdate(CREATE_TABLE_SQL);
0
~~~THERE IS SOME INVISIBLE CODE HERE~~~
0
}
1
       catch(Exception e){ System.out.println(e);}  
2
    }
3
}
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
1
No. of columns : 4\n
Column 1 Name: UID\n
Column 1 Type : INT\n
Column 2 Name: Name\n
Column 2 Type : VARCHAR\n
Column 3 Name: Roll\n
Column 3 Type : VARCHAR\n
Column 4 Name: Age\n
Column 5 Type : INT
No. of columns : 4\n
Column 1 Name: UID\n
Column 1 Type : INT\n
Column 2 Name: Name\n
Column 2 Type : VARCHAR\n
Column 3 Name: Roll\n
Column 3 Type : VARCHAR\n
Column 4 Name: Age\n
Column 5 Type : INT
Passed



Week 11 : Programming Assignment 5

Due on 2024-10-10, 23:59 IST

Complete the code segment to rename an already created table named ‘STUDENTS’  into ‘GRADUATES’.

Select the Language for this assignment. 
File name for this program : 
1
import java.sql.*;
2
import java.lang.*;
3
public class W11_P5 {
4
    public static void main(String args[]) {
5
        try {
6
              Connection conn = null;
7
              Statement stmt = null;
8
              String DB_URL = "jdbc:sqlite:/tempfs/db";
9
              System.setProperty("org.sqlite.tmpdir", "/tempfs");
10
              // Open a connection
11
              conn = DriverManager.getConnection(DB_URL);
12
              stmt = conn.createStatement();
13
~~~THERE IS SOME INVISIBLE CODE HERE~~~
14
// Write the SQL command to rename a table
15
String alter="ALTER TABLE STUDENTS RENAME TO GRADUATES;";
16
// Execute the SQL command
17
stmt.executeUpdate(alter);
0
~~~THERE IS SOME INVISIBLE CODE HERE~~~
0
}   catch(Exception e){ System.out.println(e);}  
1
    }
2
}
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
1
TABLE NAME = GRADUATES
TABLE NAME = GRADUATES
Passed




Week 12 : Programming Assignment 1

Due on 2024-10-17, 23:59 IST

In the following program, an array of integer data to be initialized.
During the initialization, if a user enters a value other than integer value, then it will throw InputMismatchException exception.
On the occurrence of such an exception, your program should print “
You entered bad data.”
If there is no such exception it will print the total sum of the array.

 

Your last recorded submission was on 2024-10-11, 08:42 IST
Select the Language for this assignment. 
File name for this program : 
1
//Prefixed Fixed Code:
2
import java.util.Scanner;
3
import java.util.InputMismatchException;
4
5
public class W12_P1 {
6
  public static void main(String[] args) {
7
      Scanner sc = new Scanner(System.in); 
8
    int length = sc.nextInt(); 
9
    // create an array to save user input 
10
    int[] name = new int[length];
11
     int sum=0;//save the total sum of the array.
12
/* Define try-catch block to save user input in the array "name"
13
   If there is an exception then catch the exception otherwise print the total sum of the array. */
14
try{
15
       for(int i=0;i<length;i++){  
16
          int userInput=sc.nextInt();
17
          name[i] = userInput;
18
          sum=sum+name[i]; 
19
          } 
20
        System.out.print(sum);
21
        }
22
       catch(InputMismatchException e) {
23
        System.out.print("You entered bad data.");
24
        }
0
}
1
}
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
3
5 2 1
8
8
Passed
Test Case 2
2
1 g
You entered bad data.
You entered bad data.
Passed



Week 12 : Programming Assignment 2

Due on 2024-10-17, 23:59 IST

Write suitable code to develop a 2D Flip-Flop Array with dimension 5 × 5, which replaces all input elements with values 0 by 1 and 1 by 0. 

Your last recorded submission was on 2024-10-11, 08:44 IST
Select the Language for this assignment. 
File name for this program : 
1
import java.util.Scanner;
2
public class W12_P2{
3
  public static void main(String args[]){
4
    Scanner sc = new Scanner(System.in);
5
// Declare the 5X5 2D array to store the input
6
7
// Input 2D Array using Scanner Class and check data validity
8
9
// Perform the Flip-Flop Operation
10
11
// Output the 2D Flip-Flop Array
12
String arr[]=new String[5];
13
    for(int i=0;i<5;i++)
14
        arr[i]=sc.nextLine();
15
    
16
char matrix[][]=new char[5][5];
17
for(int i=0;i<5;i++){
18
    char[] chararray=arr[i].toCharArray();
19
  for(int j=0;j<5;j++){
20
    matrix[i][j]=chararray[j];
21
  }
22
}
23
for(int i=0;i<5;i++){
24
  for(int j=0;j<5;j++){
25
    if(matrix[i][j]=='0')
26
      System.out.print('1');
27
    else
28
      System.out.print('0');
29
   
30
  }
31
  System.out.println();
32
}
0
} // The main() ends here
1
} // The main class ends here
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
00001
00001
00001
00001
00001
11110\n
11110\n
11110\n
11110\n
11110
11110\n
11110\n
11110\n
11110\n
11110\n
Passed after ignoring Presentation Error



Week 12 : Programming Assignment 3

Due on 2024-10-17, 23:59 IST

Write a program to print Butterfly star pattern.

Your last recorded submission was on 2024-10-11, 11:27 IST
Select the Language for this assignment. 
File name for this program : 
1
import java.util.Scanner;
2
public class W12_P3 {
3
  public static void main(String[] args) {
4
      //  int n = 7; // Number of rows (should be odd for symmetry)
5
       Scanner sc = new Scanner(System.in);
6
         int n = sc.nextInt();
7
//Print Butterfly pattern
8
        // Step 2: Print the upper half of the butterfly pattern
9
        for (int i = 1; i <= n; i++) {
10
            // Step 3: Print the left wing of the butterfly
11
            for (int j = 1; j <= i; j++) {
12
                System.out.print("*");
13
            }
14
15
            // Step 4: Print spaces in the middle
16
            for (int j = 1; j <= 2 * (n - i); j++) {
17
                System.out.print(" ");
18
            }
19
20
            // Step 5: Print the right wing of the butterfly
21
            for (int j = 1; j <= i; j++) {
22
                System.out.print("*");
23
            }
24
25
            System.out.println();
26
        }
27
28
        // Step 6: Print the lower half of the butterfly pattern
29
        for (int i = n; i >= 1; i--) {
30
            // Step 7: Print the left wing of the butterfly
31
            for (int j = 1; j <= i; j++) {
32
                System.out.print("*");
33
            }
34
35
            // Step 8: Print spaces in the middle
36
            for (int j = 1; j <= 2 * (n - i); j++) {
37
                System.out.print(" ");
38
            }
39
40
            // Step 9: Print the right wing of the butterfly
41
            for (int j = 1; j <= i; j++) {
42
                System.out.print("*");
43
            }
44
45
            System.out.println();
46
        }
47
48
        // Close the scanner
49
        sc.close();
0
}
1
}
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
3
*    *\n
**  **\n
******\n
******\n
**  **\n
*    *
*    *\n
**  **\n
******\n
******\n
**  **\n
*    *\n
Passed after ignoring Presentation Error



Week 12 : Programming Assignment 4

Due on 2024-10-17, 23:59 IST

Write a program to solve the given Sudoku.

530070000
600195000
098000060
800060003
400803001
700020006
060000280
000419005
000080079

(0 is unsloved)
(Remember to match the output given exactly, including the spaces and new lines)
(passed with presentation error means you will always get full marks)
(DO NOT PUT spaces between the numbers in the output)

Your last recorded submission was on 2024-10-11, 10:54 IST
Select the Language for this assignment. 
File name for this program : 
1
public class W12_P4 {
2
//program to solve Sudoku
3
//printBoard should not print any spaces
4
public int BOARD_START_INDEX = 0;
5
public int BOARD_SIZE = 9;
6
public int NO_VALUE = 0;
7
public int MIN_VALUE = 1;
8
public int MAX_VALUE = 9;
9
public int SUBSECTION_SIZE = 3;
10
11
private boolean solveSudoku(int[][] board) {
12
  return solve(board);
13
}
14
private boolean solve(int[][] board) {
15
    for (int row = BOARD_START_INDEX; row < BOARD_SIZE; row++) {
16
        for (int column = BOARD_START_INDEX; column < BOARD_SIZE; column++) {
17
            if (board[row][column] == NO_VALUE) {
18
                for (int k = MIN_VALUE; k <= MAX_VALUE; k++) {
19
                    board[row][column] = k;
20
                    if (isValid(board, row, column) && solve(board)) {
21
                        return true;
22
                    }
23
                    board[row][column] = NO_VALUE;
24
                }
25
                return false;
26
            }
27
        }
28
    }
29
    return true;
30
}
31
private boolean isValid(int[][] board, int row, int column) {
32
    return (rowConstraint(board, row)
33
      && columnConstraint(board, column) 
34
      && subsectionConstraint(board, row, column));
35
}
36
private boolean rowConstraint(int[][] board, int row) {
37
    boolean[] constraint = new boolean[BOARD_SIZE];
38
    for (int column = BOARD_START_INDEX; column < BOARD_SIZE; column++) {
39
        if (!checkConstraint(board, row, constraint, column)) {
40
            return false;
41
        }
42
    }
43
    return true;
44
}
45
private boolean columnConstraint(int[][] board, int column) {
46
    boolean[] constraint = new boolean[BOARD_SIZE];
47
    for (int row = BOARD_START_INDEX; row < BOARD_SIZE; row++) {
48
        if (!checkConstraint(board, row, constraint, column)) {
49
            return false;
50
        }
51
    }
52
    return true;
53
}
54
private boolean subsectionConstraint(int[][] board, int row, int column) {
55
    boolean[] constraint = new boolean[BOARD_SIZE];
56
    int subsectionRowStart = (row / SUBSECTION_SIZE) * SUBSECTION_SIZE;
57
    int subsectionRowEnd = subsectionRowStart + SUBSECTION_SIZE;
58
59
    int subsectionColumnStart = (column / SUBSECTION_SIZE) * SUBSECTION_SIZE;
60
    int subsectionColumnEnd = subsectionColumnStart + SUBSECTION_SIZE;
61
62
    for (int r = subsectionRowStart; r < subsectionRowEnd; r++) {
63
        for (int c = subsectionColumnStart; c < subsectionColumnEnd; c++) {
64
            if (!checkConstraint(board, r, constraint, c)) return false;
65
        }
66
    }
67
    return true;
68
}
69
boolean checkConstraint(
70
  int[][] board, 
71
  int row, 
72
  boolean[] constraint, 
73
  int column) {
74
    if (board[row][column] != NO_VALUE) {
75
        if (!constraint[board[row][column] - 1]) {
76
            constraint[board[row][column] - 1] = true;
77
        } else {
78
            return false;
79
        }
80
    }
81
    return true;
82
}
83
private void printBoard(int[][] board) {
84
    for (int row = BOARD_START_INDEX; row < BOARD_SIZE; row++) {
85
        for (int column = BOARD_START_INDEX; column < BOARD_SIZE; column++) {
86
            System.out.print(board[row][column]);
87
        }
88
      if ( row != BOARD_SIZE-1 )
89
        System.out.println();
90
    }
91
}
0
public static void main(String[] args) {
1
        W12_P4 solver = new W12_P4();
2
        int[][] board = {
3
            {5, 3, 0, 0, 7, 0, 0, 0, 0},
4
            {6, 0, 0, 1, 9, 5, 0, 0, 0},
5
            {0, 9, 8, 0, 0, 0, 0, 6, 0},
6
            {8, 0, 0, 0, 6, 0, 0, 0, 3},
7
            {4, 0, 0, 8, 0, 3, 0, 0, 1},
8
            {7, 0, 0, 0, 2, 0, 0, 0, 6},
9
            {0, 6, 0, 0, 0, 0, 2, 8, 0},
10
            {0, 0, 0, 4, 1, 9, 0, 0, 5},
11
            {0, 0, 0, 0, 8, 0, 0, 7, 9}
12
        };
13
14
        //System.out.println("Sudoku board before solving:");
15
        //solver.printBoard(board);
16
17
        if (solver.solveSudoku(board)) {
18
            //System.out.println("\nSudoku board after solving:");
19
            solver.printBoard(board);
20
        } else {
21
            System.out.println("No solution exists.");
22
        }
23
    }
24
}
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
530070000
600195000
098000060
800060003
400803001
700020006
060000280
000419005
000080079
534678912\n
672195348\n
198342567\n
859761423\n
426853791\n
713924856\n
961537284\n
287419635\n
345286179
534678912\n
672195348\n
198342567\n
859761423\n
426853791\n
713924856\n
961537284\n
287419635\n
345286179
Passed



Week 12 : Programming Assignment 5

Due on 2024-10-17, 23:59 IST

Write a program to create a Tic-Tac-Toe game.

You have to create the logic for determining the winner, INPUT and OUTPUT is already taken care of.

Read the code and find a method to determine the winner and store in the variable `winner` (x, o).
If it's a draw then set the `gameWon` variable as false.

Your last recorded submission was on 2024-10-11, 11:23 IST
Select the Language for this assignment. 
File name for this program : 
1
import java.util.Scanner;
2
3
public class W12_P5 {
4
5
  private static final int ROWS = 3;
6
  private static final int COLS = 3;
7
8
  private static char[][] board = new char[ROWS][COLS];
9
10
  private static void initializeBoard() {
11
    for (int i = 0; i < ROWS; i++) {
12
      for (int j = 0; j < COLS; j++) {
13
        board[i][j] = '-';
14
      }
15
    }
16
  }
17
18
  private static void printBoard() {
19
    System.out.println("-------------");
20
    for (int i = 0; i < ROWS; i++) {
21
      System.out.print("| ");
22
      for (int j = 0; j < COLS; j++) {
23
        System.out.print(board[i][j] + " | ");
24
      }
25
      System.out.println();
26
      System.out.println("-------------");
27
    }
28
  }
29
30
  private static void inputBoard(Scanner scanner) {
31
    for (int i = 0; i < ROWS; i++) {
32
      String line = scanner.nextLine();
33
      String[] cells = line.split(" ");
34
      for (int j = 0; j < COLS; j++) {
35
        board[i][j] = cells[j].charAt(0);
36
      }
37
    }
38
  }
39
40
  private static void printWinner(boolean gameWon, char winner) {
41
    // Print result
42
    if (gameWon) {
43
      System.out.print("Player " + winner + " wins!");
44
    } else {
45
      System.out.print("It's a draw!");
46
    }
47
  }
48
49
  public static void main(String[] args) {
50
    boolean gameWon = false;
51
    char winner = '-';
52
53
    Scanner scanner = new Scanner(System.in);
54
55
    initializeBoard();
56
    inputBoard(scanner);
57
    printBoard();
58
//Code to implement a Tic-Tac-Toe game
59
//You have to check for winner
60
for (int i = 0; i < ROWS; i++) {
61
  char temp = board[i][0];
62
  boolean win = true;
63
      for (int j = 0; j < COLS; j++) {
64
        if ( board[i][j] != temp )
65
          win = false;
66
      }
67
  if ( win == true ){
68
    gameWon = true;
69
    winner = board[i][0];
70
    break;
71
  }
72
}
73
for (int i = 0; i < COLS; i++) {
74
  char temp = board[0][i];
75
  boolean win = true;
76
      for (int j = 0; j < ROWS; j++) {
77
        if ( board[j][i] != temp )
78
          win = false;
79
      }
80
  if ( win == true ){
81
    gameWon = true;
82
    winner = board[0][i];
83
    break;
84
  }
85
}
86
87
if ( board[0][0] == board[1][1] && board[1][1] == board[2][2] ){
88
  gameWon = true;
89
  winner = board[0][0];
90
}
91
if ( board[0][2] == board[1][1] && board[1][1] == board[2][0] ){
92
  gameWon = true;
93
  winner = board[1][1];
94
}
0
printWinner(gameWon, winner);
1
    scanner.close();
2
  }
3
}
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
x x o
o o x
x x o
-------------\n
| x | x | o | \n
-------------\n
| o | o | x | \n
-------------\n
| x | x | o | \n
-------------\n
It's a draw!
-------------\n
| x | x | o | \n
-------------\n
| o | o | x | \n
-------------\n
| x | x | o | \n
-------------\n
It's a draw!
Passed
Test Case 2
x x o
x x x
o o x
-------------\n
| x | x | o | \n
-------------\n
| x | x | x | \n
-------------\n
| o | o | x | \n
-------------\n
Player x wins!
-------------\n
| x | x | o | \n
-------------\n
| x | x | x | \n
-------------\n
| o | o | x | \n
-------------\n
Player x wins!
Passed
Test Case 3
o o x
o x x
o x x
-------------\n
| o | o | x | \n
-------------\n
| o | x | x | \n
-------------\n
| o | x | x | \n
-------------\n
Player o wins!
-------------\n
| o | o | x | \n
-------------\n
| o | x | x | \n
-------------\n
| o | x | x | \n
-------------\n
Player o wins!
Passed
















































No comments:

Post a Comment

Keep your comments reader friendly. Be civil and respectful. No self-promotion or spam. Stick to the topic. Questions welcome.