Home

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

NPTEL Programming in Java Jan 2024 Week 9 to 10


  Please scroll down for latest Programs. ðŸ‘‡ 


Week 9 : Programming Assignment 1

Due on 2024-03-28, 23:59 IST
Write a Java program that utilizes multithreading to calculate and print the squares of numbers from a specified begin to a specified end.
The main method is already created.
You need to design a SquareThread class that has two members,
  • int begin;
  • int end;
Each thread should sequentially print the squares of numbers from begin to end (both inclusive).
The same code will be used to create another thread that prints the sqaure of numbers from end to begin in reverse order.
(if begin is greater than end, print the square of each number in reverse order first)
The main method will first call SquareThread with begin and end and then in reverse order.
The class you create should be able to handle such case and print as required in the correct order.
HINT: use the keyword `synchronized` in the run method.
Your last recorded submission was on 2024-03-18, 17:40 IST
Select the Language for this assignment. 
File name for this program : 
1
import java.util.Scanner;
2
 
3
class SquareThread extends Thread {
4
    private int begin;
5
    private int end;
6
SquareThread(int begin, int end){
7
  this.begin = begin;
8
  this.end = end;
9
}
10
 
11
synchronized public void run() {
12
        // print the square of each number from begin to end
13
       if( begin <= end )
14
        for (int i=begin; i<=end; i++)
15
          System.out.println(i*i);  
16
        // if begin is greater than end, 
17
        // print the square of each number in reverse order from end to begin
18
       else
19
        for (int i=begin; i>=end; i--)
20
          System.out.println(i*i);
21
}
0
}
1
 
