0% found this document useful (0 votes)
5 views23 pages

JS Programs

The document contains a series of JavaScript functions that perform various mathematical and character-related operations. These include determining if a character is a vowel or consonant, checking if a number is positive or negative, calculating the area of a circle, finding the greatest common divisor (GCD) and least common multiple (LCM) of two numbers, and identifying prime, Armstrong, and perfect numbers, among others. Each function prompts the user for input and logs the result to the console.

Uploaded by

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

JS Programs

The document contains a series of JavaScript functions that perform various mathematical and character-related operations. These include determining if a character is a vowel or consonant, checking if a number is positive or negative, calculating the area of a circle, finding the greatest common divisor (GCD) and least common multiple (LCM) of two numbers, and identifying prime, Armstrong, and perfect numbers, among others. Each function prompts the user for input and logs the result to the console.

Uploaded by

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

1)A character is a vowel or consonant

==========================================
function isVowelOrConsonant(character) {
const lowerCaseChar = character.toLowerCase();

if (lowerCaseChar === ’a’ || lowerCaseChar === ’e’ || lowerCaseChar === ’i’ || lowerCaseChar === ’o’ || l
owerCaseChar === ’u’) {
return ’Vowel’;
} else if (lowerCaseChar >= ’a’ && lowerCaseChar <= ’z’) {
return ’Consonant’;
} else {
return ’Invalid input’;
}
}

const inputChar = prompt("Enter a character:"); // Prompt the user for input


const result = isVowelOrConsonant(inputChar);

console.log(‘The character ’${inputChar}’ is a ${result}.‘);


---------------------------------------------------------------------------------------------
2)A character is an alphabet or not
=====================================
function isAlphabet(character) {
const lowerCaseChar = character.toLowerCase();
return (lowerCaseChar >= ’a’ && lowerCaseChar <= ’z’);
}

const inputChar = prompt("Enter a character:");


const result = isAlphabet(inputChar);

if (result) {
console.log(‘The character ’${inputChar}’ is an alphabet.‘);
} else {
console.log(‘The character ’${inputChar}’ is not an alphabet.‘);
}
----------------------------------------------------------------------------------------------
3)Ascii values of a character
===============================
const inputChar = prompt("Enter a character:");
const asciiValue = inputChar.charCodeAt(0);

console.log(‘The ASCII value of the character ’${inputChar}’ is ${asciiValue}.‘);


----------------------------------------------------------------------------------------------
4)Uppercase, Lowercase or special character
============================================
function checkCharacterType(character) {
if (character >= ’A’ && character <= ’Z’) {
return ’Uppercase’;
} else if (character >= ’a’ && character <= ’z’) {
return ’Lowercase’;
} else {
return ’Special character’;
}
}
const inputChar = prompt("Enter a character:");
const result = checkCharacterType(inputChar);

console.log(‘The character ’${inputChar}’ is a ${result}.‘);


------------------------------------------------------------------------------------------------
5)A number is positive or negative
===================================
const inputNumber = parseFloat(prompt("Enter a number:"));

if (inputNumber > 0) {
console.log("The number is positive.");
} else if (inputNumber < 0) {
console.log("The number is negative.");
} else {
console.log("The number is zero.");
}
--------------------------------------------------------------------------------------------------
6)A number is even or odd
==========================
const inputNumber = parseInt(prompt("Enter a number:"));

if (inputNumber % 2 === 0) {
console.log("The number is even.");
} else {
console.log("The number is odd.");
}
--------------------------------------------------------------------------------------------------
7)Area of a circle
======================
const radius = parseFloat(prompt("Enter the radius of the circle:"));
const area = Math.PI * radius * radius;

console.log(‘The area of the circle with radius ${radius} is ${area.toFixed(2)}.‘);


---------------------------------------------------------------------------------------------------
8)LCM of two numbers
=======================
function gcd(a, b) {
if (b === 0) {
return a;
}
return gcd(b, a % b);
}

function lcm(a, b) {
return (a * b) / gcd(a, b);
}

const number1 = parseInt(prompt("Enter the first number:"));


const number2 = parseInt(prompt("Enter the second number:"));

const result = lcm(number1, number2);

console.log(‘The LCM of ${number1} and ${number2} is ${result}.‘);


---------------------------------------------------------------------------------------------------
9)GCD of two numbers
=======================
function gcd(a, b) {
while (b !== 0) {
const temp = b;
b = a % b;
a = temp;
}
return a;
}

const number1 = parseInt(prompt("Enter the first number:"));


