atulgairola08's blog

By atulgairola08, history, 5 months ago, In English

All the web developers here who love javascript have always faced some difficulty in using it in competitive programming. Code forces has made vanilla javascript available for competitive programming using V8 compiler of chrome.

To start with javascript v8 in codeforces you need to be able to read inputs and give outputs.

HERE we can use readline() and print(), which reads input and gives output respectively

readline()

This function reads the first line of the input as a string including all the whitespaces.

print()

this prints the provided parameter to the console output.

for ex:

INPUT

2 3 4 5


var x = readline(); print(x);

OUTPUT

2 3 4 5

If you want each number separately, we use split() cause the input is nothing but a string.

So..

INPUT

2 3 4 5


var x = readline().split(' '); // x is an array now [2,3,4,5] print(x);

OUTPUT

2,3,4,5

to take multiline inputs

Mostly in the questions there are more than one lines of input. readline() just reads one line per call.

So, we have to call it again if we need another line input.

INPUT

2

3 4 5


var x = readline(); var y = readline().split(" "); print(x); print(y);

OUTPUT

2

3,4,5

Looping through multiple lines to take input

We usually loop through multiple lines of inputs instead of hardcoding one for each. But we need to be careful that we first declare the var for storing the input outside of the loop else the readline() will keep reading the same line again and again in each loop.

INPUT

3

3 4 5

6 7 8

9 10 11


var x = readline(); // first line of input usually gives the no. of test cases,i.e, the no. of lines ahead. var inp; // declaring the variable outside the loop for(var i = 0 ; i < x ; i++) { inp = readline().split(" "); print(inp); }

OUTPUT

3,4,5

6,7,8

9,10,11

Now you are ready to start your cp journey with js.

 
 
 
 
  • Vote: I like it
  • +3
  • Vote: I do not like it

»
5 months ago, # |
  Vote: I like it 0 Vote: I do not like it

Auto comment: topic has been updated by atulgairola08 (previous revision, new revision, compare).

»
5 months ago, # |
  Vote: I like it 0 Vote: I do not like it

Auto comment: topic has been updated by atulgairola08 (previous revision, new revision, compare).

»
5 months ago, # |
  Vote: I like it 0 Vote: I do not like it

Auto comment: topic has been updated by atulgairola08 (previous revision, new revision, compare).

»
5 months ago, # |
  Vote: I like it 0 Vote: I do not like it

Auto comment: topic has been updated by atulgairola08 (previous revision, new revision, compare).

»
5 months ago, # |
  Vote: I like it 0 Vote: I do not like it

Auto comment: topic has been updated by atulgairola08 (previous revision, new revision, compare).

»
4 weeks ago, # |
  Vote: I like it 0 Vote: I do not like it

I am getting undefined output afer following code:

var x = readline(); print(x);

What is wrong with above code?