2
public class W09_P1 {
3
    public static void main(String args[]) {
4
        Scanner scanner = new Scanner(System.in);
5
        //System.out.print("Enter the begin for square calculation: ");
6
        int begin = scanner.nextInt();
7
        //System.out.print("Enter the end for square calculation: ");
8
        int end = scanner.nextInt();
9
        scanner.close();
10
 
11
        SquareThread thread1 = new SquareThread(begin, end);
12
        SquareThread thread2 = new SquareThread(end, begin);
13
 
14
        thread1.start();       
15
        thread2.start();
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
5
1\n
4\n
9\n
16\n
25\n
25\n
16\n
9\n
4\n
1
1\n
4\n
9\n
16\n
25\n
25\n
16\n
9\n
4\n
1\n
Passed after ignoring Presentation Error
Test Case 2
9
6
81\n
64\n
49\n
36\n
36\n
49\n
64\n
81
81\n
64\n
49\n
36\n
36\n
49\n
64\n
81\n
Passed after ignoring Presentation Error


Week 9 : Programming Assignment 2

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

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

On the occurrence of such an exception, your program should print

§ Please enter valid data

If there is no such exception, it will print the square of the number entered.

Your last recorded submission was on 2024-03-18, 19:12 IST
Select the Language for this assignment. 
File name for this program : 
1
import java.io.*;  
2
class W09_P2{  
3
        public static void main(String args[]){
4
try{
5
  java.util.Scanner r=new java.util.Scanner(System.in);  
6
  String number=r.nextLine();
7
  int x = Integer.parseInt(number);
8
  System.out.print(x*x);
9
}
10
catch( Exception e )
11
{
12
  System.out.print("Please enter valid data");
13
}
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
4
Passed
Test Case 2
q
Please enter valid data
Please enter valid data
Passed


Week 9 : Programming Assignment 3

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

The program given below stores characters in a byte array named byte_array, which means ‘A’ is stored as 65.

Your task is the following:

§  Given a user input `n`, print the output in the given format, if `n` = 1, print:

o   byte_array[1] = ‘P’

§ If the value of n is negative or is out of bound, then use TRY_CATCH to print the following:

o   Array index is out of range

Your last recorded submission was on 2024-03-18, 11:51 IST
Select the Language for this assignment. 
File name for this program : 
1
import java.util.*;
2
 
3
public class W09_P3 {
4
    public static void main(String[] args) {
5
        try {
6
            byte byte_array[] = {
7
                'N', 'P', 'T', 'E', 'L', ' ', 
8
                '-', ' ', 
9
                'P', 'R', 'O', 'G', 'R', 'A', 'M', 'M', 'I', 'N', 'G', ' ', 
10
                'I', 'N', ' ', 
11
                'J', 'A', 'V', 'A'};
12
            Scanner inr = new Scanner(System.in);
13
            int n = inr.nextInt();
14
            inr.close();
15
// print the required output
16
 
17
System.out.print("byte_array[" + n + "] = '" + (char)byte_array[n] + "'");
18
}
19
// close try and add a catch block for index out of bounds
20
catch (IndexOutOfBoundsException e2) {
21
      System.out.print("Array index is out of range");
22
    }
0
catch (Exception e) {
1
            System.out.println("Exception occurred");
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
byte_array[0] = 'N'
byte_array[0] = 'N'
Passed
Test Case 2
-1
Array index is out of range
Array index is out of range
Passed


Week 9 : Programming Assignment 4

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

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 distance(Point p2){} // Function to return the distance of this Point from another Point

Your last recorded submission was on 2024-03-18, 11:23 IST
Select the Language for this assignment. 
File name for this program : 
1
import java.util.Scanner;
2
 
3
public class W09_P4{
4
            
5
    public static void main(String[] args) {
6
 
7
        Scanner sc = new Scanner(System.in);
8
        double x1 = sc.nextDouble();
9
        double y1 = sc.nextDouble();
10
        double x2 = sc.nextDouble();
11
        double y2 = sc.nextDouble();
12
        Point p1 = new Point(x1, y1);
13
        Point p2 = new Point(x2, y2);
14
        
15
        System.out.print(p1.distance(p2));
16
    }
17
 
18
}
19
//Complete the code segment to define a class Point with parameter x,y and method distance()for calculating distance between two points.
20
// Note: Pass objectsof type class Point as argument in distance() method.
21
class Point{
22
  private double x;
23
  private double y;
24
  
25
  public Point(double x, double y){ //Constructor to initialize a Shape object  
26
    this.x = x;
27
    this.y= y;
28
  }
29
 
30
  public double distance(Point p2){
31
    double d;
32
    d=Math.sqrt((p2.x-x)*(p2.x-x) + (p2.y-y)*(p2.y-y));
33
    return d;
34
  }
35
}
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
1.4142135623730951
1.4142135623730951
Passed
Test Case 2
0 0
0 5
5.0
5.0
Passed


Week 9 : Programming Assignment 5

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

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

§ Cannot Divide by ZERO

Your last recorded submission was on 2024-03-18, 10:12 IST
Select the Language for this assignment. 
File name for this program : 
1
import java.util.Scanner;
2
 
3
public class W09_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.println(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\n
Passed after ignoring Presentation Error
Test Case 2
1 0
Cannot Divide by ZERO
Cannot Divide by ZERO
Passed





Week 10 : Programming Assignment 1

Due on 2024-04-04, 23:59 IST
Program to sort the elements of an array in ascending order. Follow the naming convention as given in the main method of the suffix code.
Your last recorded submission was on 2024-03-25, 08:55 IST
Select the Language for this assignment. 
File name for this program : 
1
import java.util.Scanner;
2
class W10_P1
3
{
4
   public static void printArray(int[] array)
5
    {
6
        // Iterating using for loops
7
        for (int i = 0; i < array.length; i++) {
8
            System.out.print(array[i] + " ");
9
        }
10
       // System.out.println();
11
    }
12
//code to sort the elements of an array in ascending order.
13
public static void sortArray(int[] array)
14
{
15
  for (int i = 0; i < array.length; i++) {
16
    for (int j = 0; j < array.length-i-1; j++) {
17
      if(array[j]>array[j+1])
18
      {
19
        int tmp = array[j];
20
        array[j] = array[j+1];
21
        array[j+1] = tmp;
22
      }
23
    }
24
  }
25
}
0
public static void main(String... a)
1
    {        
2
        Scanner s = new Scanner(System.in);
3
        int size = s.nextInt();
4
        int[] array = new int[size];
5
        int i;
6
        for (i = 0; i < size; i++) {
7
            array[i] = s.nextInt();
8
        }
9
        sortArray(array);
10
// Displaying elements of array after sorting
11
         System.out.println(
12
            "Elements of array sorted in ascending order:");
13
        printArray(array);
14
 
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
6
-5 -9 8 12 1 3
Elements of array sorted in ascending order:\n
-9 -5 1 3 8 12
Elements of array sorted in ascending order:\n
-9 -5 1 3 8 12 
Passed after ignoring Presentation Error



Week 10 : Programming Assignment 2

Due on 2024-04-04, 23:59 IST
Print a given matrix in spiral form. Follow the naming convention as given in the main method of the suffix code.
Your last recorded submission was on 2024-03-25, 15:15 IST
Select the Language for this assignment. 
File name for this program : 
1
import java.util.*;
2
 
3
public class W10_P2{
4
//code to print a given matrix in spiral form.
5
public static void spiral_method(int [][] a, int dimension1, int dimension2)
6
{
7
  int k = 0;
8
  int l = 0;
9
  
10
  while(k<dimension1 && l<dimension2){
11
    
12
    for (int i = l; i < dimension2 ; i++)
13
      System.out.print(a[k][i] + " ");
14
    
15
    k++;
16
    
17
    for (int i = k; i < dimension1 ; i++)
18
      System.out.print(a[i][dimension2-1] + " ");
19
    
20
    dimension2--;
21
    
22
    if(k<dimension1){
23
      for (int i = dimension2-1; i > l-1 ; i--)
24
      System.out.print(a[dimension1-1][i] + " ");
25
    
26
    dimension1--;
27
    }
28
    
29
    if(l<dimension2){
30
      for (int i = dimension1-1; i > k-1 ; i--)
31
      System.out.print(a[i][l] + " ");
32
    
33
    l++;
34
    }
35
  }
36
}
0
public static void main(String args[]) {
1
        int i, j;
2
        // double sum = 0, square = 0, result = 0;
3
        Scanner s = new Scanner(System.in);
4
        int dimension = s.nextInt();
5
 
6
        int[][] spiral = new int[dimension][dimension];
7
        for (i = 0; i < dimension ; i++) {
8
            // loop for columns
9
            for (j = 0; j < dimension ; j++) {
10
                // reads the matrix elements
11
                spiral[i][j] = s.nextInt();
12
            }
13
        }
14
        spiral_method(spiral, dimension,dimension);
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
5
6 3 2 1 4
7 8 3 12 9
1 11 10 5 8
5 18 6 9 14
19 23 3 12 11
6 3 2 1 4 9 8 14 11 12 3 23 19 5 1 7 8 3 12 5 9 6 18 11 10
6 3 2 1 4 9 8 14 11 12 3 23 19 5 1 7 8 3 12 5 9 6 18 11 10 
Passed after ignoring Presentation Error






Week 10 : Programming Assignment 3

Due on 2024-04-04, 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.
  • Hints: 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.
Your last recorded submission was on 2024-03-25, 10:52 IST
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 W10_P3{
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
 
6
        //System.out.print("Enter the starting value for even numbers: ");
7
        int evenStart = scanner.nextInt();
8
       // System.out.print("Enter the ending value for even numbers: ");
9
        int evenEnd = scanner.nextInt();
10
 
11
       // System.out.print("Enter the starting value for odd numbers: ");
12
        int oddStart = scanner.nextInt();
13
       // System.out.print("Enter the ending value for odd numbers: ");
14
        int oddEnd = scanner.nextInt();
15
 
16
        Thread evenThread = new Thread(new PrintNumbers(evenStart, evenEnd), "EvenThread");
17
        Thread oddThread = new Thread(new PrintNumbers(oddStart, oddEnd), "OddThread");
18
 
19
        evenThread.start();
20
try {
21
            Thread.sleep(1000);
22
        } catch (InterruptedException e) {
23
            e.printStackTrace();
24
        }
25
        oddThread.start();
26
 
27
        scanner.close();
28
    }
29
}
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 10 : Programming Assignment 4

Due on 2024-04-04, 23:59 IST
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-03-25, 11:12 IST
Select the Language for this assignment. 
File name for this program : 
1
import java.util.Scanner;
2
 
3
public class W10_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.println(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\n
Passed after ignoring Presentation Error


Week 10 : Programming Assignment 5

Due on 2024-04-04, 23:59 IST
Write a program that converts temperatures between Celsius and Fahrenheit. Implement two methods, celsiusToFahrenheit and fahrenheitToCelsius, to perform the conversions.
  • Use exception handling to handle invalid input temperatures (if  celsius < -273.15 and fahrenheit < -459.67 , program should throw exception error).
  • The TemperatureConverter class contains two methods for temperature conversion (celsiusToFahrenheit and fahrenheitToCelsius).
  • The TemperatureException class is a custom exception class that extends Exception and is used to handle invalid temperatures.
  • The TemperatureConverterApp class is the main class that takes user input for temperatures and handles potential exceptions during the conversion process.
  • celsiusToFahrenheit = (celsius * 9 / 5) + 32
  • fahrenheitToCelsius = (fahrenheit - 32) * 5 / 9
Follow the naming convention as given in the main method of the suffix code.
Your last recorded submission was on 2024-03-25, 11:35 IST
Select the Language for this assignment. 
File name for this program : 
1
import java.util.Scanner;
2
class TemperatureException extends Exception {
3
    public TemperatureException(String message) {
4
        super(message);
5
    }
6
}
7
 
8
class TemperatureConverter {
9
//Code to create two function for temperature conversion (celsiusToFahrenheit and fahrenheitToCelsius).
10
public static double celsiusToFahrenheit(double celsius) throws TemperatureException {
11
  if ( celsius < -273.15 )
12
    throw new TemperatureException("Invalid Celsius temperature (below absolute zero)");
13
  else
14
    return (celsius * 9 / 5) + 32;
15
}
16
 
17
public static double fahrenheitToCelsius (double fahrenheitInput) throws TemperatureException {
18
  if ( fahrenheitInput < -459.67 )
19
    throw new TemperatureException("Invalid Fahrenheit temperature (below absolute zero)");
20
  else
21
    return (fahrenheitInput - 32) * 5 / 9;
22
}
23
 
24
}
0
public class W10_P5{
1
    public static void main(String[] args) {
2
        Scanner scanner = new Scanner(System.in);
3
 
4
        try {
5
            //System.out.print("Enter temperature in Celsius: ");
6
            double celsius = scanner.nextDouble();
7
            double fahrenheit = TemperatureConverter.celsiusToFahrenheit(celsius);
8
            System.out.println("Temperature in Fahrenheit: " + fahrenheit);
9
 
10
          //  System.out.print("Enter temperature in Fahrenheit: ");
11
            double fahrenheitInput = scanner.nextDouble();
12
            double celsiusOutput = TemperatureConverter.fahrenheitToCelsius(fahrenheitInput);
13
            System.out.println("Temperature in Celsius: " + celsiusOutput);
14
        } catch (TemperatureException e) {
15
            System.out.println("Error: " + e.getMessage());
16
        } catch (Exception e) {
17
            System.out.println("Error: Invalid input");
18
        } finally {
19
            scanner.close();
20
        }
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
-278
Error: Invalid Celsius temperature (below absolute zero)
Error: Invalid Celsius temperature (below absolute zero)\n
Passed after ignoring Presentation Error
Test Case 2
-1
-500
Temperature in Fahrenheit: 30.2\n
Error: Invalid Fahrenheit temperature (below absolute zero)
Temperature in Fahrenheit: 30.2\n
Error: Invalid Fahrenheit temperature (below absolute zero)\n
Passed after ignoring Presentation Error
Test Case 3
45
112
Temperature in Fahrenheit: 113.0\n
Temperature in Celsius: 44.44444444444444
Temperature in Fahrenheit: 113.0\n
Temperature in Celsius: 44.44444444444444\n
Passed after ignoring Presentation Error











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.