Swayam NPTEL Programming in Java Programming Assignment July-2025 Week-1 to Week-9

  Please scroll down for latest Programs. 👇  



Week 01 : Programming Assignment 3

Due on 2025-08-07, 23:59 IST

Write a Java program to print the multiplication table of a given number up to 4.

 

NOTE:

Print EXACTLY as shown in the sample output.

DO NOT MISS a single space otherwise you will not be scored.

(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 2025-07-24, 10:16 IST
Select the Language for this assignment. 
File name for this program : 
import java.util.Scanner;
 
public class W01_P3 {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int number = in.nextInt();
// Print the multiplication table of number up to 5
for (int i = 1; i <= 4; i++)
  System.out.printf("%d x %d = %d\n", number, i, number * i);
in.close();
    }
}
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
5
5 x 1 = 5\n
5 x 2 = 10\n
5 x 3 = 15\n
5 x 4 = 20
5 x 1 = 5\n
5 x 2 = 10\n
5 x 3 = 15\n
5 x 4 = 20\n
Passed after ignoring Presentation Error



Week 01 : Programming Assignment 4

Due on 2025-08-07, 23:59 IST

Complete the code fragment that reads two integer inputs from keyboard and compute the quotient and remainder.

Your last recorded submission was on 2025-07-24, 10:18 IST
Select the Language for this assignment. 
File name for this program : 
import java.util.Scanner;
public class W01_P4{
       public static void main(String[] args) {
       Scanner sc = new Scanner(System.in);
       int x=sc.nextInt();
       int y=sc.nextInt();
//code for quotient and remainder
if (y == 0) {
  System.out.println("Error: Division by zero is not allowed.");
}
else {
  int quotient = x / y;
  int remainder = x % y;
  System.out.println("The Quotient is = " + quotient);
  System.out.print("The Remainder is = " + remainder);
}
sc.close();  
  }
}
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
556
9
The Quotient is = 61\n
The Remainder is = 7
The Quotient is = 61\n
The Remainder is = 7
Passed



Week 01 : Programming Assignment 5

Due on 2025-08-07, 23:59 IST

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

Your last recorded submission was on 2025-07-24, 10:19 IST
Select the Language for this assignment. 
File name for this program : 
import java.util.Scanner;
public class W01_P5 { 
   public static void main(String[] strings) {
       double width ;
       double height;
       Scanner in = new Scanner(System.in);
       width = in.nextDouble();
       height = in.nextDouble();
// Calculate the perimeter of the rectangle
double perimeter = 2 * ( height + width ) ;
// Calculate the area of the rectangle
double area = height * width;
// Print the calculated perimeter using placeholders for values
       System.out.printf("Perimeter is 2*(%.1f + %.1f) = %.2f\n", height, width, perimeter);
 
// Print the calculated area using placeholders for values
       System.out.printf("Area is %.1f * %.1f = %.2f", width, height, area);    
   }
}
   


 
 
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




W02 Programming Assignments 1

Due on 2025-08-07, 23:59 IST

Write a Java program to calculate the area of a rectangle.

The formula for area is:
Area = length × width

You are required to read the length and width from the user, compute the area, and print the result.

This task helps you practice using variables, arithmetic operations, and printing output in Java.

Your last recorded submission was on 2025-08-01, 16:57 IST
Select the Language for this assignment. 
File name for this program : 
import java.util.Scanner;
 
public class W02_P1 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
 
        // Read length and width of the rectangle
        int length = sc.nextInt();
        int width = sc.nextInt();
// ================================================
        // NOTE TO STUDENTS:
        // This is a simple beginner-level task.
        // Your role is to calculate the area using the given length and width.
        // Complete the line below using the correct formula.
        // ================================================
 
        // TODO: Calculate area of the rectangle
 
        /*
         Hint:
         - Multiply length and width to get the area
         - Store the result in a variable called 'area'
         */
int area = length * width;
// Print the area
        System.out.print("Area is: " + area);
 
        sc.close();
    }
}
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
5
10
Area is: 50
Area is: 50
Passed



W02 Programming Assignments 2

Due on 2025-08-07, 23:59 IST

Problem Statement

Write a Java program to calculate the perimeter of a rectangle.

The formula for perimeter is:
Perimeter = 2 multiplied by (length + width)

You are required to read the length and width as integers from the user, compute the perimeter, and print the result.

This problem helps in practicing arithmetic operations and output printing in Java.

Your last recorded submission was on 2025-08-01, 16:59 IST
Select the Language for this assignment. 
File name for this program : 
import java.util.Scanner;
 
public class W02_P2 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
 
        // Read length and width of the rectangle
        int length = sc.nextInt();
        int width = sc.nextInt();
// Complete the code to calculate the perimeter of the rectangle
        // TODO: Calculate the perimeter using the correct formula
        /*
         Hint:
         The formula is: perimeter = 2 multiplied by (length + width)
         */
int perimeter = 2 * (length + width);
System.out.println("Perimeter is: " + perimeter);
 
        sc.close();
    }
}
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
4  
6
Perimeter is: 20
Perimeter is: 20\n
Passed after ignoring Presentation Error



W02 Programming Assignments 3

Due on 2025-08-07, 23:59 IST

Finding the Maximum Element in an Array


Problem Statement

What is the Maximum Element?
In an array of numbers, the maximum is the largest number among all elements.

In this assignment:

  • You will read n numbers from the user

  • Store them in an array

  • Find the largest number among them

  • Print the maximum number

This task helps you apply loops and arrays together to solve a real logic-based problem.

Your last recorded submission was on 2025-08-01, 17:00 IST
Select the Language for this assignment. 
File name for this program : 
import java.util.Scanner;
 
public class W02_P3 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
 
        int n = sc.nextInt();
        int[] arr = new int[n];
 
        // Read n numbers into array
        for (int i = 0; i < n; i++) {
            arr[i] = sc.nextInt();
        }
 
        int max = arr[0];  // Assume first element is maximum
// TODO: Use a loop to find maximum element
        /*
         Hint:
         Start loop from index 1 to n - 1
         Compare each element with max
         If element is greater, update max
         */