const number2 = parseInt(prompt("Enter the second number:"));

const result = gcd(number1, number2);

console.log(‘The GCD of ${number1} and ${number2} is ${result}.‘);


---------------------------------------------------------------------------------------------------
10)Greatest of two numbers
=============================
const number1 = parseFloat(prompt("Enter the first number:"));
const number2 = parseFloat(prompt("Enter the second number:"));

if (number1 > number2) {


console.log(‘The greatest number is: ${number1}‘);
} else if (number2 > number1) {
console.log(‘The greatest number is: ${number2}‘);
} else {
console.log("Both numbers are equal.");
}
---------------------------------------------------------------------------------------------------
11)Greatest of three numbers
==============================
const number1 = parseFloat(prompt("Enter the first number:"));
const number2 = parseFloat(prompt("Enter the second number:"));
const number3 = parseFloat(prompt("Enter the third number:"));

if (number1 >= number2 && number1 >= number3) {


console.log(‘The greatest number is: ${number1}‘);
} else if (number2 >= number1 && number2 >= number3) {
console.log(‘The greatest number is: ${number2}‘);
} else {
console.log(‘The greatest number is: ${number3}‘);
}
--------------------------------------------------------------------------------------------------
12)Number of digits in an integer
==================================
const number = parseInt(prompt("Enter an integer:"));
const numString = Math.abs(number).toString();
const digitCount = numString.length;

console.log(‘The number of digits in ${number} is: ${digitCount}‘);


---------------------------------------------------------------------------------------------------
13)Sum of digits of a number
==================================
const number = parseInt(prompt("Enter a number:"));
let num = Math.abs(number);
let sum = 0;

while (num > 0) {


sum += num % 10;
num = Math.floor(num / 10);
}

console.log(‘The sum of digits of ${number} is: ${sum}‘);


---------------------------------------------------------------------------------------------------
14)Sum of N natural numbers
=============================
const n = parseInt(prompt("Enter a positive integer (N):"));
let sum = 0;

if (n > 0) {
for (let i = 1; i <= n; i++) {
sum += i;
}
console.log(‘The sum of the first ${n} natural numbers is: ${sum}‘);
} else {
console.log("Please enter a positive integer.");
}
-----------------------------------------------------------------------------------------------------
15)Sum of numbers in a given range
====================================
const start = parseInt(prompt("Enter the start of the range:"));
const end = parseInt(prompt("Enter the end of the range:"));
let sum = 0;

if (start <= end) {


for (let i = start; i <= end; i++) {
sum += i;
}
console.log(‘The sum of numbers from ${start} to ${end} is: ${sum}‘);
} else {
console.log("Invalid range. Please ensure the start is less than or equal to the end.");
}
--------------------------------------------------------------------------------------------------------
16)Reverse of a given number
==============================
const number = parseInt(prompt("Enter a number:"));
let reversedNumber = 0;
let num = Math.abs(number);

while (num > 0) {


reversedNumber = (reversedNumber * 10) + (num % 10);
num = Math.floor(num / 10);
}

console.log(‘The reverse of ${number} is: ${reversedNumber}‘);


------------------------------------------------------------------------------------------------------
17)Factorial of a number
============================
const number = parseInt(prompt("Enter a non-negative integer:"));
if (number < 0) {
console.log("Factorial is not defined for negative numbers.");
} else {
let factorial = 1;
for (let i = 1; i <= number; i++) {
factorial *= i;
}
console.log(‘The factorial of ${number} is: ${factorial}‘);
}
-----------------------------------------------------------------------------------------------------
18)Fibonacci series up to n
==============================
const n = parseInt(prompt("Enter a positive integer (n):"));

let fibSeries = [0, 1];

for (let i = 2; fibSeries[i - 1] + fibSeries[i - 2] <= n; i++) {


fibSeries[i] = fibSeries[i - 1] + fibSeries[i - 2];
}

console.log("Fibonacci series up to", n, ":", fibSeries.join(’, ’));


----------------------------------------------------------------------------------------------------
19)Leap year or not
=====================
const year = parseInt(prompt("Enter a year:"));

if ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0) {


console.log(‘${year} is a leap year.‘);
} else {
console.log(‘${year} is not a leap year.‘);
}
---------------------------------------------------------------------------------------------------
20)Prime number or not
=========================
const number = parseInt(prompt("Enter a positive integer:"));
let isPrime = true;

if (number <= 1) {
isPrime = false;
} else {
for (let i = 2; i <= Math.sqrt(number); i++) {
if (number % i === 0) {
isPrime = false;
break;
}
}
}

