Restarting i in for loop???

Hi all,

I have a little problem with the following code, I have to check to see if the idnumber that is entered is unique to the array of student's id's that have already been entered.

1
2
3
4
5
6
7
8
9
10
11
12
cout << "What is the new student's ID number?" << endl;
cin >> newidnumber;

for (i = 0; i > numberofstudents; i++)
{
    if(newidnumber == studentarray[i]->getidnum())
    {
        cout << "Please enter another ID Number that one was taken." << endl;
        cin >> newidnumber;
        i = 0; // wanting to restart if newid is already taken
    }
}
for (i = 0; i > numberofstudents; i++)

Probably a typo and should be <, right? ;-)

Ciao, Imi.
PS: Consider using a while-loop instead. It could improve readability, as many people don't expect a for loop to reset over and over again..
Last edited on
yeah my bad hehehe should have been <.

well I only want the loop to reset to the beginning of the list of students's IF the newidnumber is unique.

what's a good way to do that?
Well, from the compiler point of view, "while" is as good as "for". But IMHO, most programmers have certain expectations. "for" usually loops over something in a more-or-less static way, means there is no sudden jumping back and forth during the loop. "while" is freelancer's meat. Programmer expect whatever complex stuff.

That's a personal thought. May differ in different teams.

I'd just rewrite the for into a while:

1
2
3
4
5
6
7
8
9
int i = 0;
while (i < numberofstudents)
{
    ...
    if (...)
        i = 0;
    else
        i++;
}


Wow! While writing the example code, I spottet another problem with your for loop. You would have to set i to -1 (hope it's not unsigned? ;), because it would be increased immediately by the i++ in the for-loop. If you use while, you spot this mistake better (because you have to write your iterator increase explicit). And you can write the if/else and set it to 0, which looks much better.


Ciao, Imi.
Thanks heap Imi,

What I ended up doing is similar to what you had there actually.

what do you mean by "while is freelancer's meat"?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
i = 0;
while(i < numberofstudents)
{
	if(newidnumber != studentarray[i]->getidnum())
	{
		i++;
	}
	else
	{
	        cout << "Please enter another ID Number that one was taken." << endl;
		cin >> newidnumber;
		i = 0;
	}
}
Last edited on
what do you mean by "while is freelancer's meat"?

Aww. nothing particular. Just that when programmer see "while"-loops, they are more cautious and assuming a more complex loop condition than just "for every element of something".


(In our company, freelancer tend to write more complex code, so if something looks suspicious or just strange, we say "probably be written by a freelancer" or short: "probably freelancer meat.") (Edit: Which doesn't mean we can't write while-loops by ourself ^^)

Ciao, Imi.
Last edited on
Topic archived. No new replies allowed.