while-loop interview questions
Top while-loop frequently asked interview questions
I am asking this question from an educational/hacking point of view, (I wouldn't really want to code like this).
Is it possible to implement a while loop only using C preprocessor directives. I understand that macros cannot be expanded recursively, so how would this be accomplished?
Source: (StackOverflow)
I have a script and want to ask the user for some information, the script cannot continue until the user fills in this information. The following is my attempt at putting a command into a loop to achieve this but it doesn't work for some reason.
echo "Please change password"
while passwd
do
echo "Try again"
done
I have tried many variations of the while loop:
while `passwd`
while [[ "`passwd`" -gt 0 ]]
while [ `passwd` -ne 0 ]]
# ... And much more
But I can't seem to get it to work.
Source: (StackOverflow)
This was an interview question asked by a senior manager.
Which is faster?
while(1) {
// Some code
}
or
while(2) {
//Some code
}
I said that both have the same execution speed, as the expression inside while
should finally evaluate to true
or false
. In this case, both evaluate to true
and there are no extra conditional instructions inside the while
condition. So, both will have the same speed of execution and I prefer while (1).
But the interviewer said confidently:
"Check your basics. while(1)
is faster than while(2)
."
(He was not testing my confidence)
Is this true?
Source: (StackOverflow)
In this code sample, is there any way to continue on the outer loop from the catch block?
while
{
// outer loop
while
{
// inner loop
try
{
throw;
}
catch
{
// how do I continue on the outer loop from here?
continue;
}
}
}
Source: (StackOverflow)
I need to emulate a do-while loop in a Python program. Unfortunately, the following straightforward code does not work:
l = [ 1, 2, 3 ]
i = l.__iter__()
s = None
while True :
if s :
print s
try :
s = i.next()
except StopIteration :
break
print "done"
Instead of "1,2,3,done", it prints the following output:
[stdout:]1
[stdout:]2
[stdout:]3
None['Traceback (most recent call last):
', ' File "test_python.py", line 8, in <module>
s = i.next()
', 'StopIteration
']
What can I do in order to catch the 'stop iteration' exception and break a while
loop properly?
An example of why such a thing may be needed is shown below as pseudocode.
State machine:
s = ""
while True :
if state is STATE_CODE :
if "//" in s :
tokens.add( TOKEN_COMMENT, s.split( "//" )[1] )
state = STATE_COMMENT
else :
tokens.add( TOKEN_CODE, s )
if state is STATE_COMMENT :
if "//" in s :
tokens.append( TOKEN_COMMENT, s.split( "//" )[1] )
else
state = STATE_CODE
# Re-evaluate same line
continue
try :
s = i.next()
except StopIteration :
break
Source: (StackOverflow)
Having trouble coming up with the right combination of semicolons and/or braces. I'd like to do this, but as a one-liner from the command line:
while [ 1 ]
do
foo
sleep 2
done
Source: (StackOverflow)
Question 1:
Why does the following code compile without having a return statement?
public int a()
{
while(true);
}
Notice: If I add return after the while then I get an Unreachable Code Error
.
Question 2:
On the other hand, why does the following code compile,
public int a()
{
while(0 == 0);
}
even though the following does not.
public int a(int b)
{
while(b == b);
}
Source: (StackOverflow)
I've heard this quite a few times. Are JavaScript loops really faster when counting backward? If so, why? I've seen a few test suite examples showing that reversed loops are quicker, but I can't find any explanation as to why!
I'm assuming it's because the loop no longer has to evaluate a property each time it checks to see if it's finished and it just checks against the final numeric value.
I.e.
for (var i = count - 1; i >= 0; i--)
{
// count is only evaluated once and then the comparison is always on 0.
}
Source: (StackOverflow)
Why is this:
String str;
while(condition){
str = calculateStr();
.....
}
better than this?
while(condition){
String str = calculateStr();
.....
}
Is it necessary to declare variables outside the loop?
Source: (StackOverflow)
I've been programming in Java for several years now, but I just recently returned to school to get a formal degree. I was quite surprised to learn that, on my last assignment, I lost points for using a loop like the one below.
do{
//get some input.
//if the input meets my conditions, break;
//Otherwise ask again.
} while(true)
Now for my test I'm just scanning for some console input, but I was told that this kind of loop is discouraged because using break
is akin to goto
, we just don't do it.
I understand fully the pitfalls of goto
and its Java cousin break:label
, and I have the good sense not to use them. I also realize that a more complete program would provide some other means of escape, say for instance to just end the program, but that wasn't a reason my professor cited, so...
What's wrong with do-while(true)
?
Source: (StackOverflow)
So Scala is supposed to be as fast as Java. I'm revisiting some Project Euler problems in Scala that I originally tackled in Java. Specifically Problem 5: "What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?"
Here's my Java solution, which takes 0.7 seconds to complete on my machine:
public class P005_evenly_divisible implements Runnable{
final int t = 20;
public void run() {
int i = 10;
while(!isEvenlyDivisible(i, t)){
i += 2;
}
System.out.println(i);
}
boolean isEvenlyDivisible(int a, int b){
for (int i = 2; i <= b; i++) {
if (a % i != 0)
return false;
}
return true;
}
public static void main(String[] args) {
new P005_evenly_divisible().run();
}
}
Here's my "direct translation" into Scala, which takes 103 seconds (147 times longer!)
object P005_JavaStyle {
val t:Int = 20;
def run {
var i = 10
while(!isEvenlyDivisible(i,t))
i += 2
println(i)
}
def isEvenlyDivisible(a:Int, b:Int):Boolean = {
for (i <- 2 to b)
if (a % i != 0)
return false
return true
}
def main(args : Array[String]) {
run
}
}
Finally here's my attempt at functional programming, which takes 39 seconds (55 times longer)
object P005 extends App{
def isDivis(x:Int) = (1 to 20) forall {x % _ == 0}
def find(n:Int):Int = if (isDivis(n)) n else find (n+2)
println (find (2))
}
Using Scala 2.9.0.1 on Windows 7 64-bit. How do I improve performance? Am I doing something wrong? Or is Java just a lot faster?
Source: (StackOverflow)
I found similar questions asked here but there weren't answers to my satisfaction. So rephrasing the question again-
I have a task that needs to be done on a periodic basis (say 1 minute intervals). What is advantage of using Timertask & Timer to do this as opposed to creating a new thread that has a infinite loop with sleep?
Code snippet using timertask-
TimerTask uploadCheckerTimerTask = new TimerTask(){
public void run() {
NewUploadServer.getInstance().checkAndUploadFiles();
}
};
Timer uploadCheckerTimer = new Timer(true);
uploadCheckerTimer.scheduleAtFixedRate(uploadCheckerTimerTask, 0, 60 * 1000);
Code snippet using Thread and sleep-
Thread t = new Thread(){
public void run() {
while(true) {
NewUploadServer.getInstance().checkAndUploadFiles();
Thread.sleep(60 * 1000);
}
}
};
t.start();
I really don't have to worry if I miss certain cycles if the execution of the logic takes more than the interval time.
Please comment on this..
Thanks,
-Keshav
Update:
Recently I found another difference between using Timer versus Thread.sleep(). Suppose the current system time is 11:00AM. If we rollback the system time to 10:00AM for some reason, The Timer will STOP executing the task until it has reached 11:00AM, whereas Thread.sleep() method would continue executing the task without hindrance. This can be a major decision maker in deciding what to use between these two.
Source: (StackOverflow)
While browsing the code for the Java 8 version of ForkJoinPool(which has a few interesting changes from Java 7) I ran across this construct (here):
do {} while (!blocker.isReleasable() &&
!blocker.block());
I'm struggling with why you would write it like this instead of just
while (!blocker.isReleasable() &&
!blocker.block());
Is it just a semantics/readability choice, since you could read the first construct as do "nothing" while "conditions"
? Or is there some additional benefit I'm missing?
Source: (StackOverflow)
Possible Duplicates:
While vs. Do While
When should I use do-while instead of while loops?
I've been programming for a while now (2 years work + 4.5 years degree + 1 year pre-college) and I've never used a do-while loop short of being forced to in the Introduction to Programming course. I have a growing feeling that I'm doing programming wrong if I never run into something so fundamental.
Could it be that I just haven't run into the correct circumstances?
What are some examples where it would be necessary to use a do-while instead of a while?
(My schooling was almost all in C/C++ and my work is in C#, so if there is another language where it absolutely makes sense because do-whiles work differently, then these questions don't really apply)
Edit: To clarify...I know the difference between a while and a do-while. While checks exit condition then performs tasks, do-while performs tasks then checks exit condition.
Source: (StackOverflow)