Home > Back-end >  Print number pattern with a single for loop without an if statements
Print number pattern with a single for loop without an if statements

Time:09-01

I need to print the following pattern using a single for-loop without if statements.

1
21
321

I first tried to understand the logic and coded it using 2 for loops:

for (int i = 0 ; i <= num; i  ) {
      int temp = i;
      for (int j = 0; j < i; j  ){
            printf("%d", temp);
            temp--;
      }
      printf("\n");
}

However, I have no clue on how to approach this without a for loop AND no if statements. Any hints/tips would be greatly appreciated.

CodePudding user response:

  1. Make a loop that will print integer 321 three times.
  2. Modify loop print statement to print remainder of 321 divided by 10. Each line will now print 1.
  3. After print statement, multiply divider by 10, so that after each loop iteration divider is 10 times bigger.

CodePudding user response:

You can store the previous line and use it to produce new one. Here's naive implementation, working for up to 9 lines.

int main()
{
    int num = 3;
    char buffer[100] = {0};
    char temp_buffer[200] = {0};

    for (int i = 1 ; i <= num; i  ) {
        sprintf(temp_buffer, "%d%s", i, buffer);
        printf("%s\n", temp_buffer);
        strcpy(buffer, temp_buffer);
    }
    
    return 0;
}

CodePudding user response:

  • Try to write loops as close to the most trivial/canonical form as possible:

    for(int i=0; i<n; i )

    That means: avoid iterating starting from 1, avoid comparing with <=, avoid down-counting loops. There's a place for all of these things but avoid them when you can for the sake of readability and keeping things simple. As a bonus, readable loops are very often also fast loops.

  • In this case 2 for loops isn't a bad idea. You can consider the output a matrix of sorts, then have an outer for loop for "rows" and the inner one for "columns".

  • Write the outer for loop in the canonical form I showed above where n would be your maximum, such as 3.

  • Write the inner for loop so that it iterates from zero up to "rows" - the outer loop iterator. However, you don't want to write 0, 10 and so on so you should also compensate for this by adding 1. So the upper limit condition of the inner loop could be cols < (rows 1).

  • Then when printing in the inner loop (assuming you took my advise to make it up-counting), print descending by starting at your max value rows 1 then subtract the current value. That is (rows 1) - cols.

  • Change new line in the outer loop, after printing each row, like you are already doing.

Result:

#include <stdio.h>
#define MAX 5

int main (void) { for(int rows=0; rows<MAX; rows ) { for(int cols=0; cols<(rows 1); cols ) printf("%d",(rows 1)-cols); printf("\n"); } }

  • Related