if (isPrime) {
console.log(‘${number} is a prime number.‘);
} else {
console.log(‘${number} is not a prime number.‘);
}
------------------------------------------------------------------------------------------
21)Palindrome or not
=====================
let number = parseInt(prompt("Enter a number:"));
const originalNumber = number;
let reversedNumber = 0;

while (number > 0) {


reversedNumber = (reversedNumber * 10) + (number % 10);
number = Math.floor(number / 10);
}

if (originalNumber === reversedNumber) {


console.log(‘${originalNumber} is a palindrome.‘);
} else {
console.log(‘${originalNumber} is not a palindrome.‘);
}
---------------------------------------------------------------------------------------------
22)Armstrong number or not
===========================
function isArmstrong(number) {
const numString = number.toString();
const numDigits = numString.length;
let sum = 0;

for (let i = 0; i < numDigits; i++) {


sum += Math.pow(parseInt(numString[i]), numDigits);
}

return sum === number;


}

const number = parseInt(prompt("Enter a number:"));

if (isArmstrong(number)) {
console.log(‘${number} is an Armstrong number.‘);
} else {
console.log(‘${number} is not an Armstrong number.‘);
}
--------------------------------------------------------------------------------------------
23)Strong number or not
=========================
function factorial(num) {
if (num === 0 || num === 1) {
return 1;
}
return num * factorial(num - 1);
}

function isStrong(number) {
const numString = number.toString();
let sum = 0;

for (let i = 0; i < numString.length; i++) {


sum += factorial(parseInt(numString[i]));
}
return sum === number;
}

const number = parseInt(prompt("Enter a number:"));

if (isStrong(number)) {
console.log(‘${number} is a Strong number.‘);
} else {
console.log(‘${number} is not a Strong number.‘);
}
----------------------------------------------------------------------------------------------
24)Perfect number or not
===============================
function isPerfect(number) {
let sum = 0;

for (let i = 1; i <= number / 2; i++) {


if (number % i === 0) {
sum += i;
}
}

return sum === number;


}

const number = parseInt(prompt("Enter a number:"));

if (isPerfect(number)) {
console.log(‘${number} is a perfect number.‘);
} else {
console.log(‘${number} is not a perfect number.‘);
}
-------------------------------------------------------------------------------------------------
25)Harshad number or not
==========================
function isHarshad(number) {
const numString = number.toString();
let sum = 0;

for (let i = 0; i < numString.length; i++) {


sum += parseInt(numString[i]);
}

return number % sum === 0;


}

const number = parseInt(prompt("Enter a number:"));

if (isHarshad(number)) {
console.log(‘${number} is a Harshad number.‘);
} else {
console.log(‘${number} is not a Harshad number.‘);
}
----------------------------------------------------------------------------------------------
26)Abundant number or not
===========================
function isAbundant(number) {
let sum = 1; // Initialize sum with 1 since 1 is a divisor for all numbers

for (let i = 2; i <= Math.sqrt(number); i++) {


if (number % i === 0) {
sum += i;

if (i !== number / i) {
sum += number / i;
}
}
}

return sum > number;


}

const number = parseInt(prompt("Enter a number:"));

if (isAbundant(number)) {
console.log(‘${number} is an abundant number.‘);
} else {
console.log(‘${number} is not an abundant number.‘);
}
--------------------------------------------------------------------------------------------
27)Power of a number
=====================
const base = parseFloat(prompt("Enter the base number:"));
const exponent = parseInt(prompt("Enter the exponent:"));

const result = Math.pow(base, exponent);

console.log(‘${base} raised to the power of ${exponent} is: ${result}‘);


-------------------------------------------------------------------------------------------
28)Factors of a number
=======================
const number = parseInt(prompt("Enter a positive integer:"));

if (number <= 0) {
console.log("Please enter a positive integer.");
} else {
console.log(‘Factors of ${number}:‘);
for (let i = 1; i <= number; i++) {
if (number % i === 0) {
console.log(i);
}
}
}
--------------------------------------------------------------------------------------------------
29)Add two fractions
======================
function gcd(a, b) {
if (b === 0) {
return a;
}
return gcd(b, a % b);
}

function addFractions(num1, den1, num2, den2) {


const commonDenominator = den1 * den2;
const numerator = num1 * den2 + num2 * den1;
const greatestCommonDivisor = gcd(numerator, commonDenominator);

const resultNumerator = numerator / greatestCommonDivisor;


const resultDenominator = commonDenominator / greatestCommonDivisor;

return [resultNumerator, resultDenominator];


}

