So I want to implement a for statement whose 'length' and condition depend on the value of the number-of-entries variable I give it. The loop is reading a file primarily.
For example, if the command line input for number-of-entries is a positive integer, I want the loop to run for number-of-entries iterations or until the end of the file is reached; if the input for number-of-entries is -1, I want the loop to run until the end of the file.
Is there a way to do this without writing the for loop twice, each one nested in an if statement; is there a more concise way? Asking because the statements inside the for loop are the same; the only difference is that condition in the for argument.
Here's what I know I can do:
if ( number_of_entries > 0 ) {
for ( i = 0; i < number_of_entries; i++ ){
// set of for statements
// check to see if end of file is reached
// this case stops when i reaches number_of_entries or EOF
}
}
else if ( number_of_entries < 0 ) {
for ( i = 0; i > number_of_entries; i++ ){
// identical set of for statements
// check to see if end of file is reached
// this case stops at EOF because i will never reach number_of_entries
}
}
Just wondering if I can do this while keeping only one set of for statements; because they'd be the same in either case.
Edit: Let me clarify the i++ in the second case: it should still be i++; the second loop only ends when the end of file is reached. i will keep increasing until then. The only acceptable inputs for number_of_entries are -1 or any positive integer (there is a check for this in the program).