0% found this document useful (0 votes)
58 views

Domain Fundamentals Assignments

The document contains 14 programming assignments involving basic operations like accepting user input, performing arithmetic operations, conditional checking, loops, arrays, strings, etc. The key tasks include: 1. Accepting user input and displaying output 2. Performing arithmetic operations like addition, subtraction on inputs 3. Checking conditions and printing output based on conditional logic 4. Using loops like for loops to iterate through arrays/numbers 5. Performing operations on arrays like sorting, counting elements, swapping etc. 6. Checking properties of strings like palindromes 7. Solving problems using different constructs like switch case

Uploaded by

Abi Coolboy
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
58 views

Domain Fundamentals Assignments

The document contains 14 programming assignments involving basic operations like accepting user input, performing arithmetic operations, conditional checking, loops, arrays, strings, etc. The key tasks include: 1. Accepting user input and displaying output 2. Performing arithmetic operations like addition, subtraction on inputs 3. Checking conditions and printing output based on conditional logic 4. Using loops like for loops to iterate through arrays/numbers 5. Performing operations on arrays like sorting, counting elements, swapping etc. 6. Checking properties of strings like palindromes 7. Solving problems using different constructs like switch case

Uploaded by

Abi Coolboy
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 46

Assignments

1. Accept a char input from the user and display it on the console.

const prompt =require("prompt-sync")();


var name= prompt("Enter your name:");
console.log("Your name is +",name);

2. Accept two inputs from the user and output their sum.

Variable Data Type

Number 1 Integer

Number 2 Float

Sum Float

const prompt =require("prompt-sync")();

var num1=prompt("Enter first number:");


var num2=prompt("Enter second number:");
var sum=parseInt(num1)+parseInt(num2);
console.log("Sum of 2 numbers is :"+sum);

3. Write a program to find the simple interest.

a. Program should accept 3 inputs from the user and calculate simple interest for
the given inputs. Formula: SI=(P*R*n)/100)

Variable Data Type

Principal amount (P) Integer

Interest rate (R) Float

Number of years (n) Float

Simple Interest (SI) Float

const prompt =require("prompt-sync")();

var principal=parseInt(prompt("Enter principal amount:"));


var rate=parseInt(prompt("Enter rate:"));
var years=parseInt(prompt("Enter number of years:"));
var si=(principal*rate*years)/100
console.log("Simple Interest is "+si);
4. Write a program to check whether a student has passed or failed in a subject after he
or she enters their mark (pass mark for a subject is 50 out of 100).

a. Program should accept an input from the user and output a message as
“Passed” or “Failed”

Variable Data type

mark float

const prompt =require("prompt-sync")();

var mark = parseInt(prompt("Enter marks out of 100: "))


if(mark>=50){
console.log("Passed")
}else{
console.log("Failed")
}
5. Write a program to show the grade obtained by a student after he/she enters their
total mark percentage.

a. Program should accept an input from the user and display their grade as
follows

Mark Grade

> 90 A

80-89 B

70-79 C

60-69 D

50-59 E

< 50 Failed

Variable Data type

Total mark float

const prompt =require("prompt-sync")();

var mark = parseInt(prompt("Enter marks out of 100: "))


if(mark<50){
console.log("Failed")
}else if(mark<60){
console.log("E")
}else if(mark<70){
console.log("D")
}else if(mark<80){
console.log("C")
}else if(mark<90){
console.log("B")
}else if(mark>=90){
console.log("A")
}

6. Using the ‘switch case’ write a program to accept an input number from the user and
output the day as follows.

Input Output
1 Sunday

2 Monday

3 Tuesday

4 Wednesday

5 Thursday

6 Friday

7 Saturday

Any other input Invalid Entry

const prompt =require("prompt-sync")();