const num1 = parseInt(prompt("Enter the numerator of the first fraction:"));


const den1 = parseInt(prompt("Enter the denominator of the first fraction:"));
const num2 = parseInt(prompt("Enter the numerator of the second fraction:"));
const den2 = parseInt(prompt("Enter the denominator of the second fraction:"));

const [resultNumerator, resultDenominator] = addFractions(num1, den1, num2, den2);

console.log(‘The sum of ${num1}/${den1} and ${num2}/${den2} is ${resultNumerator}/${resultDenominato


r}.‘);
-------------------------------------------------------------------------------------------------------------
30)Prime numbers in a given range
==================================
function isPrime(number) {
if (number <= 1) {
return false;
}

if (number <= 3) {
return true;
}

if (number % 2 === 0 || number % 3 === 0) {


return false;
}

let i = 5;
while (i * i <= number) {
if (number % i === 0 || number % (i + 2) === 0) {
return false;
}
i += 6;
}

return true;
}

const start = parseInt(prompt("Enter the start of the range:"));


const end = parseInt(prompt("Enter the end of the range:"));

console.log(‘Prime numbers between ${start} and ${end}:‘);


for (let number = start; number <= end; number++) {
if (isPrime(number)) {
console.log(number);
}
}
---------------------------------------------------------------------------------------------------
31)Armstrong numbers between two intervals
================================================
function isArmstrong(number) {
const numString = number.toString();
const numDigits = numString.length;
let sum = 0;

for (let i = 0; i < numDigits; i++) {


sum += Math.pow(parseInt(numString[i]), numDigits);
}

return sum === number;


}

const start = parseInt(prompt("Enter the start of the range:"));


const end = parseInt(prompt("Enter the end of the range:"));

console.log(‘Armstrong numbers between ${start} and ${end}:‘);


for (let number = start; number <= end; number++) {
if (isArmstrong(number)) {
console.log(number);
}
}
-----------------------------------------------------------------------------------------------------
32)Can a number be expressed as a sum of two prime numbers?
=============================================================
function isPrime(number) {
if (number <= 1) {
return false;
}

if (number <= 3) {
return true;
}

if (number % 2 === 0 || number % 3 === 0) {


return false;
}

let i = 5;
while (i * i <= number) {
if (number % i === 0 || number % (i + 2) === 0) {
return false;
}
i += 6;
}

return true;
}
function canBeExpressedAsSumOfPrimes(number) {
for (let i = 2; i <= number / 2; i++) {
if (isPrime(i) && isPrime(number - i)) {
return true;
}
}
return false;
}

const number = parseInt(prompt("Enter a number:"));

if (canBeExpressedAsSumOfPrimes(number)) {
console.log(‘${number} can be expressed as a sum of two prime numbers.‘);
} else {
console.log(‘${number} cannot be expressed as a sum of two prime numbers.‘);
}
-------------------------------------------------------------------------------------------------
33)Replace all 0’s with 1 in a given integer
==================================================
function replaceZerosWithOnes(number) {
const numString = number.toString();
let result = ’’;

for (let i = 0; i < numString.length; i++) {


if (numString[i] === ’0’) {
result += ’1’;
} else {
result += numString[i];
}
}

return parseInt(result);
}

const number = parseInt(prompt("Enter an integer:"));


const replacedNumber = replaceZerosWithOnes(number);

console.log(‘After replacing 0’s with 1’s: ${replacedNumber}‘);


------------------------------------------------------------------------------------------------------
34)Binary to decimal conversion
=====================================
function binaryToDecimal(binary) {
return parseInt(binary, 2);
}

const binaryNumber = prompt("Enter a binary number:");


const decimalNumber = binaryToDecimal(binaryNumber);

console.log(‘Decimal equivalent of ${binaryNumber} is: ${decimalNumber}‘);


------------------------------------------------------------------------------------------------------
35)Decimal to binary conversion
===================================
function decimalToBinary(decimal) {
return decimal.toString(2);
}

const decimalNumber = parseInt(prompt("Enter a decimal number:"));


const binaryNumber = decimalToBinary(decimalNumber);

console.log(‘Binary equivalent of ${decimalNumber} is: ${binaryNumber}‘);


---------------------------------------------------------------------------------------------------------
36)Decimal to octal conversion
===============================
function decimalToOctal(decimal) {
return decimal.toString(8);
}

