0% found this document useful (0 votes)
12 views34 pages

Coding Challenge( Kaalu)

The document contains a series of programming challenges and solutions in C, Python, SQL, HTML, CSS, JavaScript, and Java, aimed at students of Assam down town University. Each section includes specific tasks such as finding the second largest element in an array, creating a digital clock, and designing a registration form. Additionally, it showcases database queries for sales and product data, as well as object-oriented programming concepts in Java.

Uploaded by

penguin062422
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views34 pages

Coding Challenge( Kaalu)

The document contains a series of programming challenges and solutions in C, Python, SQL, HTML, CSS, JavaScript, and Java, aimed at students of Assam down town University. Each section includes specific tasks such as finding the second largest element in an array, creating a digital clock, and designing a registration form. Additionally, it showcases database queries for sales and product data, as well as object-oriented programming concepts in Java.

Uploaded by

penguin062422
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 34

Assam down town University

down town college of Engineering


Gandhinagar, Panikhaiti, Ghy - 26

Coding
Challenge

Name : Sasanka Rajowar


Branch : B.Tech CSE (CTIS)
Roll No. : ADTU/2021-25/BTECH(CTIS)/002

Session : 2021-2025

Semester : 8th
Data Structure Using C

1 .Write a C program to find the second largest element in an array.

Ans:

#include <stdio.h>
#include <limits.h>

int main() {
int arr[] = {12, 35, 1, 10, 34, 1};
int n = sizeof(arr)/sizeof(arr[0]);
int first = INT_MIN, second = INT_MIN;

for(int i = 0; i < n; i++) {


if(arr[i] > first) {
second = first;
first = arr[i];
} else if(arr[i] > second && arr[i] != first) {
second = arr[i];
}
}

if (second == INT_MIN)
printf("No second largest element\n");
else
printf("The second largest element is %d\n", second);

return 0;
}

OUTPUT :

2 Write a C program to move all zeroes to the end of an array


Ans:

#include <stdio.h>

void moveZeroes(int arr[], int n) {


int count = 0; // count of non-zero elements

for (int i = 0; i < n; i++) {


if (arr[i] != 0)
arr[count++] = arr[i];
}

while (count < n)


arr[count++] = 0;
}

int main() {
int arr[] = {0, 1, 0, 3, 12};
int n = sizeof(arr)/sizeof(arr[0]);

moveZeroes(arr, n);

printf("Array after moving zeroes: ");


for(int i = 0; i < n; i++)
printf("%d ", arr[i]);

return 0;
}

OUTPUT :

3 Write a C program to reverse a string using stack .

Ans:
#include <stdio.h>
#include <string.h>

#define MAX 100

char stack[MAX];
int top = -1;

void push(char ch) {


stack[++top] = ch;
}

char pop() {
return stack[top--];
}

int main() {
char str[] = "hello";
int len = strlen(str);

for(int i = 0; i < len; i++)


push(str[i]);

for(int i = 0; i < len; i++)


str[i] = pop();

printf("Reversed string is: %s\n", str);


return 0;
}

OUTPUT :
4 Write a C program to remove duplicates from a sorted linked list

Ans:

#include <stdio.h>
#include <stdlib.h>

struct Node {
int data;
struct Node* next;
};

void removeDuplicates(struct Node* head) {


struct Node* current = head;

while (current != NULL && current->next != NULL) {


if (current->data == current->next->data) {
struct Node* temp = current->next;
current->next = current->next->next;
free(temp);
} else {
current = current->next;
}
}
}

void push(struct Node** head_ref, int new_data) {


struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->next = *head_ref;
*head_ref = new_node;
}

void printList(struct Node *node) {


while (node != NULL) {
printf("%d ", node->data);
node = node->next;
}
}

int main() {
struct Node* head = NULL;
push(&head, 20);
push(&head, 20);
push(&head, 13);
push(&head, 13);
push(&head, 11);

printf("Original list:\n");
printList(head);

removeDuplicates(head);

printf("\nList after removing duplicates:\n");


printList(head);

return 0;
}

OUTPUT

5 Write a C program to reverse an array without using extra space . ans


these in data structure and algorithm

Ans:

#include <stdio.h>

