Problem 23. Oddcount.js (continue is introduced) continue is used to skip a particular iteration while break is used to come out of the loop.
/*Question
Given a sequence of integer, count the number of odd number in the sequence.
Input:
First line contains a positive integer, say n , denoting the length of the sequence.
Output:
One line containing an integer, denoting the number of odd numbers in the input sequence.
Example:
Input:
5
8 77 24 22 27
Output:
2
Algorithm:
1. Read the length of the sequence.
2. Read the integer from the sequence.
3. Check whether odd or even, if odd, increment he oddCount variable.
4. Repeat step 3 for every number in the sequence
5. Log the odd count.
*/
let fs = require("fs");
let data = fs.readFileSync(0, 'utf-8');
let idx = 0;
data = data.split('\n');
function readLine() {
idx++;
return data[idx - 1].trim();
}
//............................................................................................
..................................
NOTE**** Continue and break keyword can only be used inside loops
let lengthOfSeq = parseInt(readLine()); // 5
let sequence = readLine().split(" "); // ['8' , '77' , '24' , '22' , '27']
//console.log(sequence);
let odd_Count = 0; // we are assuming initially there are 0 odd numbers
for (let i = 0; i < lengthOfSeq; i++) // 1)i=0<5 ,
{
if (parseInt(sequence[i]) % 2 == 0) //1)8%2 ==0 therefore skip this iteration
{
continue
}
odd_Count++;
}
console.log(odd_Count);
Terminal:
Nobins-MacBook-Pro:STOC_MODULE 11SEPT 2022 nobinpunyo$ node odd_count.js <input.txt
2
Nobins-MacBook-Pro:STOC_MODULE 11SEPT 2022 nobinpunyo$
OR---------------------------------------------------------------------------------------------

Comments
Post a Comment