const decimalNumber = parseInt(prompt("Enter a decimal number:"));


const octalNumber = decimalToOctal(decimalNumber);

console.log(‘Octal equivalent of ${decimalNumber} is: ${octalNumber}‘);


---------------------------------------------------------------------------------------------------------
37)Octal to decimal conversion
================================
function octalToDecimal(octal) {
return parseInt(octal, 8);
}

const octalNumber = prompt("Enter an octal number:");


const decimalNumber = octalToDecimal(octalNumber);

console.log(‘Decimal equivalent of ${octalNumber} is: ${decimalNumber}‘);


---------------------------------------------------------------------------------------------------------
38)Binary to octal conversion
==============================
function binaryToOctal(binary) {
const decimal = parseInt(binary, 2);
return decimal.toString(8);
}

const binaryNumber = prompt("Enter a binary number:");


const octalNumber = binaryToOctal(binaryNumber);

console.log(‘Octal equivalent of ${binaryNumber} is: ${octalNumber}‘);


----------------------------------------------------------------------------------------------------------
39)Octal to binary conversion
================================
function octalToBinary(octal) {
const decimal = parseInt(octal, 8);
return decimal.toString(2);
}

const octalNumber = prompt("Enter an octal number:");


const binaryNumber = octalToBinary(octalNumber);

console.log(‘Binary equivalent of ${octalNumber} is: ${binaryNumber}‘);


----------------------------------------------------------------------------------------------------------
40)Maximum number of handshakes
=================================
const n = parseInt(prompt("Enter the number of people in the group:"));

if (n >= 2) {
const maxHandshakes = (n * (n - 1)) / 2;
console.log(‘The maximum number of handshakes in a group of ${n} people is: ${maxHandshakes}‘);
} else {
console.log("Please enter a valid number of people (at least 2).");
}
----------------------------------------------------------------------------------------------------------
41)Quadrants in which coordinates lie
======================================
const x = parseFloat(prompt("Enter the x-coordinate:"));
const y = parseFloat(prompt("Enter the y-coordinate:"));

if (x > 0 && y > 0) {


console.log(‘The point (${x}, ${y}) lies in the first quadrant.‘);
} else if (x < 0 && y > 0) {
console.log(‘The point (${x}, ${y}) lies in the second quadrant.‘);
} else if (x < 0 && y < 0) {
console.log(‘The point (${x}, ${y}) lies in the third quadrant.‘);
} else if (x > 0 && y < 0) {
console.log(‘The point (${x}, ${y}) lies in the fourth quadrant.‘);
} else if (x === 0 && y !== 0) {
console.log(‘The point (${x}, ${y}) lies on the y-axis.‘);
} else if (x !== 0 && y === 0) {
console.log(‘The point (${x}, ${y}) lies on the x-axis.‘);
} else {
console.log(‘The point (${x}, ${y}) is the origin (0, 0).‘);
}
-----------------------------------------------------------------------------------------------------------
42)Convert digit/number to words
==================================
function numberToWords(number) {
const units = ["", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"];
const teens = ["", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen
", "Nineteen"];
const tens = ["", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"];

if (number === 0) {
return "Zero";
}

if (number < 10) {


return units[number];
}

if (number < 20) {


return teens[number - 10];
}

if (number < 100) {


return tens[Math.floor(number / 10)] + (number % 10 !== 0 ? " " + units[number % 10] : "");
}

if (number < 1000) {


return units[Math.floor(number / 100)] + " Hundred" + (number % 100 !== 0 ? " and " + numberToWords
(number % 100) : "");
}

return "Number out of range";


}

const number = parseInt(prompt("Enter a number (up to 999):"));

if (number >= 0 && number <= 999) {


const words = numberToWords(number);
console.log(‘${number} in words: ${words}‘);
} else {
console.log("Please enter a number between 0 and 999.");
}
--------------------------------------------------------------------------------------------------------------------------------------
43)Number of days in a given month of a given year
====================================================
function isLeapYear(year) {
return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
}

function getDaysInMonth(month, year) {


const daysInMonth = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

if (month === 2 && isLeapYear(year)) {


return 29;
}

return daysInMonth[month];
}

const year = parseInt(prompt("Enter a year:"));


const month = parseInt(prompt("Enter a month (1-12):"));

if (month >= 1 && month <= 12) {


const days = getDaysInMonth(month, year);
console.log(‘Number of days in ${month}/${year}: ${days}‘);
} else {
console.log("Invalid month. Please enter a month between 1 and 12.");
}
-------------------------------------------------------------------------------------------------
44)Permutations in which n people can occupy r seats in a classroom
====================================================================
function factorial(num) {
if (num === 0 || num === 1) {
return 1;
}
return num * factorial(num - 1);
}

function permutations(n, r) {
if (n < r) {
return 0;
}
return factorial(n) / factorial(n - r);
}

const n = parseInt(prompt("Enter the total number of people (n):"));


const r = parseInt(prompt("Enter the number of seats (r):"));

const numPermutations = permutations(n, r);

console.log(‘Number of permutations: ${numPermutations}‘);


------------------------------------------------------------------------------------------------------------
45)Number of times x digit occurs in each and every number from 0 to n
========================================================================
function countDigitOccurrences(n, x) {
let count = 0;

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


count += countDigit(i, x);
}

