Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are the limits of for loops calculated once or with each loop?

Tags:

c#

loops

Is the limit in the following loop (12332*324234) calculated once or every time the loop runs?

for(int i=0; i<12332*324234;i++)
{
    //Do something!
}
like image 689
sooprise Avatar asked Jul 30 '10 21:07

sooprise


People also ask

What is the limit of for loop?

There is no such limit. You can loop as many number of times you want.

How do you set a limit on a for loop?

An easy way to go about this would be to put the user-input prompt inside of a while loop, and only break out once you've verified that the grade is valid: Scanner scanner = new Scanner(System.in); int score; while (true) { System. out. print("Please enter score " + (g + 1) + ": "); score = scanner.

Does for loop need 3 conditions?

It do says that only one condition is allowed in a for loop, however you can add multiple conditions in for loop by using logical operators to connect them.

Can the loop body of a for loop never get executed?

A loop will only execute while its condition is true. Since a for loop and a while loop both check the condition before the body is executed they will never execute if the condition is false.


1 Answers

For this it it calculated once, or more likely 0 times.

The compiler will optimize the multiplication away for you.

However this is not always the case if you have something like.

for(int i=0; i<someFunction();i++)
{
    //Do something!
}

Because the compiler is not always able to see what someFunction will return. So even if someFunction does return a constant value every time, if the compiler doesn't know that, it cannot optimize it.

EDIT: As MainMa said in a comment, you are in this situation you can eliminate the cost by doing something like this:

int limit = someFunction();
for(int i=0; i<limit ;i++)
{
    //Do something!
}

IF you are certain that the value of someFunction() will not change during the loop.

like image 170
KLee1 Avatar answered Oct 18 '22 14:10

KLee1