void reverseArray(int arr[], int n) {


int start = 0, end = n - 1;
while (start < end) {
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}

int main() {
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr)/sizeof(arr[0]);

reverseArray(arr, n);

printf("Reversed array: ");


for (int i = 0; i < n; i++)
printf("%d ", arr[i]);

return 0;
}

OUTPUT:

PYTHON

1. Write a python program that counts the number of vowels (a, e, i, o, u)


in a given string.

Ans:

def count_vowels(s):
vowels = 'aeiouAEIOU'
count = sum(1 for char in s if char in vowels)
return count

text = "Hello World"


print("Number of vowels:", count_vowels(text))

OUTPUT:

2. Given two sorted lists, write a python program to merge them into a
single sorted list without using built-in sort functions.

Ans:

def merge_sorted_lists(list1, list2):


merged = []
i=j=0

while i < len(list1) and j < len(list2):


if list1[i] < list2[j]:
merged.append(list1[i])
i += 1
else:
merged.append(list2[j])
j += 1

merged.extend(list1[i:])
merged.extend(list2[j:])
return merged

list1 = [1, 3, 5]
list2 = [2, 4, 6]
print("Merged list:", merge_sorted_lists(list1, list2))
OUTPUT:

3. Write a python program that checks if a given string of parentheses ()[]


{} is valid (i.e., properly closed and nested).

Ans:

def is_valid_parentheses(s):
stack = []
mapping = {')': '(', ']': '[', '}': '{'}

for char in s:
if char in mapping.values():
stack.append(char)
elif char in mapping:
if not stack or stack.pop() != mapping[char]:
return False
return not stack

expression = "{[()]}"
print("Is valid:", is_valid_parentheses(expression))

OUTPUT

4. Write a python program to find the common elements between two


lists.

Ans:

def find_common_elements(list1, list2):


return list(set(list1) & set(list2))

list1 = [1, 2, 3, 4]
list2 = [3, 4, 5, 6]
print("Common elements:", find_common_elements(list1, list2))

OUTPUT:

5. Write a function to find the least common multiple of two numbers.

Ans:

def lcm(a, b):


def gcd(x, y):
while y:
x, y = y, x % y
return x

return abs(a * b) // gcd(a, b)

print("LCM of 12 and 15:", lcm(12, 15))

OUTPUT:

RDBMS

Sales Table
sale_id product_id quantity_sold sale_date total_price

1 101 5 2024-01-01 2500.00

2 102 3 2024-01-02 900.00

3 103 2 2024-01-02 60.00

4 104 4 2024-01-03 80.00

5 105 6 2024-01-03 90.00

Product Table

product_id product_name category unit_price

101 Laptop Electronics 500.00


102 Smartphone Electronics 300.00
103 Headphones Electronics 30.00
104 Keyboard Electronics 20.00
105 Mouse Electronics 15.00

1. Retrieve the product details (name, category, unit price) for products
that have a quantity sold greater than the average quantity sold across all
products.

Ans:

SELECT p.product_name, p.category, p.unit_price


FROM Sales s
JOIN Product p ON s.product_id = p.product_id
WHERE s.quantity_sold > (
SELECT AVG(quantity_sold) FROM Sales
);

2. Create a query that lists the product names along with their
corresponding sales count.

Ans:

SELECT p.product_name, COUNT(s.sale_id) AS sales_count


FROM Sales s
JOIN Product p ON s.product_id = p.product_id
GROUP BY p.product_name;

3 Write a query that calculates the total revenue generated from each
category of products for the year 2024.

Ans:

SELECT p.category, SUM(s.total_price) AS total_revenue


FROM Sales s
JOIN Product p ON s.product_id = p.product_id
WHERE YEAR(s.sale_date) = 2024
GROUP BY p.category;

4.Categorize sales as "High", "Medium", or "Low" based on total price


(e.g., > $200 is High, $100-$200 is Medium, < $100 is Low).

Ans:

SELECT s.sale_id, p.product_name, s.total_price,


CASE
WHEN s.total_price > 200 THEN 'High'
WHEN s.total_price BETWEEN 100 AND 200 THEN 'Medium'
ELSE 'Low'
END AS price_category
FROM Sales s
JOIN Product p ON s.product_id = p.product_id;

5.List the Top 3 Products by Revenue Contribution Percentage in rdbms.

Ans:

