Coding Challenge( Kaalu)
Coding Challenge( Kaalu)
Coding
Challenge
Session : 2021-2025
Semester : 8th
Data Structure Using C
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;
if (second == INT_MIN)
printf("No second largest element\n");
else
printf("The second largest element is %d\n", second);
return 0;
}
OUTPUT :
#include <stdio.h>
int main() {
int arr[] = {0, 1, 0, 3, 12};
int n = sizeof(arr)/sizeof(arr[0]);
moveZeroes(arr, n);
return 0;
}
OUTPUT :
Ans:
#include <stdio.h>
#include <string.h>
char stack[MAX];
int top = -1;
char pop() {
return stack[top--];
}
int main() {
char str[] = "hello";
int len = strlen(str);
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;
};
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);
return 0;
}
OUTPUT
Ans:
#include <stdio.h>
int main() {
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr)/sizeof(arr[0]);
reverseArray(arr, n);
return 0;
}
OUTPUT:
PYTHON
Ans:
def count_vowels(s):
vowels = 'aeiouAEIOU'
count = sum(1 for char in s if char in vowels)
return count
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:
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:
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
Ans:
list1 = [1, 2, 3, 4]
list2 = [3, 4, 5, 6]
print("Common elements:", find_common_elements(list1, list2))
OUTPUT:
Ans:
OUTPUT:
RDBMS
Sales Table
sale_id product_id quantity_sold sale_date total_price
Product Table
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:
2. Create a query that lists the product names along with their
corresponding sales count.
Ans:
3 Write a query that calculates the total revenue generated from each
category of products for the year 2024.
Ans:
Ans:
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>
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>
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>
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 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;
ii.DownTown/Student/StudentDetails.java
package DownTown.Student;
iii. Main/MainApp.java
package Main;
import DownTown.Employee.EmployeeDetails;
import DownTown.Student.StudentDetails;
emp.displayEmployee();
System.out.println();
stu.displayStudent();
}
}
Ans:
a) pkgintf/IAccount.java
package pkgintf;
b) pkgbase/Account.java
package pkgbase;
import pkgintf.IAccount;
@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;
d) pkgder/CurrentAccount.java
package pkgder;
import pkgbase.Account;
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();
}
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:
// Driver class
public class Student {
public static void main(String[] args) {
Result r = new Result();
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;
@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};