printWithIndex.js (***Revise Easy***)

 /**

* print with index
You are given a function printWithIndex that takes a number and a string to print a message.
You are also given a list that contains n strings.
Write a function named printer that uses printWithIndex to print the list elements with
their indices.

Input
First line contains n denoting the number of strings given, 0 <= n <= 100

This is followed by n lines, each denoting one string element of the lit

Output
The output must contain n lines.

Each line starts with the index value of the element, followed by a space then the element
itself

Example
Input:
4
hello
cat
dog
raining

Output:

0 hello

1 cat

2 dog

3 raining

The first line is 4, denoting that there are 4 elements in the list. Th eelements are hello, cat, dog, raining. The output should be 4 lines. Each line has the index first, followed by the element itself. Index of hello is 0, index of cat is 1 and so on:
*/

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];
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////

function printWithIndex(index, string) {

console.log(index, string);
}

function printer(stringList) {

for (let i = 0; i < stringList.length; i++) { //i=0, i=1, i=2, i=3,
i=4<3(false exit the loop)

printWithIndex(i, stringList[i]); // invoking printWithIndex
// stringList[0] = 'hello' , stringList[1]= 'cat', stringList[2]='dog,
stingList[3]= 'raining'
}

}

// This part is for taking the input

let noOfStrings = parseInt(readLine()); // 4

let stringList = []; // we will push all the strings in this array

for (let i = 0; i < noOfStrings; i++) {

stringList[i] = readLine();

//OR

//stringList.push(readLine());

}
//console.log(stringList) // [ 'hello', 'cat', 'dog', 'raining' ] all green color

printer(stringList); // invoking the function printer

//////////////////////////////////////////////////////////////////////////////////////////////
TERMINAL:







Comments

Popular posts from this blog

car.js

movie.js