return count;
}

function countDigit(number, digit) {


let count = 0;

while (number > 0) {


if (number % 10 === digit) {
count++;
}
number = Math.floor(number / 10);
}

return count;
}

const n = parseInt(prompt("Enter a number (n):"));


const x = parseInt(prompt("Enter a digit (x):"));

const occurrences = countDigitOccurrences(n, x);

console.log(‘The digit ${x} occurs ${occurrences} times in each number from 0 to ${n}.‘);
------------------------------------------------------------------------------------------------------------
46)Number of integers which has exactly x divisors between a given interval
===========================================================================
function countDivisors(number) {
let count = 0;

for (let i = 1; i <= number; i++) {


if (number % i === 0) {
count++;
}
}

return count;
}
function countIntegersWithXDivisorsInRange(start, end, x) {
let count = 0;

for (let num = start; num <= end; num++) {


if (countDivisors(num) === x) {
count++;
}
}

return count;
}

const start = parseInt(prompt("Enter the start of the interval:"));


const end = parseInt(prompt("Enter the end of the interval:"));
const x = parseInt(prompt("Enter the number of divisors (x):"));

const integersWithXDivisors = countIntegersWithXDivisorsInRange(start, end, x);

console.log(‘Number of integers with exactly ${x} divisors between ${start} and ${end}: ${integersWithXDi
visors}‘);
--------------------------------------------------------------------------------------------------------------------
47)Roots of a quadratic equation
=================================
function calculateQuadraticRoots(a, b, c) {
const discriminant = b * b - 4 * a * c;

if (discriminant > 0) {
const root1 = (-b + Math.sqrt(discriminant)) / (2 * a);
const root2 = (-b - Math.sqrt(discriminant)) / (2 * a);
return [root1, root2];
} else if (discriminant === 0) {
const root = -b / (2 * a);
return [root];
} else {
return [];
}
}

const a = parseFloat(prompt("Enter the coefficient of x^2 (a):"));


const b = parseFloat(prompt("Enter the coefficient of x (b):"));
const c = parseFloat(prompt("Enter the constant term (c):"));

const roots = calculateQuadraticRoots(a, b, c);

if (roots.length === 0) {
console.log("The quadratic equation has no real roots.");
} else if (roots.length === 1) {
console.log(‘The quadratic equation has one real root: ${roots[0]}‘);
} else {
console.log(‘The quadratic equation has two real roots: ${roots[0]} and ${roots[1]}‘);
}
---------------------------------------------------------------------------------------------------------
48)Count possible decoding of a given digit sequence
=====================================================
function countDecodings(digits) {
const n = digits.length;
const dp = new Array(n + 1).fill(0);

dp[n] = 1;
dp[n - 1] = digits[n - 1] !== ’0’ ? 1 : 0;

for (let i = n - 2; i >= 0; i--) {


if (digits[i] !== ’0’) {
dp[i] += dp[i + 1];

if (parseInt(digits[i] + digits[i + 1]) <= 26) {


dp[i] += dp[i + 2];
}
}
}

return dp[0];
}

const digitSequence = prompt("Enter a digit sequence:");

const count = countDecodings(digitSequence);

console.log(‘Number of possible decodings: ${count}‘);


------------------------------------------------------------------------------------------------
49)Arrays and linked lists are both data structures used to store collections of elements, but they differ in t
erms of their characteristics, operations, and performance. Let’s explore the differences between arrays a
nd linked lists:

