lundi 10 juillet 2017

C: Use a different condition in for statement depending on value of variable

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
    }
}

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
    }
}

Just wondering if I can do this while keeping only one set of for statements; because they'd be the same in either case.

Aucun commentaire:

Enregistrer un commentaire