for (int i = 1; i < n; i++) {
  if (arr[i] > max) {
    max = arr[i];
  }
}
System.out.println("Maximum is: " + max);
 
        sc.close();
    }
}
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
5  
15 42 9 28 37
Maximum is: 42
Maximum is: 42\n
Passed after ignoring Presentation Error



W02 Programming Assignments 4

Due on 2025-08-07, 23:59 IST

Create a Class and Access Its Member Variable


Problem Statement

In this task, you will practice creating and using a class in Java.

You need to:

  1. Create a class called Rectangle

  2. Declare two integer member variables length and width

  3. In the main method, create an object of the Rectangle class, assign values to length and width, and print their sum

This problem helps you understand how to define a class, create objects, and access class members in Java.

Your last recorded submission was on 2025-08-01, 17:01 IST
Select the Language for this assignment. 
File name for this program : 
import java.util.Scanner;
 
public class W02_P4 {
 
    // Declare a class named Rectangle
    static class Rectangle {
        int length;
        int width;
    }
 
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
 
        // Read length and width
        int l = sc.nextInt();
        int w = sc.nextInt();
 
        // Create an object of the Rectangle class
        Rectangle rect = new Rectangle();
 
        // Assign values to the object's member variables
        rect.length = l;
        rect.width = w;
// Complete the code to print the sum of length and width
        // TODO: Print the sum using rect.length and rect.width
        /*
         Hint:
         Use: rect.length + rect.width to get the sum
         Print the result using System.out.println
         tip--System.out.println("Sum of length and width is: " +.....)
         */
System.out.println("Sum of length and width is: " + (rect.length + rect.width));
sc.close();
    }
}
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
5  
10
Sum of length and width is: 15
Sum of length and width is: 15\n
Passed after ignoring Presentation Error



W02 Programming Assignments 5

Due on 2025-08-07, 23:59 IST

Working with Multiple Classes, Constructors, and the this Keyword


Problem Statement

In this task, you will learn how to:

  • Declare multiple classes in the same Java program

  • Use constructors to initialize values

  • Apply the this keyword to refer to instance variables

What you need to do:

  1. Declare a class called Circle with one member variable radius

  2. Write a constructor for Circle that takes radius as a parameter and assigns it using the this keyword

  3. In the main method, create an object of Circle and print its radius

This task helps understand how classes work together and how constructors and the this keyword are used for clarity.


Your last recorded submission was on 2025-08-01, 17:02 IST
Select the Language for this assignment. 
File name for this program : 
import java.util.Scanner;
 
public class W02_P5 {
 
    // Declare a separate class named Circle
    static class Circle {
 
        int radius;
// TODO: Write a constructor that takes radius as parameter
        // Use the 'this' keyword to assign the value to the member variable
        /*
         Hint:
         The constructor name should be Circle
         Use: this.radius = radius;
         */
public Circle(int radius) {
  this.radius = radius;
}
}
 
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
 
        // Read radius value from user
        int r = sc.nextInt();
 
        // Create an object of Circle class using constructor
        Circle c = new Circle(r);
 
        // Print the radius using object member
        System.out.println("Radius of the circle is: " + c.radius);
 
        sc.close();
    }
}
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
7
Radius of the circle is: 7
Radius of the circle is: 7\n
Passed after ignoring Presentation Error





W06 Programming Assignments 1

Due on 2025-09-04, 23:59 IST

Safe Division with Run-time Error Handling


Problem Statement

In Java, some operations can cause run-time errors, for example dividing a number by zero.
We can use a try-catch block to handle such errors and avoid program crashes.

Task:

  • Read two integers from the user

  • Divide the first number by the second inside a try-catch block

  • If the second number is zero, print "Cannot divide by zero"

  • Otherwise, print the result

This task introduces basic run-time error handling in a safe and controlled way.

Your last recorded submission was on 2025-08-30, 17:15 IST
Select the Language for this assignment. 
File name for this program : 
import java.util.Scanner;
 
public class W06_P1 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
 
        // Read two integers
        int num1 = sc.nextInt();
        int num2 = sc.nextInt();
 
        // Use try-catch to handle possible run-time error
        try {
int result = num1 / num2;
System.out.println("Result is: " + result);
} catch (ArithmeticException e) {
            // Print safe message if division by zero occurs
            System.out.println("Cannot divide by zero");
        }
 
        sc.close();
    }
}
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
10  
0
Cannot divide by zero
Cannot divide by zero\n
Passed after ignoring Presentation Error
Test Case 2
10  
2
Result is: 5
Result is: 5\n
Passed after ignoring Presentation Error



W06 Programming Assignments 2

Due on 2025-09-04, 23:59 IST

Programming Assignment: Nested try-catch Block


Problem Statement

In Java, nested try-catch blocks allow handling multiple levels of errors separately.
You can place one try-catch block inside another to handle different types of errors in different places.

Programming Assignment:

  • Read two integers from the user

  • Inside an outer try-catch block, perform the following:

    • Inside a nested try block, divide the first number by the second

    • If division by zero occurs, handle it with the inner catch block

  • In the outer catch block, handle any other unexpected errors

  • Print appropriate messages for each scenario

This programming assignment introduces nested try-catch structure.

Your last recorded submission was on 2025-08-30, 17:17 IST
Select the Language for this assignment. 
File name for this program : 
import java.util.Scanner;
 
public class W06_P2 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
 
        // Read two integers
        int num1 = sc.nextInt();
        int num2 = sc.nextInt();
 
        // Outer try-catch block
        try {
 
            // Inner try-catch block for division operation
            try {
int result = num1 / num2;
System.out.println("Division successful");
System.out.println("Result is: " + result);
} catch (ArithmeticException e) {
                System.out.println("Cannot divide by zero");
            }
 
        } catch (Exception e) {
            // Handles other unexpected errors
            System.out.println("An unexpected error occurred");
        }
 
        sc.close();
    }
}
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
10  
2
Division successful\n
Result is: 5
Division successful\n
Result is: 5\n
Passed after ignoring Presentation Error



W06 Programming Assignments 3