WITH ProductRevenue AS (
SELECT p.product_name, SUM(s.total_price) AS revenue
FROM Sales s
JOIN Product p ON s.product_id = p.product_id
GROUP BY p.product_name
),
TotalRevenue AS (
SELECT SUM(revenue) AS total FROM ProductRevenue
)
SELECT pr.product_name,
pr.revenue,
ROUND((pr.revenue / tr.total) * 100, 2) AS revenue_percentage
FROM ProductRevenue pr, TotalRevenue tr
ORDER BY revenue_percentage DESC
LIMIT 3;

WEB TECHNOLOGY
1. Design a webpage displaying your favorite movies using both Ordered
and Unordered Lists.

Ans:

<!DOCTYPE html>
<html>
<head>
<title>My Favorite Movies</title>
</head>
<body>
<h1>My Favorite Movies</h1>

<h2>Top 5 Favorite Movies (Ordered)</h2>


<ol>
<li>Inception</li>
<li>Interstellar</li>
<li>Vincenzo</li>
<li>Avengers: Endgame</li>
<li>Hera Pheri</li>
</ol>

<h2>Genres I Like (Unordered)</h2>


<ul>
<li>Action</li>
<li>Sci-Fi</li>
<li>Drama</li>
<li>Comedy</li>
</ul>
</body>
</html>

2. Create a single-webpage registration form where users can register


with fields for name, email, and message.

Ans:

<!DOCTYPE html>
<html>
<head>
<title>Registration Form</title>
</head>
<body>
<h2>Register Here</h2>
<form>
<label>Name:</label><br>
<input type="text" name="name" required><br><br>

<label>Email:</label><br>
<input type="email" name="email" required><br><br>

<label>Message:</label><br>
<textarea name="message" rows="4" cols="30"></textarea><br><br>

<input type="submit" value="Submit">


</form>
</body>
</html>

3. Design and create a Digital Clock: Display the current time that
updates every second.

Ans:

<!DOCTYPE html>
<html>
<head>
<title>Digital Clock</title>
<style>
#clock {
font-size: 2em;
font-weight: bold;
}
</style>
</head>
<body>
<h1>Digital Clock</h1>
<div id="clock"></div>

<script>
function updateClock() {
const now = new Date();
document.getElementById("clock").textContent =
now.toLocaleTimeString();
}
setInterval(updateClock, 1000);
updateClock();
</script>
</body>
</html>

4. Using HTML, CSS and JavaScript create a Temeprature converter to


convert Celsius to Fahrenheit and vice versa.

Ans:

<!DOCTYPE html>
<html>
<head>
<title>Temperature Converter</title>
</head>
<body>
<h2>Temperature Converter</h2>
<input type="number" id="temp" placeholder="Enter Temperature">
<select id="convert">
<option value="CtoF">Celsius to Fahrenheit</option>
<option value="FtoC">Fahrenheit to Celsius</option>
</select>
<button onclick="convertTemp()">Convert</button>
<p id="result"></p>

<script>
function convertTemp() {
const temp = parseFloat(document.getElementById("temp").value);
const type = document.getElementById("convert").value;
let result;
if (type === "CtoF") {
result = (temp * 9/5) + 32 + " °F";
} else {
result = ((temp - 32) * 5/9).toFixed(2) + " °C";
}
document.getElementById("result").textContent = "Result: " + result;
}
</script>
</body>
</html>

5. Using HTML, CSS and JavaScript create a simple quiz with three
multiple-choice questions

Ans:

<!DOCTYPE html>
<html>
<head>
<title>Simple Quiz</title>
</head>
<body>
<h2>Simple Quiz</h2>
<form id="quizForm">
<p>1. What is the capital of France?</p>
<input type="radio" name="q1" value="Paris"> Paris<br>
<input type="radio" name="q1" value="London"> London<br>

<p>2. What is 5 + 3?</p>


<input type="radio" name="q2" value="8"> 8<br>
<input type="radio" name="q2" value="9"> 9<br>

<p>3. Which language runs in a web browser?</p>


<input type="radio" name="q3" value="JavaScript"> JavaScript<br>
<input type="radio" name="q3" value="Python"> Python<br><br>

<button type="button" onclick="checkAnswers()">Submit</button>


</form>

<p id="score"></p>

