Skip to content

Commit 0628d8e

Browse files
Update Sum of Numbers.js
1 parent 322a93c commit 0628d8e

1 file changed

Lines changed: 50 additions & 18 deletions

File tree

JavaScript Interview Programs/Sum of Numbers.js

Lines changed: 50 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -4,30 +4,62 @@
44
const a = 10;
55
const b = 20;
66
const sum = a + b;
7-
console.log("Addition of two number", sum);
7+
console.log("Addition of two number:", sum);
88
// output:
99
// Addition of two number: 30
1010

11-
// Using Function()
12-
function sum(a, b){
13-
const c = a + b;
14-
}
15-
return c;
16-
sum(4,5);
11+
// 2. Using Function()
1712

13+
// Function to calculate the sum of two numbers using a temporary variable:
14+
function Sum(a, b){
15+
const c = a + b;
16+
return c;
17+
}
18+
console.log("Sum:", Sum(4,5));
19+
// Output:
20+
// Sum: 9
1821

19-
// 2. One-Line Addition (Used for Console testing or demo purpose)
20-
Console.log(10+5);
22+
// OR
23+
24+
// Function to return the sum of two numbers directly
25+
function Sum(a, b) {
26+
return a + b;
27+
}
28+
console.log(Sum(3, 7));
2129
// Output:
22-
// 15
30+
// 10
31+
32+
// 3. Using Arrow Function
33+
// One-liner arrow function to add two numbers
34+
const add = (a, b) => a + b;
35+
console.log(add(10, 15));
36+
// Output:
37+
// 25
38+
39+
// OR
40+
41+
// Arrow function to add two numbers using a variable and return
42+
const Add = (a, b) => {
43+
const sum = a + b;
44+
return sum;
45+
}
46+
console.log("Sum of Two Number:", Add(3,2));
47+
// Output:
48+
// 5
2349

24-
// 3. Using "prompt()" It take Inputs from User, Convert to number and Perform Addition – Runs only in browser
25-
let a = Number(prompt("Enter first number:"));
26-
let b = Number(prompt("Enter second number:"));
27-
console.log("Sum:", a + b);
50+
// 4. Using Rest Parameters ( Used For Multiple Inputs)
51+
function addAll(...nums) {
52+
let sum = 0;
53+
for (let n of nums) {
54+
sum += n;
55+
}
56+
return sum;
57+
}
58+
console.log(addAll(1, 2, 3, 4));
2859
// Output:
29-
// Enter frist number: 2
30-
// Enter second number: 8
31-
// Sum: 10
60+
// 10
3261

33-
// OR
62+
//5. Using prompt() (User Input) – only browser
63+
let arr = [1, 2, 3, 4];
64+
let Sum = arr.reduce((a, b) => a + b, 0);
65+
console.log("Sum:", sum); // Output: 10

0 commit comments

Comments
 (0)