Due on 2025-09-04, 23:59 IST

Programming Assignment: try Block with Multiple catch Blocks


Problem Statement

In Java, a try block can be followed by multiple catch blocks to handle different types of errors separately.

This improves error handling by allowing specific actions for different exceptions.

Key Concepts:

  • The first matching catch block handles the error

  • Catch blocks are written in order from most specific to general

Programming Assignment:

  • Read two integers from the user

  • Inside a try block, divide the first number by the second

  • Handle ArithmeticException separately to detect division by zero

  • Handle any other general errors using another catch block

  • Print suitable messages based on the type of error

This demonstrates structured error handling with multiple catch blocks.

Your last recorded submission was on 2025-08-30, 17:19 IST
Select the Language for this assignment. 
File name for this program : 
import java.util.Scanner;
 
public class W06_P3 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
 
        // Read two integers
        int num1 = sc.nextInt();
        int num2 = sc.nextInt();
 
        // Try block with multiple catch blocks
        try {
// TODO: Perform division and print result if successful
            int result = num1 / num2;
            System.out.println("Division successful");
            System.out.println("Result is: " + result);
} catch (ArithmeticException e) {
            // Handles division by zero error
            System.out.println("Cannot divide by zero");
        } catch (Exception e) {
            // Handles other general errors
            System.out.println("An unexpected error occurred");
        }
 
        sc.close();
    }
}
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
20  
4
Division successful\n
Result is: 5
Division successful\n
Result is: 5\n
Passed after ignoring Presentation Error



W06 Programming Assignments 4

Due on 2025-09-04, 23:59 IST

Programming Assignment: Using finally in try-catch Block


Problem Statement

In Java, the finally block is a special part of error handling.

What is finally?

  • The code inside a finally block always runs, whether there is an error or not

  • It is usually used to close resources like files, database connections, or simply to show a message

Programming Assignment:

  • Read two integers from the user

  • Inside a try block, divide the first number by the second

  • If division by zero occurs, show an error message using catch block

  • Use a finally block to print "Program Ended" no matter what happens

This helps you understand how finally block always runs in a program.

Your last recorded submission was on 2025-08-30, 17:21 IST
Select the Language for this assignment. 
File name for this program : 
import java.util.Scanner;
 
public class W06_P4 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
 
        // Read two integers
        int num1 = sc.nextInt();
        int num2 = sc.nextInt();
 
        // try-catch-finally structure
        try {
// TODO: Perform division and print result
            int result = num1 / num2;
            System.out.println("Result is: " + result);
} catch (ArithmeticException e) {
            System.out.println("Cannot divide by zero");
        } finally {
            // Print final message, runs always
            System.out.println("Program Ended");
        }
 
        sc.close();
    }
}
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
15  
3
Result is: 5\n
Program Ended
Result is: 5\n
Program Ended\n
Passed after ignoring Presentation Error



W06 Programming Assignments 5

Due on 2025-09-04, 23:59 IST

Programming Assignment: Using throws Statement for Error Handling


Problem Statement

In Java, the throws keyword is used when a method might cause an error, but the method itself does not handle it.
Instead, it passes the responsibility to the caller of the method.

Why use throws?

  • Some methods may cause errors called "checked exceptions"

  • Instead of handling the error inside the method, we declare throws to inform the caller

Programming Assignment:

  • Create a method called calculateSquareRoot

  • The method reads a number and returns its square root

  • If the number is negative, it throws an Exception

  • In the main method, use a try-catch block to handle the error

This demonstrates how to use throws and handle errors safely in the caller method.

Your last recorded submission was on 2025-08-30, 17:23 IST
Select the Language for this assignment. 
File name for this program : 
import java.util.Scanner;
 
public class W06_P5 {
 
    // Method to calculate square root, may throw Exception
    public static double calculateSquareRoot(double num) throws Exception {
// TODO: Throw Exception if number is negative
        if (num < 0) {
            throw new Exception("Number cannot be negative");
        }
        return Math.sqrt(num);
}
 
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
 
        double number = sc.nextDouble();
 
        try {
            double result = calculateSquareRoot(number);
            System.out.println("Square root is: " + result);
        } catch (Exception e) {
            System.out.println("Cannot calculate square root of negative number");
        }
 
        sc.close();
    }
}
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
16
Square root is: 4.0
Square root is: 4.0\n
Passed after ignoring Presentation Error






W08 Programming Assignments 1

Due on 2025-09-18, 23:59 IST

Creating a Thread using Thread Class


Problem Statement

In Java, you can run multiple tasks at the same time using Multithreading.
The simplest way to create a thread is by extending the built-in Thread class.

What is a Thread?

  • A thread is a small unit of a program that runs independently

  • Multiple threads can run in parallel, improving efficiency

Programming Assignment:

  • Create a class called MyThread that extends Thread

  • In its run() method, print "Thread is running"

  • In the main method, create an object of MyThread and start the thread

This helps you understand the basic way to create and start a thread in Java.

Your last recorded submission was on 2025-09-15, 21:28 IST
Select the Language for this assignment. 
File name for this program : 
public class W08_P1 {
 
    // Create a class that extends Thread
    static class MyThread extends Thread {
 
        @Override
        public void run() {
System.out.print("Thread is running");
}
    }
 
    public static void main(String[] args) {
 
        // Create object of MyThread
        MyThread t = new MyThread();
 
        // Start the thread
        t.start();
    }
}
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
NA
Thread is running
Thread is running
Passed



W08 Programming Assignments 2

Due on 2025-09-18, 23:59 IST

Creating a Thread using Runnable Interface


Problem Statement

In Java, another common way to create threads is by implementing the Runnable interface.

What is Runnable?

  • Runnable is an interface with a single method called run()

  • You can pass a Runnable object to a Thread and start the thread

Why use Runnable?

  • It allows your class to extend another class, as Java supports single inheritance

  • It provides flexibility in thread creation

Programming Assignment:

  • Create a class called MyRunnable that implements Runnable

  • In its run() method, print "Runnable thread is running"

  • In the main method, create a Thread object using MyRunnable and start the thread