var choice
=parseInt(prompt("1.Sunday\n2.Monday\n3.Tuesday\n4.Wednesday\n5
.Thursday\n6.Friday\n7.Saturday\nEnter your choice : "));
switch(choice){
case 1:
console.log("Sunday");
break;
case 2:
console.log("Monday");
break;
case 3:
console.log("Tuesday");
break;
case 4:
console.log("Wednesday");
break;
case 5:
console.log("Thursday");
break;
case 6:
console.log("Friday");
break;
case 7:
console.log("Saturday");
break;
default:
console.log("Invalid entry");
break;
}

7. Write a program to print the multiplication table of given numbers.

a. Accept an input from the user and display its multiplication table

Eg:

Output: Enter a number

Input: 5

Output:

1x5=5

2 x 5 = 10
3 x 5 = 15

4 x 5 = 20

5 x 5 = 25

6 x 5 = 30

7 x 5 = 35

8 x 5 = 40

9 x 5 = 45

10 x 5 = 50

const prompt =require("prompt-sync")();

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


for(i=1;i<=10;i++)
{
console.log(`${i} x ${number}=${i*number}`);

8. Write a program to find the sum of all the odd numbers for a given limit
a. Program should accept an input as limit from the user and display the sum
of all the odd numbers within that limit

For example if the input limit is 10 then the result is 1+3+5+7+9 = 25

Output: Enter a limit

Input: 10

Output: Sum of odd numbers = 25

const prompt =require("prompt-sync")();

var limit=parseInt(prompt("Enter a limit:"));


var sum=0;
for(i=1;i<=limit;i++)
{
if(i%2!==0)
{
sum+=i;
}

}
console.log("Sum is "+sum);
9. Write a program to print the following pattern (hint: use nested loop)

12

123

1234

12345

var pattern=""
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
pattern+=j;

}
pattern+="\n"

}
console.log(pattern);

10. Write a program to interchange the values of two arrays.


a. Program should accept an array from the user, swap the values of two arrays
and display it on the console

Eg: Output: Enter the size of arrays

Input: 5

Output: Enter the values of Array 1

Input: 10, 20, 30, 40, 50

Output: Enter the values of Array 2

Input: 15, 25, 35, 45, 55

Output: Arrays after swapping:

Array1: 15, 25, 35, 45, 55

Array2: 10, 20, 30, 40, 50

const prompt =require("prompt-sync")();

var size = parseInt(prompt("Enter the size of arrays : "))


var array1=[]
var array2=[]
var temp
console.log("Enter elements of array 1 :")
for(let i=0;i<size;i++){
array1[i] = parseInt(prompt(""))
}
console.log("enter elements of array 2 :")
for(let i=0;i<size;i++){
array2[i] = parseInt(prompt(""))
}
console.log("array1 = "+array1)
console.log("array2 = "+array2)
console.log("array after swapping")
for(var i=0;i<size;i++)
{
temp=array1[i]
array1[i]=array2[i]
array2[i]=temp
}
console.log("array1 = "+array1)
console.log("array2 = "+array2)

11. Write a program to find the number of even numbers in an array

a. Program should accept an array and display the number of even numbers
contained in that array

Eg: Output: Enter the size of an array

Input: 5

Output: Enter the values of array

Input: 11, 20, 34, 50, 33

Output: Number of even numbers in the given array is 3


const prompt =require("prompt-sync")();

var size = parseInt(prompt("Enter the size of array : "));


var array=[];
var count=0;
console.log("Enter "+size+" elements");
for(var i=0;i<size;i++){
array[i] = parseInt(prompt(""));
if(array[i]%2==0){
count+=1;
}
}
console.log("Number of even numbers in the given array is "+count)

12. Write a program to sort an array in descending order

a. Program should accept and array, sort the array values in descending order
and display it

Eg: Output: Enter the size of an array

Input: 5

Output: Enter the values of array

Input: 20, 10, 50, 30, 40

Output: Sorted array:


50, 40, 30, 20, 10

const prompt =require("prompt-sync")();

var size = parseInt(prompt("Enter the size of array : "));


var array=[];
var temp;
console.log("Enter "+size+" elements")
for(var i=0;i<size;i++){
array[i] = parseInt(prompt(""))
}
for(var i=0;i<size-1;i++){
for(var j=i+1;j<size;j++){
if(array[i]<array[j]){
temp = array[i];
array[i]=array[j];
array[j] = temp;
}
}
}
console.log("Sorted array is: "+array);

13. Write a program to identify whether a string is a palindrome or not

a. A string is a palindrome if it reads the same backward or forward eg:


MALAYALAM
Program should accept a string and display whether the string is a
palindrome or not

Eg: Output: Enter a string

Input: MALAYALAM

Output: Entered string is a palindrome

Eg 2: Output: Enter a string

Input: HELLO

Output: Entered string is not a palindrome

const prompt =require("prompt-sync")();


var string = prompt("Enter a word:");
var size = string.length;
var flag = 0
for( let i=0;i<=size/2;i++){
if(string[i] !=string[size-i-1]){
flag = 1;
break
}
}
if(flag==1){
console.log("String is not palindrome")
}
else{
console.log("String is palindrome")
}

14. Write a program to add to two dimensional arrays


a. Program should accept two 2D arrays and display its sum

Eg: Output: Enter the size of arrays

Input: 3

Output: Enter the values of array 1

Input:

123

456

789

Output: Enter the values of array 2

Input:

10 20 30

40 50 60

70 80 90

Output: Sum of 2 arrays is:

11 22 33

44 55 66

77 88 99

const prompt =require("prompt-sync")();

const limit = prompt("Enter the size of array : ")


let array1 = []
let array2 = []
let arraysum = []
let rows = limit
let columns = limit
console.log("Enter the values of array 1")
for (var i = 0; i < rows; i++) {
array1.push([i])
for (var j = 0; j < columns; j++) {
array1[i][j] = prompt("")
}
}
console.log("Enter the values of array 2")
for (var i = 0; i < rows; i++) {
array2.push([i])
for (var j = 0; j < columns; j++) {
array2[i][j] = prompt("")
}
}
for (var i = 0; i < rows; i++) {
arraysum.push([i])
for (var j = 0; j < columns; j++) {
arraysum[i][j] =
parseInt(array1[i][j])+parseInt(array2[i][j])
}
}
//function
const toString = m => JSON.stringify(m)
.replace(/(\[\[)(.*)(]])/g, '\n [$2]\n')
.replace(/],/g, '\n ')
console.log("Array 1 is"+toString(array1))
console.log("Array 2 is"+toString(array2))
console.log("Sum of array is"+toString(arraysum))
15. Write a program to accept an array and display it on the console using functions