**Arrays:**
1. **Memory Allocation:** Arrays allocate a contiguous block of memory to store elements. Elements are s
tored consecutively in memory.
2. **Access Time:** Accessing elements by index is fast and constant time \(O(1)\) because you can calc
ulate the memory address directly.
3. **Insertion/Deletion:** Insertions and deletions can be slow (\(O(n)\)) because elements may need to b
e shifted to accommodate new elements or fill gaps.
4. **Size:** Arrays have a fixed size when created. Some programming languages offer dynamic arrays th
at can resize, but resizing usually involves creating a new larger array and copying elements.
5. **Memory Efficiency:** Arrays can be less memory-efficient, especially when dealing with dynamic resi
zing.
6. **Common Usage:** Arrays are commonly used when you know the size of the collection in advance a
nd need fast random access.

**Linked Lists:**
1. **Memory Allocation:** Linked lists do not require a contiguous block of memory. Elements are stored i
n nodes, and each node contains the element and a reference to the next (and sometimes previous) node
.
2. **Access Time:** Accessing elements is slower, often linear time \(O(n)\), as you have to traverse the li
st from the beginning or end.
3. **Insertion/Deletion:** Insertions and deletions are fast (\(O(1)\)) if you’re working with the head or tail o
f the list. Otherwise, they are generally faster than arrays because you can adjust pointers to insert or del
ete elements.
4. **Size:** Linked lists can dynamically grow and shrink as elements are added or removed.
5. **Memory Efficiency:** Linked lists can be more memory-efficient when elements are frequently inserte
d or removed, as no need to preallocate a large block of memory.
6. **Common Usage:** Linked lists are commonly used when you need efficient insertions and deletions,
especially in dynamic scenarios where the size can change frequently.

To summarize, arrays are generally better for scenarios where you need fast random access and know th
e size of the collection in advance. Linked lists are more suitable when you require efficient insertions and
deletions,
especially in dynamic scenarios where the size can change frequently. The choice between arrays and lin
ked lists depends on the specific requirements of your application.
--------------------------------------------------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------
50)Write a code to reverse a string without using the built in method.
=======================================================================
function reverseString(str) {
let reversed = ’’;
for (let i = str.length - 1; i >= 0; i--) {
reversed += str[i];
}
return reversed;
}

const input = prompt("Enter a string:");


const reversedString = reverseString(input);

console.log(‘Original string: ${input}‘);


console.log(‘Reversed string: ${reversedString}‘);
-----------------------------------------------------------------------------------------------------------
51)Write a code to get the length of a string without using string property
============================================================================
function getStringLength(str) {
let count = 0;
for (let char of str) {
count++;
}
return count;
}

const input = prompt("Enter a string:");


const length = getStringLength(input);

console.log(‘Length of the string: ${length}‘);


------------------------------------------------------------------------------------------------------------
52)Write a code to reverse a string
====================================
i)
// Function to reverse string
function ReverseString(str) {
return str.split(’’).reverse().join(’’)
}

// Function call
console.log(ReverseString("Geeks for Geeks"))
ii)
const str = "Geeks for Geeks";
const reversedStr = [...str].reverse().join("");
console.log(reversedStr);
-------------------------------------------------------------------------------------------------------------
53)Write a code to swipe the character
=========================================
function swapCharacters(str, index1, index2) {
if (index1 < 0 || index1 >= str.length || index2 < 0 || index2 >= str.length) {
console.log("Invalid indices");
return str;
}

const charArray = str.split(’’);


const temp = charArray[index1];
charArray[index1] = charArray[index2];
charArray[index2] = temp;

return charArray.join(’’);
}

const input = prompt("Enter a string:");


const index1 = parseInt(prompt("Enter index of first character to swap:"));
const index2 = parseInt(prompt("Enter index of second character to swap:"));

const swappedString = swapCharacters(input, index1, index2);

console.log(‘Original string: ${input}‘);


console.log(‘String after swapping characters: ${swappedString}‘);
-------------------------------------------------------------------------------------------------------
54)Write a program, using INHERITANCE - using overloading & overriding
=======================================================================
class Shape {
constructor() {
this.name = "Shape";
}

calculateArea() {
return 0;
}

toString() {
return ‘This is a ${this.name}‘;
}
}

class Circle extends Shape {


constructor(radius) {
super();
this.name = "Circle";
this.radius = radius;
}

calculateArea() {
return Math.PI * this.radius * this.radius;
}
}
class Rectangle extends Shape {
constructor(width, height) {
super();
this.name = "Rectangle";
this.width = width;
this.height = height;
}

calculateArea() {
return this.width * this.height;
}
}

const circle = new Circle(5);


const rectangle = new Rectangle(4, 6);

console.log(circle.toString());
console.log(‘Area of the circle: ${circle.calculateArea()}‘);