This demonstrates thread creation using the Runnable interface.

Your last recorded submission was on 2025-09-15, 21:29 IST
Select the Language for this assignment. 
File name for this program : 
public class W08_P2 {
 
    // Create a class that implements Runnable interface
    static class MyRunnable implements Runnable {
 
        @Override
        public void run() {
System.out.print("Runnable thread is running");
}
    }
 
    public static void main(String[] args) {
 
        // Create object of MyRunnable
        MyRunnable r = new MyRunnable();
 
        // Create Thread using Runnable object
        Thread t = new Thread(r);
 
        // Start the thread
        t.start();
    }
}
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
NA
Runnable thread is running
Runnable thread is running
Passed



W08 Programming Assignments 3

Due on 2025-09-18, 23:59 IST

Programming Assignment: Understanding Basic Thread States in Java


Problem Statement

When a thread runs in Java, it moves through different stages called states.

What are Thread States?
Think of a thread like a person:

  • It starts in one state

  • Moves to another as work happens

  • Finally, it finishes

For beginners, focus on these three simple states:

  1. New – The thread is created but not started yet

  2. Running – The thread is doing its work

  3. Terminated – The thread has finished its work

Programming Assignment:

  • Create a class called MyThread that extends Thread

  • Inside its run() method, print "Thread is running"

  • In the main method:

    • Create a MyThread object

    • Print "Thread state before start"

    • Start the thread

    • Print "Thread state after start"

    • Wait for thread to finish using join()

    • Print "Thread state after completion"

This shows how thread state changes as the thread runs.

Your last recorded submission was on 2025-09-15, 21:32 IST
Select the Language for this assignment. 
File name for this program : 
public class W08_P3 {
 
    // Create a class that extends Thread
    static class MyThread extends Thread {
 
        @Override
        public void run() {
System.out.println("Thread is running");
}
    }
 
    public static void main(String[] args) {
 
        // Create thread object
        MyThread t = new MyThread();
 
        // Thread is created but not started yet
        System.out.println("Thread state before start");
 
        // Start thread
        t.start();
 
        // Thread has started running
        System.out.println("Thread state after start");
 
        try {
            // Wait for thread to finish
            t.join();
        } catch (InterruptedException e) {
            // Not needed for beginners, but required to handle possible interruptions
        }
 
        // Thread has finished
        System.out.println("Thread state after completion");
    }
}
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
NA
Thread state before start\n
Thread state after start\n
Thread is running\n
Thread state after completion
Thread state before start\n
Thread state after start\n
Thread is running\n
Thread state after completion\n
Passed after ignoring Presentation Error



W08 Programming Assignments 4

Due on 2025-09-18, 23:59 IST

Understanding Thread Priority in Java


Problem Statement

In Java, each thread has a priority, a number from 1 (lowest) to 10 (highest).
Priority suggests how important a thread is, though actual scheduling depends on the system.

Programming Assignment:

  • Create a class MyThread that extends Thread

  • In the main method:

    • Create a MyThread object

    • Set its priority to 8

    • Start the thread

    • Print the thread's priority after setting

No output should come from the thread's run() method to avoid output mismatch.

Your last recorded submission was on 2025-09-15, 21:38 IST
Select the Language for this assignment. 
File name for this program : 
public class W08_P4 {
 
    // Thread class
    static class MyThread extends Thread {
 
        @Override
        public void run() {
            // No output here to keep portal testing consistent
        }
    }
 
    public static void main(String[] args) {
 
        MyThread t = new MyThread();
 
        // Set thread priority
        t.setPriority(8);
 
        // Start thread
        t.start();
System.out.print("Thread priority is: " + t.getPriority());
}
}
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
NA
Thread priority is: 8
Thread priority is: 8
Passed



W08 Programming Assignments 5

Due on 2025-09-18, 23:59 IST

Programming Assignment: Introduction to Thread Synchronization


Problem Statement

What is a Thread?
Imagine your computer doing many tasks at once — for example:

  • Playing music

  • Downloading files

  • Browsing the internet

In Java, each small task that runs independently is called a Thread.
Threads help programs run faster by working at the same time.

Why Synchronization?
When multiple threads work on the same thing together, they may interfere with each other.
For example:

  • Two threads try to update the same number at the same time

  • The final result may be wrong

What is Synchronization?

  • It is like putting a lock

  • Only one thread can work on the shared thing at a time

  • This prevents problems caused by threads disturbing each other


Programming Assignment:

  • Create a class Counter with a number count starting from 0

  • Write a method increment() to increase the number by 1, using synchronized keyword

  • Create a thread class called MyThread that runs the increment() method 1000 times

  • In main, run two threads to increase the number

  • After both threads finish, print the final count

This shows how to use synchronization to avoid problems when multiple threads share data.

Your last recorded submission was on 2025-09-15, 21:40 IST
Select the Language for this assignment. 
File name for this program : 
public class W08_P5 {
 
    // Shared class with a number
    static class Counter {
        int count = 0;
 
        // Synchronized method to safely increase number
        public synchronized void increment() {
            count++;
        }
    }
 
    // Thread class to run increment
    static class MyThread extends Thread {
        Counter c;
 
        MyThread(Counter c) {
            this.c = c;
        }
 
        @Override
        public void run() {
for (int i = 0; i < 1000; i++) {
                c.increment();
            }
}
    }
 
    public static void main(String[] args) {
 
        Counter c = new Counter();
 
        // Create two threads
        MyThread t1 = new MyThread(c);
        MyThread t2 = new MyThread(c);
 
        // Start both threads
        t1.start();
        t2.start();
 
        try {
            // Wait for both threads to finish
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
        }
 
        // Print final count
        System.out.println("Final count is: " + c.count);
    }
}
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
NA
Final count is: 2000
Final count is: 2000\n
Passed after ignoring Presentation Error

Week 09 : Programming Assignment 1

Due on 2025-09-25, 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. An example is shown below:

INPUT:
               00001
               00001
               00001
               00001
               00001

OUTPUT:
               11110
               11110
               11110
               11110
               11110

Note the following points carefully
:
1. Here, the input must contain only 0 and 1.

