0% found this document useful (0 votes)
2 views14 pages

Javascript Programs

The document contains a collection of JavaScript programs demonstrating various functionalities such as adding numbers, finding squares, generating random numbers, and more. Each program includes code snippets along with example outputs to illustrate their functionality. The programs cover a range of topics including mathematical calculations, string manipulations, and basic data structures.

Uploaded by

BENAZIR AE
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
2 views14 pages

Javascript Programs

The document contains a collection of JavaScript programs demonstrating various functionalities such as adding numbers, finding squares, generating random numbers, and more. Each program includes code snippets along with example outputs to illustrate their functionality. The programs cover a range of topics including mathematical calculations, string manipulations, and basic data structures.

Uploaded by

BENAZIR AE
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 14

JAVASCRIPT PROGRAMS

1. Add Two Numbers


// Adding two numbers
num1 = 10;
num2 = 20;
sum = num1 + num2;
console.log("The sum of", num1, "and", num2, "is", sum);
OUTPUT:
The sum of 10 and 20 is 30

// Adding two numbers


// Get input from the user
num1 = prompt("Enter the first number:");
num2 = prompt("Enter the second number:");
// Convert the input (which is a string) to numbers
num1 = parseFloat(num1);
num2 = parseFloat(num2);
// Add the two numbers
sum = num1 + num2;
// Display the result
console.log(`The sum of ${num1} and ${num2} is ${sum}`);
OUTPUT:
Enter the first number:2.5
Enter the second number:3.5
The sum of 2.5 and 3.5 is 6

2. Find the Square of a Number


// Find the square of a number
number = 7;
square = number * number;
console.log(`The square of ${number} is ${square}`);
OUTPUT:
The square of 7 is 49

3. Generate a Random Number


// Generate a random number between 1 and 100
randomNumber = Math.floor(Math.random() * 100) + 1;
console.log("Random number between 1 and 100:", randomNumber);
OUTPUT:
Random number between 1 and 100: 76

4. Check if a Number is Prime


