Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
Is it better to use the variable 'i' or a meaningful name such as 'loopCount' or 'studentsCount' etc?
e.g.
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 5; j++)
{
System.out.println(i + j);
} // End of j loop
} // End of i loop
VS
for (int outerLoop = 0; outerLoop < 10; outerLoop++)
{
for (int innerLoop = 0; innerLoop < 5; innerLoop++)
{
System.out.println(outerLoop + innerLoop);
} // End of innerLoop
} // End of outerLoop
By better; the main considerations would be readability / conventions.
Related question Loop iterator naming convention
EDIT:
I have tagged this a java, but answers for other languages are welcome.
Firstly, using Integer here is very expensive because Integer is immutable. Thus each time you do an increment it unboxes the previous Integer, do an increment and creates another Integer to hold the new value. You need to use int.
Secondly, whether to have a readable name really up to the semantics of the int. If it's just a control variable over a pre-determined number of loops I think i is fine; but if it has specific meaning then you are free to give it a better meaningful name.
Code is communication: what do you want the reader of this code (who might be you months or years from now) to think when he sees it? To me, using "i" and "j" in a loop says "do this thing 10 times; the variable is just a convention and means nothing", while using a more descriptive variable like "studentID" says "this number actually refers to something specific" I'd use the former if I want to de-emphasize the variable itself, and the latter if I want to highlight it.
I have seen many loops that started out small and grew very large with other loops added inside and around them and it all became a confusing mess of i j k x y z. Name your references with the shortest name that expresses your intent, so another dev will know what you were going for.
Traditionally i and j are used for this type of thing, but there's certainly nothing wrong with giving them a meaningful name to aid in readability. If I were reading another persons code, I would rather prefer outer/innerloop to i and j.
Use i and j if you want. People reading your code will probably decode these to be the names of loop variables, and if they can't, then shame on them.
(( if you use long names for loop variables in a language where long names will hinder performance, then I'll slap you ))
In the looping you can use i , j (not meaningful name) and the program will compile and run.
But in the big project if you use i, j , this is only know you. Other person who is your leader difficult to understand your code. That why you should make habit even there are not big project.
Thank you
i and j origin in mathematical conventions for matrices, as a form of abstraction. I use it mainly in an math/numeric algorithm context.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I am currently practicing with my coding skills and one of the challenges I ran into was finding the first duplicate value produced in an array. I had solve the challenge, but not in a timely manner. I looked at the solution for the problem and ran into this solution and wanted help in understanding how it exactly works. I have the solution commented in the areas that I understand and what exactly is the purpose of that block of code, but I would like help in understanding the if-statement why it works the way it does.
int firstDuplicate(int[] a) {
for(int i=0;i<a.length;i++)
//Checks ???????????
if(a[Math.abs(a[i])-1]<0)
return Math.abs(a[i]);
//Make the checked value negative
else{
a[Math.abs(a[i])-1]=-a[Math.abs(a[i])-1];
}
//If there are no duplicates it returns -1
return -1;
}
Constraints:
1 ≤ a.length ≤ 105,
1 ≤ a[i] ≤ a.length.
Welcome to SO. I will not give you the exact answer but instead provide you with tools for you to figure it out.
In order for you to figure out this code, you need to debug it. Here are some ways you could go about it.
Set a breakpoint just prior to calling the function (look up how to do this for your IDE), thereafter step into your code line-by-line.
You could use a combination of temporary variables and System.out.println() statements. Looking into your code, break it down into modular bits that you can track. For instance you could re-write the expression inside the if statement as
int currentElementAbsolute = Math.abs(a[i]);
System.out.println(currentElementAbsolute);
int difference = currentElementAbsolute - 1;
System.out.println(difference);
int element = a[difference]
System.out.println(element);
if (element < 0)
{
return Math.abs(a[i]);
}
As you can see, for each operation/line, I print out the current value thus keeping track of events. Practice this and re-write the else part
PS: Upon completion you will realise this method fails to capture all duplicates when certain type of numbers are used. Happy Hunting :)
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I'm a novice programmer is looking to get help with a program I've been working on for hours now.
Anyway my issue happens to be with initializing my "sum" variable in a way so that it is not equal a number or become an input. (It's set to equal 0 in my program)
I also seem to be struggling with my while loop statement as I can't think of a condition in which I don't cause the program to terminate or cause a infinite loop.
Any help at this point would highly appreciated.
I'm assuming you are trying to compute sum of integers from 1 to n, where n is input from the user.
One of the simpler ways to do that is to use a for loop as below
for(int i = 1; i <= n; i++) {
sum = sum + i;
}
or using while loop
while(input > 0) {
sum = sum + input;
input = input - 1;
}
Alternatively, sum of first N natural numbers is given by formula n*(n+1)/2, so you might as well do
int sum = (n * (n+1))/2;
Ensure that n is a positive number > 0 through an if conditional
your While loop is going infinity as your input is never 0 until you give it.
So you have to deal with your input.
Possibly use or declare input=0 so that when your while loop goes for the execution for 2nd Time...It finds 0.
Hope this helps...Please share doubts if any.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I had recently a discussion about the use of non-counter related conditions in for-loops in Java:
for(int i = 0; o.getC() < 10; i++)
o.addC(i);
Does anyone know if there are any "official" conventions for for-conditions like this? In my opinion it's easier to read compared to an equivalent while-loop because all loop-parameters are together in the first line:
int i = 0;
while(o.getC() < 10) {
i++;
o.addC(i);
}
Or even worse:
int i = 0;
while(o.getC() < 10)
o.addC(++i);
for loops are used in pretty much every situation over equivalent while solution. Arrays, lists, standard data structures.
On the other hand while is commonly used with streams and for infinitely long iterations..
Most developers will expect a for statement to consist of three things:
Initialization of a variable
Termination condition based on the variable
Increment on the variable
If you change your code to contain unexpected things it will get harder to read and thus harder to maintain.
Furthermore, I think the while loop makes your intention clearer: do something while o.getC() is less then 10. This "something" happens to be: add an incrementing number.
Long story short: use a while loop for "non-counter related conditions".
A nice thing about for loops is there is a shortcut method. So if you want to do all of the items in an array you can just do the following:
(double number : arrayName)
where double is the type, number is the name you are giving each element (it doesn't matter really what you call it, you will refer to each value there as "number" in this case). And arrayName is the name of the array you are referring to.
If you want to reach each element/object this is the fastest way.
How about:
for(int i = 0; i < MAX_ITERATIONS; i++)
{
o.addC(i);
if (o.getC() >= 10)
return o; // or break
}
This prevents an infinite loop if addC is not really doing what you expect.
This question already has answers here:
Closed 10 years ago.
Possible Duplicates:
Loop counter in Java API
Which of these pieces of code is faster in Java?
for(int i = 100000; i > 0; i--) {}
for(int i = 1; i < 100001; i++) {}
Which one is faster?I read that first for loop is faster.is it true?Then how it become faster than other?please help.
There is no way to tell which of the two is faster.
If all you provide is a snippet of Java code, all we have to go on is the Java Language Specification. Since the Java Language Specification never mentions any timing aspects there's no way to answer the question.
It is similar to asking your math teacher, "Which is faster to compute, 17+17 or 17*17?" Your math teacher will just stare at you and at best respond with something like, "are you using pen and paper or a pocket calculator?"
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
Is it considered poor style / discourage to ignore the loop variable in a for-each statement in Java?
I have some code looks looks sort of like the following:
public void makeChecklist( final List<File> inputSrcs ){
for( File src : inputSrcs ){
System.out.print( src.getName() + "\t" );
}
System.out.println();
for( File src : inputSrcs ){
//Not using "src" in this body!
System.out.print( "[ ]\t" );
}
System.out.println();
}
Is this a bad idea? Any reason not todo things this way? It just seems so much cleaner than using a regular for-loop.
PS- presume that for the example above I want the checkboxes to appear underneath the names, the example is contrived to ilustrate my question as simply as possible.
It certainly looks odd. I would make it clearer that it's only the count that matters with a for loop:
for (int i = 0; i < inputSrcs.size(); i++) {
System.out.println( "[ ]\t" );
}
I think that makes the intention clearer. Although as has been pointed out in the comments, we're really just replacing one "dummy" variable with another in the above. What I like about it is that it explicitly calls size(), which I believe shows that the size is important.
In a more expressive language you might find something to indicate "I just want to execute the body n times" which would be prettier still:
inputSrcs.size().times() {
System.out.println( "[ ]\t" );
}
(That may or may not be valid Groovy :)
EDIT: Another obvious answer occurs to me, which should have occurred before:
printRepeatedly("[ ]\t", inputSrcs.size());
...
private static void printRepeatedly(String text, int count) {
for (int i = 0; i < count; i++) {
System.out.println(text);
}
}
Now in the calling method, the meaning is absolutely obvious... and within printRepeatedly we don't even have the context of a list, so we couldn't possibly be trying to use the data. At this point the dummy variable i is fairly obviously a dummy variable, and the method name makes it obvious why we'd want this behaviour.
I think if you're going to do it, the comment removes a lot of the ambiguity/potential confusion.
Seems perfectly clear to me.
You will find that the line feeds added by println()--as opposed to print()--will make it so your check boxes aren't really lining up with anything other than your left margin.