2. The input and output array size must be of dimension 5 × 5.
3. Flip-Flop: If 0 then 1 and vice-versa.

Your last recorded submission was on 2025-09-20, 13:54 IST
Select the Language for this assignment. 
File name for this program : 
import java.util.Scanner;
public class W09_P1{
    public static void main(String args[]){
        Scanner sc = new Scanner(System.in);
        int[][] matrix = new int[5][5];
        for (int i = 0; i < 5; i++) {
            String row = sc.next();
            for (int j = 0; j < 5; j++) {
                matrix[i][j] = Character.getNumericValue(row.charAt(j));
            }
        }
        for (int i = 0; i < 5; i++) {
            for (int j = 0; j < 5; j++) {
                if (matrix[i][j] == 0) {
                    matrix[i][j] = 1;
                }
                else {
                    matrix[i][j] = 0;
                }
            }
        }
        for (int i = 0; i < 5; i++) {
            for (int j = 0; j < 5; j++) {
                System.out.print(matrix[i][j]);
            }
            System.out.println();
        }
} // The main() ends here
} // The main class ends here
   


 
 
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 09 : Programming Assignment 2

Due on 2025-09-25, 23:59 IST

Complete the code to develop a BASIC CALCULATOR that can perform operations like AdditionSubtractionMultiplication and Division.

Note the following points carefully
:
1. Use only 
double datatype to store calculated numeric values.
2. Assume input to be of 
integer datatype.
3. The output should be rounded using 
Math.round() method.
4. Take care of the spaces during formatting output (e.g., single space each before and after =).
5. The calculator should be able to perform required operations on a minimum of two operands as shown in the below example:


Input:
                       5+6 

Output:
                       5+6 = 11


Your last recorded submission was on 2025-09-20, 13:57 IST
Select the Language for this assignment. 
File name for this program : 
import java.util.Scanner;
public class W09_P2{
    public static void main(String args[]){
        Scanner sc = new Scanner(System.in);
        String input = sc.nextLine(); // Read as string, e.g., 5+6
String[] parts;
        char operator = ' ';
        double result = 0.0;
        if (input.contains("+")) {
            parts = input.split("\\+");
            operator = '+';
        } else if (input.contains("-")) {
            parts = input.split("-");
            operator = '-';
        } else if (input.contains("*")) {
            parts = input.split("\\*");
            operator = '*';
        } else if (input.contains("/")) {
            parts = input.split("/");
            operator = '/';
        } else {
            return;
        }
        int operand1 = Integer.parseInt(parts[0].trim());
        int operand2 = Integer.parseInt(parts[1].trim());
        switch (operator) {
            case '+':
                result = (double) operand1 + operand2;
                break;
            case '-':
                result = (double) operand1 - operand2;
                break;
            case '*':
                result = (double) operand1 * operand2;
                break;
            case '/':
                if (operand2 != 0) {
                    result = (double) operand1 / operand2;
                }
                break;
        }
        long roundedResult = Math.round(result);
        System.out.println(input + " = " + roundedResult);
} // The main() method ends here
} // The main class ends here
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
5+6
5+6 = 11
5+6 = 11\n
Passed after ignoring Presentation Error



Week 09 : Programming Assignment 3

Due on 2025-09-25, 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 2025-09-20, 14:01 IST
Select the Language for this assignment. 
File name for this program : 
import java.util.Scanner;
 
class SquareThread extends Thread {
    private int begin;
    private int end;
    private static final Object lock = new Object();
    public SquareThread(int begin, int end) {
        this.begin = begin;
        this.end = end;
    }
    public void run() {
        synchronized (SquareThread.lock) {
            if (begin > end) {
                for (int i = begin; i >= end; i--) {
                    System.out.println(i * i);
                }
            }
            else {
                for (int i = begin; i <= end; i++) {
                    System.out.println(i * i);
                }
            }
        }
    }
}
 
public class W09_P3 {
    public static void main(String args[]) {
        Scanner scanner = new Scanner(System.in);
        //System.out.print("Enter the begin for square calculation: ");
        int begin = scanner.nextInt();
        //System.out.print("Enter the end for square calculation: ");
        int end = scanner.nextInt();
        scanner.close();
 
        SquareThread thread1 = new SquareThread(begin, end);
        SquareThread thread2 = new SquareThread(end, begin);
 
        thread1.start();
        thread2.start();
    }
}
   


 
 
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 09 : Programming Assignment 4

Due on 2025-09-25, 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 2025-09-20, 14:12 IST
Select the Language for this assignment. 
File name for this program : 
import java.io.*;  
class W09_P4{  
        public static void main(String args[]){
        try{
                InputStreamReader r=new InputStreamReader(System.in);  
                BufferedReader br=new BufferedReader(r);  
                String number=br.readLine();  
                int x = Integer.parseInt(number);
                System.out.println(x*x);
            } catch (Exception e) {
                System.out.println("Please enter valid data");
            }
} // The main() ends here
} // The main class ends here
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
2
4
4\n
Passed after ignoring Presentation Error
Test Case 2
p
Please enter valid data
Please enter valid data\n
Passed after ignoring Presentation Error



Week 09 : Programming Assignment 5

Due on 2025-09-25, 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 2025-09-20, 14:04 IST
Select the Language for this assignment. 
File name for this program : 
import java.util.Scanner;
 
public class W09_P5{
            
    public static void main(String[] args) {
 
        Scanner sc = new Scanner(System.in);
        double x1 = sc.nextDouble();
        double y1 = sc.nextDouble();
        double x2 = sc.nextDouble();
        double y2 = sc.nextDouble();
        Point p1 = new Point(x1, y1);
        Point p2 = new Point(x2, y2);
        
        System.out.print(p1.distance(p2));
    }
 
}
class Point{
    private double x;
    private double y;
    public Point(double x, double y){
        this.x = x;
        this.y = y;
    }
    public double distance(Point p2){
        double dist;
        dist = Math.sqrt(Math.pow((p2.x-x),2) + Math.pow((p2.y-y),2));
        return dist;
    }
}
   


 
 
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