<script>
function checkAnswers() {
const answers = {
q1: "Paris",
q2: "8",
q3: "JavaScript"
};
let score = 0;
for (let key in answers) {
const selected = document.querySelector(`input[name="$
{key}"]:checked`);
if (selected && selected.value === answers[key]) {
score++;
}
}
document.getElementById("score").textContent = "Your score: " +
score + "/3";
}
</script>
</body>
</html>

JAVA
1. Create a package named "DownTown". Under this create two packages
named "Employee" and "Student". Under the employee package create a
class called "EmployeeDetails" having required member fields and
methods. Under the Student package create a class called
"StudentDetails" having required member fields and methods.
Demonstrate the above by creating objects of StudentDetails and
EmployeeDetails inside another class which resides in another package.
Hint: You can assume the relevant fields and methods to be written inside
the EmployeeDetails and StudentDetails class.

Ans:

i.DownTown/Employee/EmployeeDetails.java

package DownTown.Employee;

public class EmployeeDetails {


private String name;
private int id;
private double salary;

public EmployeeDetails(String name, int id, double salary) {


this.name = name;
this.id = id;
this.salary = salary;
}

public void displayEmployee() {


System.out.println("Employee Details:");
System.out.println("Name: " + name);
System.out.println("ID: " + id);
System.out.println("Salary: $" + salary);
}
}

ii.DownTown/Student/StudentDetails.java

package DownTown.Student;

public class StudentDetails {


private String name;
private int rollNumber;
private float marks;

public StudentDetails(String name, int rollNumber, float marks) {


this.name = name;
this.rollNumber = rollNumber;
this.marks = marks;
}

public void displayStudent() {


System.out.println("Student Details:");
System.out.println("Name: " + name);
System.out.println("Roll Number: " + rollNumber);
System.out.println("Marks: " + marks);
}
}

iii. Main/MainApp.java

package Main;

import DownTown.Employee.EmployeeDetails;
import DownTown.Student.StudentDetails;

public class MainApp {


public static void main(String[] args) {
EmployeeDetails emp = new EmployeeDetails("Alice", 101, 50000);
StudentDetails stu = new StudentDetails("Bob", 201, 87.5f);

emp.displayEmployee();
System.out.println();
stu.displayStudent();
}
}

2. Tom is participating in a coding contest, he will win the contest if he


performs the following task: Design and develop an application for
Banking in Java using the concept of Interface. Follow the following
instructions for developing the application.
a) . Create an interface IAccount which contains the functions such as
balanceEnquiry(int accountNumber), depositAmount(int
AccountNumber) in package pkgintf.
b) . Create a class Account which implements IAccount in package
pkgbase.
c) . Create a class SavingsAccount which inherits Account class in
package pkgder
d) . Create a class CurrentAccount which inherits Account class in
package pkgder
e) . Include a createAccount() method that generates account number
in sequence and another method showAccountDetails() to display the
account information.
f). Create a Banking in package pkgtest to demonstrate the application
using a menu driven program which gives the choices to operate. Create
array for both types of accounts and manage the same.

Ans:

a) pkgintf/IAccount.java

package pkgintf;

public interface IAccount {


void balanceEnquiry(int accountNumber);
void depositAmount(int accountNumber, double amount);
}

b) pkgbase/Account.java

package pkgbase;

import pkgintf.IAccount;

public class Account implements IAccount {


protected static int accountCounter = 1001;
protected int accountNumber;
protected String name;
protected double balance;

public Account(String name) {


this.name = name;
this.accountNumber = accountCounter++;
this.balance = 0.0;
}

public void createAccount() {


System.out.println("Account created: " + accountNumber);
}

public void depositAmount(int accountNumber, double amount) { ... }

public void balanceEnquiry(int accountNumber) { ... }

public void showAccountDetails() { ... }


}

@Override
public void balanceEnquiry(int accountNumber) {
if (this.accountNumber == accountNumber) {
System.out.println("Account Balance: ₹" + balance);
}
}
@Override
public void depositAmount(int accountNumber, double amount) { if
(this.accountNumber
== accountNumber) {
balance += amount;
System.out.println("Deposited ₹" + amount + ". New Balance: ₹" +
balance); }
}
public void showAccountDetails() {
System.out.println("Account No: " + accountNumber + " | Holder: " +
accountHolder + " |
Balance: ₹" + balance);
}
}

c) pkgder/SavingsAccount.java

package pkgder;
import pkgbase.Account;

