Error correction in a For loop

This is the question that I was asked at the interview today:

Take a look at the following code:

int n=20; for (int i =0; i<n; i--) print("*"); 

You are allowed to change one and only one character so that the loop runs exactly 20 times.

I could not answer the question at all. At first I decided to set it to 40, but then I realized that 40 is at least 20.

My interviewer said that there are 5 different answers to answer this question ...

Please help me find the answers.

+5
source share
3 answers

Change to

 int n=20; for (int i =0; i<n; n--) print("*"); 
+12
source

Another may be:

 int n=20; for (int i =0; -i<n; i--) print("*"); 
+9
source

This also does the job:

 int n=20; for (int i =0; i+n; i--) print("*"); 

Assuming the language implicitly discards integers in booleans, i.e. treats nonzero integers as true and zeros as false.

+4
source

Source: https://habr.com/ru/post/1236002/


All Articles