netaji gandi Monday, August 11, 2025
INTRODUCTION TO PROGRAMMING 2025-26 VR23
Introduction to Programming Syllabus
INTRODUCTION TO PROGRAMMING
Common to all branches of Engineering
I Year – I Semester  |  Code: 1005231101
Course Objectives:
  1. 1. Impart in-depth knowledge on the need of programming languages, problem-solving techniques, and program development skills.
  2. 2. Enable effective use of control structures and implement different operations on arrays.
  3. 3. Demonstrate the use of strings and functions.
  4. 4. Impart knowledge of pointers and memory allocation principles in C.
  5. 5. Understand structures, unions, and perform file operations in C.
Course Outcomes:
  • CO1: Illustrate fundamental concepts of computers and basics of computer programming.
  • CO2: Demonstrate control structures, branching, and looping statements.
  • CO3: Demonstrate arrays and pointers in solving complex problems.
  • CO4: Develop modular programs using functions and strings.
  • CO5: Demonstrate user-defined data types, solve real-world problems using structures, unions, and file operations.
UNIT I – Introduction to Computer Problem Solving
Programs and Algorithms, Problem Solving Requirements & Strategies
  • Programs and Algorithms, Computer Problem Solving Requirements, Phases of Problem Solving, Problem Solving Strategies, Top-Down Approach, Algorithm Designing, Program Verification, Improving Efficiency, Algorithm Analysis and Notations.
UNIT II – Introduction to C Programming
C Program Structure, Comments, Keywords, Variables, Data Types
  • Introduction, Structure of a C Program, Comments, Keywords, Identifiers, Data Types, Variables, Constants, Input/output Statements. Operators, Type Conversion. Control Flow, Relational Expressions: Conditional Branching Statements: if, if-else, if-else—if, switch. Basic Loop Structures: while, do-while loops, for loop, nested loops, The Break and Continue Statements, goto statement.
UNIT III – Arrays
One-Dimensional and Multi-Dimensional Arrays, Pointers
  • Introduction, Operations on Arrays, Arrays as Function Arguments, Two Dimensional Arrays, Multidimensional Arrays. Pointers: Concept of a Pointer, Declaring and Initializing Pointer Variables, Pointer Expressions and Address Arithmetic, Null Pointers, Generic Pointers, Pointers as Function Arguments, Pointers and Arrays, Pointer to Pointer, Dynamic Memory Allocation, Dangling Pointer, Command Line Arguments.
UNIT IV – Functions
Function Declaration, Recursion, Scope, Storage Classes
  • Introduction Function: Declaration, Function Definition, Function Call, Categories of Functions, Passing Parameters to Functions, Scope of Variables, Variable Storage Classes. Recursion. Strings: String Fundamentals, String Processing with and without Library Functions, Pointers and Strings.
UNIT V – Structures and Files
Bit Fields, Nested Structures, Arrays of Structures, Unions, Self-Referential Structures
  • Structures, Unions, Bit Fields: Introduction, Nested Structures, Arrays of Structures, Structures and Functions, Self-Referential Structures, Unions, Enumerated Data Type —Enum variables, Using Typedef keyword, Bit Fields. Data Files: Introduction to Files, Using Files in C, Reading from Text Files, Writing to Text Files, Random File Access.
Textbooks
  • A Structured Programming Approach Using C, Forouzan & Gilberg, Cengage.
  • How to Solve it by Computer, R.G. Dromey, Pearson.
  • Programming in C: A Practical Approach, Ajay Mittal, Pearson.
References
  • Byron Gottfried, Schaum’s Outline of Programming with C, McGraw-Hill.
  • Reema Thareja, Computer Programming, Oxford University Press.
  • The C Programming Language, Kernighan & Ritchie, Pearson.
Web Resources

netaji gandi Thursday, August 7, 2025
COMPUTER PROGRAMMING LAB 2025-26
Computer Programming Lab 2025-26

COMPUTER PROGRAMMING LAB 2025-26 (Common to All branches of Engineering)

(I Year– I Semester - Course Code (1005231110) VR-23)

 COMPUTER PROGRAMMING LAB 2025-26

(Common to All branches of Engineering)

I Year– I Semester 

Course Code (1005231110)

VR-23

Course Objectives:
The course aims to give students hands-on experience and train them on the concepts of the C programming language.

Course Outcomes:
CO1: Read, understand, and trace the execution of programs written in the C language. (Understand)
CO2: Apply the right control structure for solving the problem. (Apply)
CO3: Develop, Debug and Execute programs to demonstrate the applications of arrays, functions, pointers and files in C. (Apply)
CO4: Improve individual/teamwork skills, communication and report writing skills with ethical values



UNIT I

WEEK 1  Click Link for Lab Notes


SAMPLE PROGRAMS

Objective: Getting familiar with the programming environment on the computer and writing the first program.

Suggested Experiments/Activities:

Tutorial 1: Problem-solving using Computers.
Lab 1: Familiarization with programming environment
i) Basic Linux environment and its editors like Vi, Vim & Emacs etc.
ii) Exposure to Turbo C, gcc
iii) Writing simple programs using printf() and scanf()


WEEK 2 Click Link for Lab Notes

Objective: Getting familiar with how to formally describe a solution to a problem in a series of finite steps both using textual notation and graphic notation.
Suggested Experiments /Activities:
Tutorial 2: Problem-solving using Algorithms and Flow charts.
Lab 1: Converting algorithms/flow charts into C Source code.
Developing the algorithms/flowcharts for the following sample programs
i) Sum and average of 3 numbers
ii) Conversion of Fahrenheit to Celsius and vice versa
iii) Simple interest calculation

WEEK 3 Click Link for Lab Notes Link2

Objective: Learn how to define variables with the desired data-type, initialize them with appropriate values and how arithmetic operators can be used with variables and constants.
Suggested Experiments/Activities:
Tutorial 3: Variable types and type conversions:
Lab 3: Simple computational problems using arithmetic expressions.
i) Finding the square root of a given number
ii) Finding compound interest
iii) Area of a triangle using heron’s formulae
iv) Distance travelled by an object

UNIT II


