JS Programs
JS Programs
==========================================
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’;
}
}
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);
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;
function lcm(a, b) {
return (a * b) / gcd(a, b);
}
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 (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;
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;
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;
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;
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
if (i !== number / i) {
sum += number / i;
}
}
}
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:"));
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);
}
if (number <= 3) {
return true;
}
let i = 5;
while (i * i <= number) {
if (number % i === 0 || number % (i + 2) === 0) {
return false;
}
i += 6;
}
return true;
}
if (number <= 3) {
return true;
}
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;
}
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 = ’’;
return parseInt(result);
}
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 (number === 0) {
return "Zero";
}
return daysInMonth[month];
}
function permutations(n, r) {
if (n < r) {
return 0;
}
return factorial(n) / factorial(n - r);
}
return count;
}
return count;
}
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;
return count;
}
function countIntegersWithXDivisorsInRange(start, end, x) {
let count = 0;
return count;
}
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 [];
}
}
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;
return dp[0];
}
**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;
}
// 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;
}
return charArray.join(’’);
}
calculateArea() {
return 0;
}
toString() {
return ‘This is a ${this.name}‘;
}
}
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;
}
}
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;
}
console.log(output);
}
}
return result;
}
return result;
}
function displayMatrix(matrix) {
for (let i = 0; i < matrix.length; i++) {
console.log(matrix[i].join(" "));
}
}
console.log("Matrix A:");
displayMatrix(matrixA);
console.log("Matrix B:");
displayMatrix(matrixB);