DEV Community

Chris Cook
Chris Cook

Posted on

Print Number Pattern Using Loops

I recently found this question on one of those job interview preparation websites. The problem is simply to print a pattern of numbers given a number from 1 to n. For example, n is 5:

5 5 5 5 5 5 5 5 5 
5 4 4 4 4 4 4 4 5 
5 4 3 3 3 3 3 4 5 
5 4 3 2 2 2 3 4 5 
5 4 3 2 1 2 3 4 5 
5 4 3 2 2 2 3 4 5 
5 4 3 3 3 3 3 4 5 
5 4 4 4 4 4 4 4 5 
5 5 5 5 5 5 5 5 5
Enter fullscreen mode Exit fullscreen mode

This honestly gave me a headache because I was trying to interpolate a mathematical function to calculate the particular digit based on the variables: n, column, row.

The solution I finally came up with considers each row (left to right) as an array of n*2-1 elements, and the entire pattern as a fictitious multi-dim array of n*2-1 rows (top to bottom). It's fictitious because I'm not actually creating a multi-dim array. This means that n*2-1 is the length of each row (array).

The first row is initialized with n+1. Then at each iteration from row 0 to length the array elements from index row to the inverse index length-row are manipulated (decremented and incremented). This means that on the first iteration in row 0, the elements between indices 0 to 9-0 are decremented. This is the reason why the array was initialized with n+1. At the second iteration the elements between the indices 1 to 9-1 are decremented. And so on until the midpoint on index 4 has been passed after the fifth row. Then the operation is reversed and the elements between indices length-row to row are incremented.

int main() {
  int n = 5;   

  int length = (n*2)-1;
  int numbers[length];

  // initialize array row with n+1
  for (int i = 0; i < length; i++) { 
      numbers[i] = n+1; 
  }

  // iterate through all rows
  for(int row = 0; row < length; row++) {
      // decrement elements until midpoint
      for(int i = row; i < (length-row); i++) { 
          numbers[i] -= 1;  
      }
      // increment elements after midpoint
      for(int i = (length-row); i < row; i++) { 
          numbers[i] += 1;  
      }        
      // print current array row
      for(int i = 0; i < length; i++) { 
          printf("%d ", numbers[i]); 
      }
      // print line break        
      printf("\n");
  }

  return 0;
}
Enter fullscreen mode Exit fullscreen mode

I originally solved the question in C, as part of learning the programming language. To present an interactive solution here, I converted it to TypeScript, but the algorithm is basically the same.

I would like to know if there are any other solutions to this problem or improvements to my solution.

Top comments (0)