Problem 12. odd_count.js (forloop is introduced)

 /*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();
}
//..............................................................................................................................

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 don't go into if condition and i++, same for other all
{
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

Popular posts from this blog

Problem 33. patter122333.js

Problem 38. diamond.js

Problem 16. chocolatebills.js