a. Program should contain 3 functions including main() function

main()

1. Declare an array
2. Call function getArray()
3. Call function displayArray()
getArray()

1. Get values to the array

displayArray()

1. Display the array values

const prompt =require("prompt-sync")();

const size = prompt("Enter the size of array : ");


let array1 = [];
let rows = size;
let columns = size;
getArray(array1,rows,columns);
displayArray();
//function
function getArray(array,row,column){
console.log("Enter the values of array")
for (var i = 0; i < rows; i++) {
array1.push([i])
for (var j = 0; j < columns; j++) {
array1[i][j] = prompt("")
}
}
}
function displayArray(){
const toString = m =>
JSON.stringify(m).replace(/(\[\[)(.*)(]])/g, '\n
[$2]\n').replace(/],/g, '\n ');
console.log("Array is"+toString(array1))
}
16. Write a program to check whether a given number is prime or not

a. Program should accept an input from the user and display whether the
number is prime or not

Eg: Output: Enter a number

Input: 7

Output: Entered number is a Prime number

const prompt =require("prompt-sync")();

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


let flag = 0;
for(var i=2;i<=num1/2;i++){
if(num1%i==0){
flag = 1;
break;
}
}
if(flag==1){
console.log("Entered number is not prime");
}
else{
console.log("Entered number is prime");
}

17. Write a menu driven program to do the basic mathematical operations such as
addition, subtraction, multiplication and division (hint: use if else ladder or switch)

a. Program should have 4 functions named addition(), subtraction(),


multiplication() and division()
b. Should create a class object and call the appropriate function as user prefers
in the main function

const prompt =require("prompt-sync")();

class Operations {
constructor(numa,numb){
this.num1 = numa
this.num2 = numb
}
addition(numa,numb){
return numa + numb
}
subtraction(numa,numb){
return numa - numb
}
multiplication(numa,numb){
return numa * numb
}
division(numa,numb){
return numa / numb
}
}
let newOperations = new Operations();
let num1 = parseInt(prompt("enter first number:"))
let num2 = parseInt(prompt("enter second number:"))
let sum

let ch
=parseInt(prompt("1.addition\n2.subtraction\n3.multiplication\n
4.division\nEnter your choice: "))
switch(ch){
case 1:
sum = newOperations.addition(num1,num2);
break;
case 2:
sum = newOperations.subtraction(num1,num2);
break;
case 3:
sum = newOperations.multiplication(num1,num2);
break;
case 4:
sum = newOperations.division(num1,num2)
break;
default:
console.log("invalid entry")
break;
}
console.log("result = "+sum);
18. Grades are computed using a weighted average. Suppose that the written test
counts 70%, lab exams 20% and assignments 10%.

If Arun has a score of

Written test = 81

Lab exams = 68

Assignments = 92

Arun’s overall grade = (81x70)/100 + (68x20)/100 + (92x10)/100 = 79.5

Write a program to find the grade of a student during his academic year.

a. Program should accept the scores for written test, lab exams and
assignments
b. Output the grade of a student (using weighted average)

Eg:

Enter the marks scored by the students

Written test = 55

Lab exams = 73
Assignments = 87

Grade of the student is 61.8

const prompt =require("prompt-sync")();

console.log("Enter the marks scored by student")


let written = parseInt(prompt("Written test = "))
let lab = parseInt(prompt("Lab exams = "))
let assignments = parseInt(prompt("Assignments = "))
let grade = (written * 70)/100 + (lab * 20)/100 +
(assignments*10)/100
console.log("overall grade = "+grade)

19. Income tax is calculated as per the following table

Annual Income Tax percentage

Up to 2.5 Lakhs No Tax

Above 2.5 Lakhs to 5 5%


Lakhs

Above 5 Lakhs to 10 20%


Lakhs

Above 10 Lakhs to 50 30%


Lakhs

Write a program to find out the income tax amount of a person.


a. Program should accept annual income of a person
Output the amount of tax he has to pay

Eg 1:
Enter the annual income
495000
Income tax amount = 24750.00

Eg 2:
Enter the annual income
500000
Income tax amount = 25000.00

const prompt =require("prompt-sync")();


let tax
console.log("Enter the annual income:")
let income = parseInt(prompt(""))
if(income < 250000){
tax = "no tax"
}else if(income < 500000){
tax = income * 0.05
}else if(income < 1000000){
tax = income * 0.2
}else if(income > 5000000){
tax = income * 0.3
}
console.log("Income tax amount = "+tax)
20. Write a program to print the following pattern using for loop

2 3

4 5 6

7 8 9 10

let n = 5
let string = "";
let num = 1;
for (let i = 1; i < n; i++) {
for (let j = 1; j <= i; j++) {
string += " "+num;
num++
}
string += "\n";
}
console.log(string);
21.

21. Write a program to multiply the adjacent values of an array and store it in an
another array

a. Program should accept an array


b. Multiply the adjacent values
c. Store the result into another array

Eg:

Enter the array limit

Enter the values of array

1 2 3 4 5

Output

2 6 12 20

const prompt =require("prompt-sync")();

let limit = parseInt(prompt("Enter the array limit: "))


let array1 = [];
let array2 = [];
console.log("Enter the values of array:")
for (var i = 0 ; i < limit ; i++){
array1[i] = parseInt(prompt(""))
}
console.log(array1)
for (var i = 0 ; i < limit-1 ; i++){
array2[i] = (array1[i] * array1[i+1])
}
console.log(array2)
22. Write a program to add the values of two 2D arrays

a. Program should contains 3 functions including the main function

main()

1. Call function getArray()


2. Call function addArray()
3. Call function displayArray()

getArray()

1. Get values to the array

getArray()

1. Add array 1 and array 2

displayArray()

1. Display the array values

Eg:

Enter the size of array

2
Enter the values of array 1

1 2

3 4

Enter the values of array 2

5 6

7 8

Output:

Sum of array 1 and array 2:

6 8

10 12

const prompt =require("prompt-sync")();

const limit = prompt("Enter the size of array : ")


let array1 = []
let array2 = []
let arraysum = []
let rows = limit
let columns = limit
function getArray(){
console.log("Enter the values of array 1:")
for (var i = 0; i < rows; i++) {
array1.push([i])
for (var j = 0; j < columns; j++) {
array1[i][j] = prompt("")
}
}
console.log("Enter the values of array 2:")
for (var i = 0; i < rows; i++) {
array2.push([i])
for (var j = 0; j < columns; j++) {
array2[i][j] = prompt("")
}
}
}
function addArray(){
for (var i = 0; i < rows; i++) {
arraysum.push([i])
for (var j = 0; j < columns; j++) {
arraysum[i][j] =
parseInt(array1[i][j])+parseInt(array2[i][j])
}
}
}
function displayArray(){
console.log("sum of array 1 and array 2: "+toString(arraysum))
}
//function
const toString = m => JSON.stringify(m)
.replace(/(\[\[)(.*)(]])/g, '\n [$2]\n')
.replace(/],/g, '\n ')
getArray()
addArray()
displayArray()
23. Write an object oriented program to store and display the values of a 2D array

a. Program should contains 3 functions including the main function

main()

1. Declare an array
2. Call function getArray()
3. Call function displayArray()

getArray()

1. Get values to the array

displayArray()
1. Display the array values

Eg:

Enter the size of array

Enter the array values

1 2 3

4 5 6

7 8 9

Array elements are:

1 2 3

4 5 6

7 8 9

const prompt =require("prompt-sync")();

const limit = prompt("Enter the size of array : ")


let array1 = []
let rows = limit
let columns = limit
function getArray(){
console.log("Enter the values of array:")
for (var i = 0; i < rows; i++) {
array1.push([i])
for (var j = 0; j < columns; j++) {
array1[i][j] = prompt("")
}
}
}
function displayArray(){
console.log("Array elements are : "+toString(array1))
}
//function
const toString = m => JSON.stringify(m)
.replace(/(\[\[)(.*)(]])/g, '\n [$2]\n')
.replace(/],/g, '\n ')
getArray()
displayArray()

24. Write a menu driven program to calculate the area of a given object.

a. Program should contain two classes


i. Class 1: MyClass
ii. Class 2: Area
b. Class MyClass should inherit class Area and should contain the following
functions
i. main()
ii. circle()
iii. square()
iv. rectangle()
v. triangle()
c. Class Area should contain the following functions to calculate the area of
different objects
i. circle()
ii. square()
iii. rectangle()
iv. triangle()

Class MyClass extends Area{

public static void main(string args[]){

circle() {

square() {

rectangle() {

triangle() {

}
}

Class Area{

circle(){

square(){

rectangle() {

triangle() {

Eg 1:

Enter your choice

1. Circle
2. Square
3. Rectangle
4. Triangle

2
Enter the length

Output

Area of the square is: 4

Eg 2:

Enter your choice

1. Circle
2. Square
3. Rectangle
4. Triangle

Enter the radius

Output

Area of the circle is: 28.26

const prompt =require("prompt-sync")();

let area
class Area {
circle(){
let radius = parseInt(prompt("Enter radius: "))
area = 3.14 * radius * radius
return area
}
square(){
let width = parseInt(prompt("Enter the length:"))
area = width * width
return width
}
rectangle(){
let length = parseInt(prompt("Enter the length:"))
let breadth = parseInt(prompt("Enter the breadth:"))
area = length * breadth
return area
}
triangle(){
let length = parseInt(prompt("Enter the length:"))
let height = parseInt(prompt("Enter the height:"))
area = .5 * length * height
return area
}
}
class MyClass extends Area{
}
let obj = new MyClass();
let ch =
parseInt(prompt("1.Circle\n2.Square\n3.Rectangle\n4.Triangle\nEnte
r your choice: "))
switch(ch){
case 1:
obj.circle()
break;
case 2:
obj.square()
break;
case 3:
obj.rectangle()
break;
case 4:
obj.triangle()
break;
default:
console.log("Invalid entry")
break;
}
console.log("Area = "+area);

25. Write a Javascript program to display the status (I.e. display book name, author
name & reading status) of books. You are given an object library in the code's template. It
contains a list of books with the above mentioned properties.Your task is to display the
following:

● If the book is unread:


You still need to read '<book_name>' by <author_name>.
● If the book is read:
Already read '<book_name>' by <author_name>.

var library = [

title: 'Bill Gates',

author: 'The Road Ahead',


readingStatus: true

},

title: 'Steve Jobs',

author: 'Walter Isaacson',

readingStatus: true

},

title: 'Mockingjay: The Final Book of The Hunger Games',

author: 'Suzanne Collins',

readingStatus: false

];

const prompt =require("prompt-sync")();

var library = [
{
title: 'Bill Gates',
author: 'The Road Ahead',
readingStatus: true
},
{
title: 'Steve Jobs',
author: 'Walter Isaacson',
readingStatus: true
},
{
title: 'Mockingjay: The Final Book of The Hunger Games',
author: 'Suzanne Collins',
readingStatus: false
}
];
let ch = prompt("1.Bill Gates\n2.Steve
Jobs\n3.Mockingjay\nEnteryour choice")
if(library[ch-1].readingStatus == true){
console.log("Already read '"+library[ch-1].title+"'
by'"+library[ch-1].author+"'")
}else{
console.log("You still need to read '"+library[ch-1].title+"'by
'"+library[ch-1].author+"'")
}

26. Given a variable named my_string, try reversing the string using
my_string.split().reverse().join() and then print the reversed string to the console. If the try
clause has an error, print the error message to the console. Finally, print the typeof of the
my_string variable to the console.

Output format:

The statement to print in the tryblock is:


Reversed string is : ${my_string}

The statement to print in the catchblock is:

Error : ${err.message}

The statement to print in the finally block is:

Type of my_string is : ${typeof my_string}

Eg:

a) Sample Input 0

"1234"

Sample Output 0

Reversed string is : 4321

Type of my_string is : string

b) Sample Input 1

Number(1234)

Sample Output 1

Error : my_string.split is not a function

Type of my_string is : number

var my_string = "1234"


var message = " found"
try{
function reverseString(string) {
return string.split("").reverse().join("");
}
my_string = reverseString(my_string);
console.log(`reversed string is ${my_string}`)
}
catch($){
console.log(`Error${message}`)
}
finally{
console.log(`typeof my_string is ${typeof(my_string)}`)
}
27. Given a variable named userHeight, you must throw errors under the following

conditions:
● notANumberError- When userHeight is NaN
● HugeHeightError – When userHeight is greater than 200
● TinyHeightError - When userHeight is less than 40

Eg:
a) Sample Input 0

test
Sample Output 0

notANumberError
b) Sample Input 1

250
Sample Output 1
hugeHeightError
c) Sample Input 2
0
Sample Output 2
tinyHeightError
d) If userHeight is valid print ‘valid’

let input = require("readline-sync")


const prompt=require("prompt-sync")({signint:true});
var height = prompt("enter height: ")
try{
if(typeof(height)==NaN){
throw new notANumberError("notANumberError")
}
else if(height>10){
throw new HugeHeightError("HugeHeightError")
}
else if(height<2){
throw new TinyHeightError("TinyHeightError")
}
else{
console.log(height);
}
}
catch(e){
console.log(e.message)
}

28. Create a constructor function that satisfies the following conditions:

a. The name of the constructor function should be Car.


b. It should take three parameters: name, mileage and max_speed.
c. Store these parameter values in their respective thiskeywords:
this.name, this.mileage and this.max_speed.

let input = require("readline-sync")


const prompt =require("prompt-sync")();
let name
let mileage
let max_speed
class car{
constructor(name,mileage,max_speed){
this.name = name
this.mileage = mileage
this.max_speed = max_speed
}
getDetails(){
console.log("\ncar name: "+this.name+"\nmileage
:"+this.mileage+"\nmax speed is "+this.max_speed)
}
}
let c1 = new car("Swift",18,180);
c1.getDetails();
let c2 = new car("Mini",16,260);
c2.getDetails();

29. Write a myFilter function that takes 2 parameters: myArray and callback. Here,
myArray is an array of numbers and callback is a function that takes the elements of
myArray as its parameter and returns a boolean true if the sum of the number is even or
false if the sum of the number is odd.

The myFilter function should return the sum of the array.

a) Sample Input
12345

b) Sample Output

15

let sum = 0
function myFilter(array,call){
for(let i=0;i < array.length;i++){
sum = sum + array[i]
}
}
let callback = (s) => s % 2
let myArray = [1,2,3,4,5]
myFilter(myArray,callback)
console.log(sum)

You might also like