// Check if a number is prime
number = 29;
isPrime = true;
if (number < 2) {
isPrime = false;
} else {
for (i = 2; i <= Math.sqrt(number); i++) {
if (number % i === 0) {
}
isPrime = false;
break;
}
}
console.log(number, "is", isPrime ? "a prime number." : "not a prime
number.");
OUTPUT:
29 is not a prime number.

5. Convert Hours to Minutes


// Convert hours to minutes
hours = 5;
minutes = hours * 60;
console.log(`${hours} hours is equal to ${minutes} minutes.`);
OUTPUT:
5 hours is equal to 300 minutes.

6. Display the First N Fibonacci Numbers


// Display the first N Fibonacci numbers
n = 10;
fib = [0, 1]; // Initialize the first two numbers
for (i = 2; i < n; i++) {
fib.push(fib[i - 1] + fib[i - 2]);
}
console.log(`The first ${n} Fibonacci numbers are:`, fib.join(", "));
OUTPUT:
The first 10 Fibonacci numbers are: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34

7. Check Even or Odd


// Check if a number is even or odd
number = 15;
if (number % 2 === 0) {
console.log(number, "is even.");
} else {
console.log(number, "is odd.");
}
OUTPUT:
15 is odd.

8. Simple Multiplication Table


// Display multiplication table for a given number
num = 5;
console.log("Multiplication Table of", num);
for (i = 1; i <= 10; i++) {
console.log(`${num} x ${i} = ${num * i}`);
}
OUTPUT:
Multiplication Table of 5
5x1=5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
9. Find the Largest Number
// Find the largest number among three
a = 12, b = 25, c = 9;
largest = a;
if (b > largest) largest = b;
if (c > largest) largest = c;
console.log("The largest number is", largest);
OUTPUT:
The largest number is 25

10. Countdown Timer


// Simple countdown timer
countdown = 5;
interval = setInterval(() => {
console.log(countdown);
countdown--;
if (countdown === 0) {
console.log("Time's up!");
clearInterval(interval);
}
}, 1000); // 1-second interval
OUTPUT:
5
4
3
2
1
Time's up!
11. Reverse a String
// Reverse a string
originalString = "hello";
reversedString = "";
for (i = originalString.length - 1; i >= 0; i--) {
reversedString += originalString[i];
}
console.log("Original:", originalString);
console.log("Reversed:", reversedString);
OUTPUT:
Original: hello
Reversed: olleh

12. Simple Interest Calculator


// Calculate simple interest
principal = 1000; // Principal amount
rate = 5; // Annual interest rate
time = 2; // Time in years
simpleInterest = (principal * rate * time) / 100;
console.log("Simple Interest is:", simpleInterest);
OUTPUT:
Simple Interest is: 100

13. Convert Celsius to Fahrenheit


// Convert Celsius to Fahrenheit
celsius = 25;
fahrenheit = (celsius * 9/5) + 32;
console.log(`${celsius}°C is equal to ${fahrenheit}°F`);
OUTPUT:
25°C is equal to 77°F

14. Find Factorial


// Find factorial of a number
number = 5;
factorial = 1;
for (i = 1; i <= number; i++) {
factorial *= i;
}
console.log(`Factorial of ${number} is ${factorial}`);
OUTPUT:
Factorial of 5 is 120

15. Check Palindrome


// Check if a string is a palindrome
word = "madam";
reversed = word.split("").reverse().join("");
if (word === reversed) {
console.log(`${word} is a palindrome.`);
} else {
console.log(`${word} is not a palindrome.`);
}
OUTPUT:
madam is a palindrome.
1.Calculate Total Price in an Ice Cream Parlor
// Function to calculate total price
function calculateTotalPrice(prices) {
total = 0;
for (price of prices) {
total += price;
}
return total;
}
// Example usage
iceCreamPrices = [3.5, 2.8, 4.0]; // Prices of selected ice creams
console.log("Total Price: $" +
calculateTotalPrice(iceCreamPrices).toFixed(2));
OUTPUT: Total Price: $10.30

2.Book Search in a Library


// Array of books
books = ["Harry Potter", "The Hobbit", "1984", "The Catcher in the
Rye", "To Kill a Mockingbird"];
// Function to search for a book
function searchBook(query) {
for (book of books) {
if (book.toLowerCase().includes(query.toLowerCase())) {
return `"${book}" is available in the library.`;
}
}
return "Book not found.";
}
// Example usage
userQuery = "hobbit";
console.log(searchBook(userQuery));
OUTPUT: "The Hobbit" is available in the library.

3. Discount Calculator for a Store


// Function to calculate discounted price
function calculateDiscount(price, discountPercent) {
if (discountPercent > 100 || discountPercent < 0) {
return "Invalid discount percentage!";
}
discount = (price * discountPercent) / 100;
return price - discount;
}
// Example usage
originalPrice = 50; // $50
discount = 20; // 20% off
console.log("Discounted Price: $" + calculateDiscount(originalPrice,
discount).toFixed(2));
OUTPUT: Discounted Price: $40.00

4. Customer Order Tracker


// Array to store customer orders
orders = [];
// Function to add an order
function addOrder(customerName, item) {
orders.push({ customer: customerName, item: item });
console.log(`${customerName} ordered ${item}.`);
}
// Function to list all orders
function listOrders() {
console.log("Current Orders:");
for (let order of orders) {
console.log(`${order.customer} ordered ${order.item}.`);
}
}
// Example usage
addOrder("Alice", "Vanilla Ice Cream");
addOrder("Bob", "Chocolate Shake");
listOrders();
OUTPUT:
Alice ordered Vanilla Ice Cream.
Bob ordered Chocolate Shake.
Current Orders:
Alice ordered Vanilla Ice Cream.
Bob ordered Chocolate Shake.

5. Temperature Conversion Tool


// Function to convert Celsius to Fahrenheit
function celsiusToFahrenheit(celsius) {
return (celsius * 9/5) + 32;
}
// Function to convert Fahrenheit to Celsius
function fahrenheitToCelsius(fahrenheit) {
return (fahrenheit - 32) * 5/9;
}
// Example usage
tempC = 25; // 25°C
tempF = 77; // 77°F
console.log(`${tempC}°C is equal to $
{celsiusToFahrenheit(tempC).toFixed(2)}°F`);
console.log(`${tempF}°F is equal to $
{fahrenheitToCelsius(tempF).toFixed(2)}°C`);
OUTPUT
25°C is equal to 77.00°F
77°F is equal to 25.00°C

6. Stock Checker in a Book Shop


// Array of books with stock counts
books = [
{ title: "Harry Potter", stock: 5 },
{ title: "The Hobbit", stock: 0 },
{ title: "1984", stock: 3 }
];

// Function to check stock


function checkStock(bookName) {
for (book of books) {
if (book.title.toLowerCase() === bookName.toLowerCase()) {
return book.stock > 0
? `"${book.title}" is in stock (${book.stock} copies available).`
: `"${book.title}" is out of stock.`;
}
}
return "Book not found.";
}
// Example usage
console.log(checkStock("The Hobbit"));
console.log(checkStock("1984"));
OUTPUT
"The Hobbit" is out of stock.
"1984" is in stock (3 copies available).

7. Order Total Calculator


function calculateOrderTotal(items, taxRate) {
total = 0;
for (item of items) {
total += item.price * item.quantity;
}
total += total * taxRate / 100;
return total.toFixed(2);
}

// Example usage
orderItems = [
{ name: "Vanilla Ice Cream", price: 3.5, quantity: 2 },
{ name: "Strawberry Shake", price: 4.2, quantity: 1 }
];
taxRate = 8; // 8% tax
console.log("Order Total: $" + calculateOrderTotal(orderItems, taxRate));
OUTPUT
Order Total: $12.10

8. Customer Queue Management


customerQueue = [];
// Function to add a customer to the queue
function addCustomerToQueue(name) {
customerQueue.push(name);
console.log(`${name} has been added to the queue.`);
}
// Function to serve the next customer
function serveCustomer() {
if (customerQueue.length === 0) {
console.log("No customers in the queue.");
} else {
servedCustomer = customerQueue.shift();
console.log(`${servedCustomer} has been served.`);
}
}
// Example usage
addCustomerToQueue("Alice");
addCustomerToQueue("Bob");
serveCustomer();
serveCustomer();
serveCustomer(); // Empty queue case
OUTPUT
Alice has been added to the queue.
Bob has been added to the queue.
Alice has been served.
Bob has been served.
No customers in the queue.
9. Daily Revenue Tracker
// Array to track daily sales
dailySales = [];
// Function to record a sale
function recordSale(amount) {
dailySales.push(amount);
console.log(`Sale of $${amount} recorded.`);
}
// Function to calculate total daily revenue
function calculateTotalRevenue() {
total = 0;
for (sale of dailySales) {
total += sale;
}
return total.toFixed(2);
}
// Example usage
recordSale(50);
recordSale(20.5);
recordSale(35.3);
console.log("Total Revenue: $" + calculateTotalRevenue());
OUTPUT
Sale of $50 recorded.
Sale of $20.5 recorded.
Sale of $35.3 recorded.
Total Revenue: $105.80

You might also like