WEEK 4 Click Link for Lab Notes     LINK2

Objective: Explore the full scope of expressions, type-compatibility of variables &constants and operators used in the expression and how operator precedence works.
Suggested Experiments/Activities:
Tutorial4: Operators and the precedence and as associativity:
Lab4: Simple computational problems using the operator’ precedence and associativity
i) Evaluate the following expressions.
a. A+B*C+(D*E) + F*G
b. A/B*C-B+A*D/3
c. A+++B---A
d. J= (i++) + (++i)
ii) Find the maximum of three numbers using conditional operator
iii) Take marks of 5 subjects in integers, and find the total, average in float

WEEK 5 Click Link for Lab Notes

Objective: Explore the full scope of different variants of “if construct” namely if- else, null- else, if-else if*-else, switch and nested-if including in what scenario each one of them can be used and how to use them. Explore all relational and logical operators while writing conditionals for “if construct”.
Suggested Experiments/Activities:
Tutorial 5: Branching and logical expressions:
Lab 5: Problems involving if-then-else structures.
i) Write a C program to find the max and min of four numbers using if-else.
ii) Write a C program to generate electricity bill.
iii) Find the roots of the quadratic equation.
iv) Write a C program to simulate a calculator using switch case.
v) Write a C program to find the given year is a leap year or not.

WEEK 6  Click Link for Lab Notes

Objective: Explore the full scope of iterative constructs namely while loop, do-while loop and for loop in addition to structured jump constructs like break and continue including when each of these statements is more appropriate to use.
Suggested Experiments/Activities:
Tutorial 6: Loops, while and for loops
Lab 6: Iterative problems e.g., the sum of series
i) Find the factorial of given number using any loop.
ii) Find the given number is a prime or not.
iii) Compute sine and cos series
iv) Checking a number palindrome
v) Construct a pyramid of numbers.

UNIT III

WEEK 7:  Click Link for Lab Notes

Objective: Explore the full scope of Arrays construct namely defining and initializing 1-D and 2-D and more generically n-D arrays and referencing individual array elements from the defined array. Using integer 1-D arrays, explore the search solution linear search.
Suggested Experiments/Activities:
Tutorial 7: 1 D Arrays: searching.
Lab 7: 1D Array manipulation, linear search
i) Find the min and max of a 1-D integer array.
ii) Perform linear search on1D array.
iii) The reverse of a 1D integer array
iv) Find 2’s complement of the given binary number.
v) Eliminate duplicate elements in an array.

WEEK 8:

Objective: Explore the difference between other arrays and character arrays that can be used as Strings by using null character and get comfortable with string by doing experiments that will reverse a string and concatenate two strings. Explore sorting solution bubble sort using integer arrays.
Suggested Experiments/Activities:
Tutorial 8: 2 D arrays, sorting and Strings.
Lab 8: Matrix problems, String operations, Bubble sort
i) Addition of two matrices
ii) Multiplication two matrices
iii) Sort array elements using bubble sort
iv) Concatenate two strings without built-in functions
v) Reverse a string using built-in and without built-in string functions

UNIT IV
WEEK 9:

Objective: Explore pointers to manage a dynamic array of integers, including memory allocation & value initialization, resizing changing and reordering the contents of an array and memory de-allocation using malloc (), calloc (), realloc () and free () functions. Gain experience processing command-line arguments received by C
Suggested Experiments/Activities:
Tutorial 9: Pointers, structures and dynamic memory allocation
Lab 9: Pointers and structures, memory dereference.
i) Write a C program to find the sum of a 1D array using malloc()
ii) Write a C program to find the total, average of n students using structures
iii) Enter n students data using calloc() and display failed students list
iv) Read student name and marks from the command line and display the student
details along with the total.
v) Write a C program to implement realloc()

WEEK 10:

Objective: Experiment with C Structures, Unions, bit fields and self-referential structures (Singly linked lists) and nested structures
Suggested Experiments/Activities:
Tutorial 10: Bitfields, Self-Referential Structures, Linked lists
Lab10 : Bitfields, linked lists
Read and print a date using dd/mm/yyyy format using bit-fields and differentiate the same without using bit- fields
i) Create and display a singly linked list using self-referential structure.
ii) Demonstrate the differences between structures and unions using a C program.
iii) Write a C program to shift/rotate using bitfields.
iv) Write a C program to copy one structure variable to another structure of the same type.

UNIT V
WEEK 11: CLICK LINK FOR LAB NOTES

Objective: Explore the Functions, sub-routines, scope and extent of variables, doing some experiments by parameter passing using call by value. Basic methods of numerical integration.
Suggested Experiments/Activities:
Tutorial 11: Functions, call by value, scope and extent,
Lab 11: Simple functions using call by value, solving differential equations
using Eulers theorem.
i) Write a C function to calculate NCR value.
ii) Write a C function to find the length of a string.
iii) Write a C function to transpose of a matrix.
iv) Write a C function to demonstrate numerical integration of differential equations
using Euler’s method

WEEK 12: Click Link for Lab Notes

Objective: Explore how recursive solutions can be programmed by writing recursive functions that can be invoked from the main by programming at-least five distinct problems that have naturally recursive solutions.
Suggested Experiments/Activities:
Tutorial 12: Recursion, the structure of recursive calls
Lab 12: Recursive functions
i) Write a recursive function to generate the Fibonacci series.
ii) Write a recursive function to find the lcm of two numbers.
iii) Write a recursive function to find the factorial of a number.
iv) Write a C Program to implement the Ackermann function using recursion.
v) Write a recursive function to find the sum of the series.

WEEK 13: Click Link for Lab Notes

Objective: Explore the basic difference between normal and pointer variables, Arithmetic operations using pointers and passing variables to functions using pointers
Suggested Experiments/Activities:
Tutorial 13: Call by reference, dangling pointers
Lab 13: Simple functions using Call by reference, Dangling pointers.
i) Write a C program to swap two numbers using call by reference.
ii) Demonstrate Dangling pointer problem using a C program.
iii) Write a C program to copy one string into another using pointer.
iv) Write a C program to find no of lowercase, uppercase, digits
and other characters using pointers.