public class SavingsAccount extends Account {


public SavingsAccount(String name) {
super(name);
}
}

d) pkgder/CurrentAccount.java

package pkgder;

import pkgbase.Account;

public class CurrentAccount extends Account {


public CurrentAccount(String name) {
super(name);
}
}

e) Include createAccount() and showAccountDetails()

package pkgtest;
import pkgder.SavingsAccount;
import pkgder.CurrentAccount;
import java.util.Scanner;
public class Banking {
static int nextAccountNumber = 1001;
static SavingsAccount[] savings = new SavingsAccount[10];
static CurrentAccount[] current = new CurrentAccount[10];
static int sIndex = 0, cIndex = 0;
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
while (true) {
System.out.println("\n====== BANKING SYSTEM MENU ======");
System.out.println("1. Create Savings Account");
System.out.println("2. Create Current Account");
System.out.println("3. Deposit");
System.out.println("4. Balance Enquiry");
System.out.println("5. Show All Accounts");
System.out.println("0. Exit");
System.out.print("Enter choice: ");
int choice = sc.nextInt();
switch (choice) {
case 1 -> createSavingsAccount();
case 2 -> createCurrentAccount();
case 3 -> depositToAccount();
case 4 -> checkBalance();
case 5 -> displayAllAccounts();
case 0 -> {
System.out.println("Thank you for using the Banking System!"); return;
}
default -> System.out.println("Invalid choice, try again.");
}
}
}
static void createSavingsAccount() {
System.out.print("Enter Account Holder Name: "); String name =
sc.next();
SavingsAccount acc = new SavingsAccount();
acc.createAccount(nextAccountNumber++,
name); savings[sIndex++] = acc;
System.out.println("Savings Account Created Successfully.");
acc.showAccountDetails();
}
static void createCurrentAccount() {
System.out.print("Enter Account Holder Name: "); String name =
sc.next();
CurrentAccount acc = new CurrentAccount();
acc.createAccount(nextAccountNumber++,
name); current[cIndex++] = acc;
System.out.println("Current Account Created Successfully.");
acc.showAccountDetails();
}
static void depositToAccount() {
System.out.print("Enter Account Number: "); int accNum = sc.nextInt();
System.out.print("Enter Amount to Deposit: "); double amt =
sc.nextDouble();
boolean found = false;
for (SavingsAccount sa : savings) {
if (sa != null && sa.accountNumber == accNum) {
sa.depositAmount(accNum, amt);
found = true;
break;
}
}
for (CurrentAccount ca : current) {
if (ca != null && ca.accountNumber == accNum) {
ca.depositAmount(accNum, amt);
found = true;
break;
}
}
if (!found) System.out.println("Account not found!");
}
static void checkBalance() {
System.out.print("Enter Account Number: ");
int accNum = sc.nextInt();
boolean found = false;
for (SavingsAccount sa : savings) {
if (sa != null && sa.accountNumber == accNum) {
sa.balanceEnquiry(accNum);
found = true;
break;
}
}
for (CurrentAccount ca : current) {
if (ca != null && ca.accountNumber == accNum) {
ca.balanceEnquiry(accNum);
found = true;
break;
}
}
if (!found) System.out.println("Account not found!");
}
static void displayAllAccounts() {
System.out.println("---- Savings Accounts ----");
for (SavingsAccount sa : savings) {
if (sa != null) sa.showAccountDetails();
}
System.out.println("---- Current Accounts ----");
for (CurrentAccount ca : current) {
if (ca != null) ca.showAccountDetails();
}
}
}
f) pkgtest/Banking.java

