Home > Software design >  for loop, how to print integers/string two by two
for loop, how to print integers/string two by two

Time:10-03

This drives me crazy because it seems so easy, but I cannot figure it out.

I have a for-loop and it prints out words what I have entered. This version of for-loop prints it out this way:

"car - wheel - bike - handlebar",

instead I want to print it this way:

"car - wheel

bike - handlebar"

for(int i=0;i<numberOfWords;i  ) 
        printf("%s - ",words[i]);
        printf("\n"); 

EDIT: It prints out from an array. I have a function that takes in words and stores in an array. Then I want to pair two words side by side.

CodePudding user response:

for(int i=0;i<numberOfWords;i  ) }
        printf("%s",words[i]);
        if(i%2) printf("\n");
        else printf(" - ");
}
printf("\n"); 

Explanation. Prints every word. And if i is odd (so after printing words[1] and words[3]) print a newline. Otherwise, print a - since another word will be printed on that line.

If the total number of words might not be even (of multiple of whatever number of words per line you want, since this code can be adapted for other than 2), then a specific code should be written for the last word. For example, adding if(i==numberOfWords-1) break after the first printf, so that last loop iteration does not print any separator - nor newline.

CodePudding user response:

It seems you mean the following

for ( int i = 0; i < numberOfWords; i   )
{ 
    if ( i % 2 == 0 )
    {
        printf( "\"%s - ", words[i] );
    }
    else
    {
        printf( "%s\"\n", words[i] ); 
    }
}

The output will be

"car - wheel"
"bike - handlebar"

CodePudding user response:

If you have an even number of words:

for (int i = 0; i < numberOfWords; i  ) 
    printf("%s%s", words[i], i % 2 ? "\n" : " - ");

If you have an even or odd number of words:

int i = 0;
while (i < numberOfWords)
    {
    printf("%s", words[i]);
    printf(i   % 2 || i == numberOfWords ? "\n" : " - ");
    }

CodePudding user response:

My minimum working example uses command line parameters (argc, argv) to provide the test case array of strings, but the main difference to the other examples I have seen here is that this iterates over that array in steps of two.

It prints all pairs of words, and then catches and handles the single leftover array item in case the array contains an odd number of items.

int main(const int argc, const char *const argv[]) {

    for (int i=0; i<argc; i =2) {
        if ((i 1)<argc) {
            printf("word pair: %s - %s\n", argv[i], argv[i 1]);
        } else {
            printf("leftover word: %s\n", argv[i]);
        }
    }

    return 0;
}
  • Related