for and while loop in c#

(update) Actually – there is one scenario where the for construct is more efficient; looping on an array. The compiler/JIT has optimisations for this scenario as long as you use arr.Length in the condition: for(int i = 0 ; i < arr.Length ; i++) { Console.WriteLine(arr[i]); // skips bounds check } In this very specific … Read more

while loop to read file ends prematurely

If you run commands which read from stdin (such as ssh) inside a loop, you need to ensure that either: Your loop isn’t iterating over stdin Your command has had its stdin redirected: …otherwise, the command can consume input intended for the loop, causing it to end. The former: while read -u 5 -r hostname; … Read more

Java InputMismatchException

You can use a do-while loop instead to eliminate the first input.nextInt(). int students = 0; do { try { // Get input System.out.print(“Enter the number of students: “); students = input.nextInt(); } catch (InputMismatchException e) { System.out.print(“Invalid number of students. “); } input.nextLine(); // clears the buffer } while (students <= 0); // Do … Read more