package pkgtest;
import pkgder.SavingsAccount;
import pkgder.CurrentAccount;
import java.util.Scanner;
public class Banking {
static int nextAccountNumber = 1001;
static SavingsAccount[] savings = new SavingsAccount[10]; static
CurrentAccount[] current
= new CurrentAccount[10]; static int sIndex = 0, cIndex = 0;
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
while (true) {
System.out.println("\n====== BANKING SYSTEM MENU ======");
System.out.println("1. Create Savings Account");
System.out.println("2. Create Current Account");
System.out.println("3. Deposit");
System.out.println("4. Balance Enquiry");
System.out.println("5. Show All Accounts");
System.out.println("0. Exit");
System.out.print("Enter choice: ");
int choice = sc.nextInt();
switch (choice) {
case 1 -> createSavingsAccount();
case 2 -> createCurrentAccount();
case 3 -> depositToAccount();
case 4 -> checkBalance();
case 5 -> displayAllAccounts();
case 0 -> {
System.out.println("Thank you for using the Banking System!"); return;
}
default -> System.out.println("Invalid choice, try again."); }
}
}
static void createSavingsAccount() {
System.out.print("Enter Account Holder Name: ");
String name = sc.next();
SavingsAccount acc = new SavingsAccount();
acc.createAccount(nextAccountNumber++, name);
savings[sIndex++] = acc;
System.out.println("Savings Account Created Successfully.");
acc.showAccountDetails();
}
static void createCurrentAccount() {
System.out.print("Enter Account Holder Name: "); String name =
sc.next();
CurrentAccount acc = new CurrentAccount();
acc.createAccount(nextAccountNumber++,
name); current[cIndex++] = acc;
System.out.println("Current Account Created Successfully.");
acc.showAccountDetails();
}
static void depositToAccount() {
System.out.print("Enter Account Number: "); int accNum = sc.nextInt();
System.out.print("Enter Amount to Deposit: "); double amt =
sc.nextDouble();
boolean found = false;
for (SavingsAccount sa : savings) {
if (sa != null && sa.accountNumber == accNum) {
sa.depositAmount(accNum, amt);
found = true;
break;
}
}
for (CurrentAccount ca : current) {
if (ca != null && ca.accountNumber == accNum) {
ca.depositAmount(accNum, amt);
found = true;
break;
}
}
if (!found) System.out.println("Account not found!"); }
static void checkBalance() {
System.out.print("Enter Account Number: "); int accNum = sc.nextInt();
boolean found = false;
for (SavingsAccount sa : savings) {
if (sa != null && sa.accountNumber == accNum) {
sa.balanceEnquiry(accNum);
found = true;
break;
}
}
for (CurrentAccount ca : current) {
if (ca != null && ca.accountNumber == accNum) {
ca.balanceEnquiry(accNum);
found = true;
break;
}
}
if (!found) System.out.println("Account not found!");
}
static void displayAllAccounts() {
System.out.println("---- Savings Accounts ----");
for (SavingsAccount sa : savings) {
if (sa != null) sa.showAccountDetails();
}
System.out.println("---- Current Accounts ----");
for (CurrentAccount ca : current) {
if (ca != null) ca.showAccountDetails();
}

3. With the help of the Multithreading concept, create two separate


threads, one thread titled
"primeThread" by extending the Thread class, and the other titled
"fiboThread" by
implementing Runnable interface. "primeThread" will be responsible to
print all the prime
numbers from1 to 100 in a regular interval of 0.25 seconds."fiboThread"
will be responsible
to print fibonacci series of 20 numbers,in a regular interval of 0.5
seconds. On executing this
application, get the following info also.
a) Get the id,name and priority of the main thread
b) Change the name and priority of the main thread and print the same. c)
Print the thread
group info of both the child threads
d) Use isAlive method to check the status of the childThread. //
PrimeThread class by
extending Thread.