console.log(rectangle.toString());
console.log(‘Area of the rectangle: ${rectangle.calculateArea()}‘);
----------------------------------------------------------------------------------------------------------------------
54)Numbers will be given - a lot of them in diamond shape with increments in sequence.
================================================================================
=======
function generateDiamondPattern(rows) {
if (rows % 2 === 0) {
console.log("Please provide an odd number of rows for a symmetric diamond.");
return;
}

const midRow = Math.floor(rows / 2) + 1;

for (let i = 1; i <= rows; i++) {


const spaces = Math.abs(midRow - i);
const numbers = rows - spaces * 2;

let output = "";

for (let j = 1; j <= spaces; j++) {


output += " ";
}

for (let k = 1; k <= numbers; k++) {


output += (k % 10); // Display single-digit numbers
}

console.log(output);
}
}

const rows = parseInt(prompt("Enter the number of rows (should be an odd number):"));


generateDiamondPattern(rows);
------------------------------------------------------------------------------------------------------------
55)Number of sequences is given - find the missing number.
===========================================================
function findMissingNumber(sequence) {
const n = sequence.length + 1; // One number is missing
const totalSum = (n * (n + 1)) / 2; // Sum of first n natural numbers

const sequenceSum = sequence.reduce((sum, num) => sum + num, 0);

return totalSum - sequenceSum;


}

const sequence = [1, 2, 4, 5, 6]; // Example sequence


const missingNumber = findMissingNumber(sequence);

console.log(‘The missing number is: ${missingNumber}‘);


---------------------------------------------------------------------------------------------------------------
56)Write the coding part of alphabets and numbers in given alphanumeric string.
================================================================================
=
function countAlphabetsAndNumbers(inputString) {
let alphabetCount = 0;
let numberCount = 0;

for (let i = 0; i < inputString.length; i++) {


const char = inputString[i];
if (/[a-zA-Z]/.test(char)) {
alphabetCount++;
} else if (/[0-9]/.test(char)) {
numberCount++;
}
}

return [alphabetCount, numberCount];


}

const input = prompt("Enter a string:");


const [alphabets, numbers] = countAlphabetsAndNumbers(input);

console.log(‘Number of alphabets: ${alphabets}‘);


console.log(‘Number of numbers: ${numbers}‘);
-------------------------------------------------------------------------------------------------------
57)Matrix creation,addition,multiplication
==============================================
function createMatrix(rows, cols) {
const matrix = [];
for (let i = 0; i < rows; i++) {
const row = [];
for (let j = 0; j < cols; j++) {
row.push(Math.floor(Math.random() * 10)); // Fill with random numbers (0-9)
}
matrix.push(row);
}
return matrix;
}

function addMatrices(matrix1, matrix2) {


const rows = matrix1.length;
const cols = matrix1[0].length;
const result = [];

for (let i = 0; i < rows; i++) {


const row = [];
for (let j = 0; j < cols; j++) {
row.push(matrix1[i][j] + matrix2[i][j]);
}
result.push(row);
}

return result;
}

function multiplyMatrices(matrix1, matrix2) {


const rows1 = matrix1.length;
const cols1 = matrix1[0].length;
const rows2 = matrix2.length;
const cols2 = matrix2[0].length;
const result = [];

if (cols1 !== rows2) {


console.log("Matrices cannot be multiplied.");
return result;
}

for (let i = 0; i < rows1; i++) {


const row = [];
for (let j = 0; j < cols2; j++) {
let sum = 0;
for (let k = 0; k < cols1; k++) {
sum += matrix1[i][k] * matrix2[k][j];
}
row.push(sum);
}
result.push(row);
}

return result;
}

function displayMatrix(matrix) {
for (let i = 0; i < matrix.length; i++) {
console.log(matrix[i].join(" "));
}
}

const rows = parseInt(prompt("Enter the number of rows:"));


const cols = parseInt(prompt("Enter the number of columns:"));

const matrixA = createMatrix(rows, cols);


const matrixB = createMatrix(rows, cols);

console.log("Matrix A:");
displayMatrix(matrixA);

console.log("Matrix B:");
displayMatrix(matrixB);

const sumMatrix = addMatrices(matrixA, matrixB);


console.log("Sum of Matrices:");
displayMatrix(sumMatrix);

const productMatrix = multiplyMatrices(matrixA, matrixB);


console.log("Product of Matrices:");
displayMatrix(productMatrix);
----------------------------------------------------------------------------------------------------------

You might also like