WEEK14: Click Link for Lab Notes

Objective: To understand data files and file handling with various file I/O functions. Explore the differences between text and binary files.
Suggested Experiments/Activities:
Tutorial 14: File handling
Lab 14: File operations
i) Write a C program to write and read text into a file.
ii) Write a C program to write and read text into a binary file using fread() and fwrite()
iii) Copy the contents of one file to another file.
iv) Write a C program to merge two files into the third file using command-line arguments.
v) Find no. of lines, words and characters in a file
vi) Write a C program to print last n characters of a given file.

Textbooks:

1. Ajay Mittal, Programming in C: A practical approach, Pearson.
2. Byron Gottfried, Schaum&amp;'s Outline of Programming with C, McGraw Hill

Reference Books:

1. Brian W. Kernighan and Dennis M. Ritchie, The C Programming Language,
Prentice- Hall of India
2. C Programming, A Problem-Solving Approach, Forouzan, Gilberg, Prasad, CENGAGE



netaji gandi
C-Program-Development-Life-Cycle

 

Program Development Life Cycle


When we want to develop a program using any programming language, we follow a sequence of steps. These steps are called phases in program development. The program development life cycle is a set of steps or phases that are used to develop a program in any programming language.
Generally, the program development life cycle contains 6 phases, they are as follows….

  1. Problem Definition
  2. Problem Analysis
  3. Algorithm Development
  4. Coding & Documentation
  5. Testing & Debugging
  6. Maintenance

1. Problem Definition

In this phase, we define the problem statement and we decide the boundaries of the problem. In this phase we need to understand the problem statement, what is our requirement, what should be the output of the problem solution. These are defined in this first phase of the program development life cycle.

2. Problem Analysis

In phase 2, we determine the requirements like variables, functions, etc. to solve the problem. That means we gather the required resources to solve the problem defined in the problem definition phase. We also determine the bounds of the solution.

3. Algorithm Development

During this phase, we develop a step by step procedure to solve the problem using the specification given in the previous phase. This phase is very important for program development. That means we write the solution in step by step statements.

4. Coding & Documentation

This phase uses a programming language to write or implement the actual programming instructions for the steps defined in the previous phase. In this phase, we construct the actual program. That means we write the program to solve the given problem using programming languages like C, C++, Java, etc.,

5. Testing & Debugging

During this phase, we check whether the code written in the previous step is solving the specified problem or not. That means we test the program whether it is solving the problem for various input data values or not. We also test whether it is providing the desired output or not.

6. Maintenance

During this phase, the program is actively used by the users. If any enhancements found in this phase, all the phases are to be repeated to make the enhancements. That means in this phase, the solution (program) is used by the end-user. If the user encounters any problem or wants any enhancement, then we need to repeat all the phases from the starting, so that the encountered problem is solved or enhancement is added.




netaji gandi Tuesday, August 5, 2025
C Preprocessor

 

Introduction to C Preprocessor

The Preprocessor used in C is one of the important step which is used in the compilation process but it is not a part of the compiler. In simple terms, a preprocessor is system software or a program which process the source code before the compilation step.

C Program Compilation:

A C Preprocessor performs processing of source code or high-level language (HLL).
The first step in the language processing system is preprocessing. This language processing system converts the high-level language into a language that is easily understood by the machine, i.e., machine-level language.

The intermediate steps involved between writing a C program and it’s execution are shown in the figure above.

A preprocessor is primarily used for performing three tasks on high level language(HLL) code given below:

  1. Expanding macros: The preprocessor replaces occurrences of macro names with their corresponding definitions.
  2. Including files: The preprocessor inserts the contents of specified files into the source code at the point where the #include directive appears.
  3. Conditional compilation: The preprocessor can include or exclude parts of the source code based on specified conditions, using the #if, #ifdef, and #ifndef directives.
  4. Replacing constants: The preprocessor replaces occurrences of constants with their corresponding values, using the #define directive.

C Preprocessor Directives


All preprocessing directives begin with a hash symbol(#).

Some of the commonly used preprocessor directives are listed below:

DirectiveDescription
#defineThis directive substitutes a preprocessor macro.
#includeThis directive inserts a particular header from another file.
#undefThis directive undefines a preprocessor macro.
#ifdefThis directive returns true if this macro is defined.
#ifndefThis directive returns true if this macro is not defined.

Example


#include <stdio.h>
#define PI 3.1415

 int main () 
{
  
float r, a;
  
printf ("Enter the radius: ");
  
scanf ("%f", &r);
  
    // Notice, the use of PI
    a = PI * r * r;
  
 
printf ("Area=%.2f", a);
  
return 0;
}

Output


Enter the radius: 6
Area = 113.09

netaji gandi Friday, July 18, 2025
C Program to check if a Number Is Positive Or Negative

 

C Program to check if a Number Is Positive Or Negative



#include <stdio.h>
int main()
{
    int num = 23;
      
    //Conditions to check if the number is negative/positive or zero
    if (num > 0)
         printf("The number is positive");
    else if (num < 0)
        printf("The number is negative");
    else
        printf("Zero");
    
    return 0;
}                                                                                                                                                                                       

Output:

Insert a number: 23
The number is Positive                                                               
#include <stdio.h>
int main()
{
    int num = -10;
    
    //Condition to check if num is negative/positive or zero
    if (num >= 0)
    {
        if (num == 0)
            printf("The number is 0");
        else
            printf("The number is Positive");
    }
    else
        printf("The number is Negative");
    
    return 0;
}

Output

Insert a number: -10
The number is Negative
#include <stdio.h>
int main()
{
    int num = -4;
    
    //Condition to check if the 0, positive or negative
    
    if(num == 0)
        printf("Zero");
    else
        (num > 0) ? printf("Positive"): printf("Negative");
    
    return 0;
}
Insert a number: -4
Negative

netaji gandi Tuesday, July 15, 2025

Internship offering Organizations

 Internship offering Organizations https://www.iitg.ac.in/dsai/docs/flyer/sum_intern_call2026_iitg_dsai_details.pdf  https://www.indiascienc...