Ans:
class PrimeThread extends Thread {
public PrimeThread() {
super("primeThread");
}
public void run() {
System.out.println(getName() + " started in group: " +
getThreadGroup()); for (int i = 2; i <=
100; i++) {
if (isPrime(i)) {
System.out.print(i + " ");
try {
Thread.sleep(250); // 0.25 seconds
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
System.out.println("\n" + getName() + " finished.");
}
private boolean isPrime(int num) {
for (int i = 2; i <= num / 2; i++)
if (num % i == 0)
return false;
return true;
}
}
// FiboThread class by implementing Runnable
class FiboThread implements Runnable {
public void run() {
Thread t = Thread.currentThread();
System.out.println(t.getName() + " started in group: " +
t.getThreadGroup()); int a = 0, b =
1, c;
System.out.print(a + " " + b + " ");
for (int i = 3; i <= 20; i++) {
c = a + b;
System.out.print(c + " ");
a = b;
b = c;
try {
Thread.sleep(500); // 0.5 seconds
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("\n" + t.getName() + " finished.");
}
}
// Main class
public class ThreadDemo {
public static void main(String[] args) {
// Main thread info
Thread mainThread = Thread.currentThread();
System.out.println("Main Thread - ID: " + mainThread.getId() + ",
Name: " +
mainThread.getName() + ", Priority: " + mainThread.getPriority());
// Change main thread name and priority
mainThread.setName("MainBankThread");
mainThread.setPriority(Thread.MAX_PRIORITY);
System.out.println("Main Thread (after change) - ID: " +
mainThread.getId() + ", Name: " +
mainThread.getName() + ", Priority: " + mainThread.getPriority());
// Create threads
PrimeThread primeThread = new PrimeThread();
Thread fiboThread = new Thread(new FiboThread(), "fiboThread");
// Start threads
primeThread.start();
fiboThread.start();
// Check if threads are alive
try {
Thread.sleep(100); // small delay
System.out.println("Is primeThread alive? " + primeThread.isAlive());
System.out.println("Is fiboThread alive? " + fiboThread.isAlive());
// Wait for threads to finish
primeThread.join();
fiboThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("All threads finished. Exiting main...");
}
}
4.Create an Interface Subject for a student to read the marks obtained by
her in 3 subjects. Create another interface Test to calculate the total marks
scored in the three subjects. Now create an interface Sports to read the
score obtained in any two sports taken by the student and another method
to calculate the total score. Create a class Result to calculate the overall
result in percent for both test and sports and finally grade the student
based on the criteria below – i. “Excellent” if scores 75% or above. ii.
“Average” if scores between 55%(inclusive) to 75%. iii. “Slow” if scores
below 55%. Create a driver class Student to execute the program.

Ans:

// Interface to read academic marks


interface Subject {
void readMarks(int m1, int m2, int m3);
}

// Interface to calculate total academic marks


interface Test {
int getTotalMarks();
}

// Interface to read sports scores and calculate sports total


interface Sports {
void readSportsMarks(int s1, int s2);
int getTotalSportsMarks();
}

// Result class implementing all interfaces


class Result implements Subject, Test, Sports {
private int sub1, sub2, sub3;
private int sport1, sport2;

// Subject interface method


public void readMarks(int m1, int m2, int m3) {
sub1 = m1;
sub2 = m2;
sub3 = m3;
}

// Test interface method


public int getTotalMarks() {
return sub1 + sub2 + sub3;
}

// Sports interface methods


public void readSportsMarks(int s1, int s2) {
sport1 = s1;
sport2 = s2;
}

public int getTotalSportsMarks() {


return sport1 + sport2;
}

// Method to calculate overall result and grade


public void calculateResult() {
int totalMarks = getTotalMarks() + getTotalSportsMarks();
int maxTotal = 300 + 200; // assuming each subject = 100, each
sport = 100
double percent = (totalMarks * 100.0) / maxTotal;

System.out.println("Total Marks: " + totalMarks + " / " + maxTotal);


System.out.printf("Percentage: %.2f%%\n", percent);

if (percent >= 75)


System.out.println("Grade: Excellent");
else if (percent >= 55)
System.out.println("Grade: Average");
else
System.out.println("Grade: Slow");
}
}

// Driver class
public class Student {
public static void main(String[] args) {
Result r = new Result();

// Sample data input


r.readMarks(80, 75, 78); // Academic marks
r.readSportsMarks(85, 70); // Sports marks

r.calculateResult();
}
}
5.Sam has been assigned a task of finding the median of an array using
concept of abstraction. Help her complete her assignment. Given the
array – A[8]={15,7,12,5,6,8,11,1}

Ans:

import java.util.Arrays;

// Abstract class defining the structure


abstract class MedianFinder {
abstract double findMedian(int[] arr);
}

// Concrete class that implements the abstract method


class ArrayMedian extends MedianFinder {

@Override
double findMedian(int[] arr) {
Arrays.sort(arr); // Sort the array first
int n = arr.length;
if (n % 2 == 0) {
return (arr[n/2 - 1] + arr[n/2]) / 2.0; // Median for even number of
elements
} else {
return arr[n/2]; // Median for odd number of elements
}
}
}

// Driver class
public class MedianApp {
public static void main(String[] args) {
int[] A = {15, 7, 12, 5, 6, 8, 11, 1};

MedianFinder medianFinder = new ArrayMedian();


double median = medianFinder.findMedian(A);

System.out.println("The median is: " + median);


}
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy