Advertisement
dmilicev

number_triangle_pattern_alternate.c

Jan 26th, 2024
533
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.97 KB | None | 0 0
  1. /*
  2.  
  3.     number_triangle_pattern_alternate.c
  4.  
  5. https://www.facebook.com/groups/3092811364081112/permalink/7605244639504406/
  6.  
  7. Solution from Dan Mathew Gamale :
  8. https://www.facebook.com/groups/3092811364081112/user/100005184546962/
  9.  
  10. numbers           indexes           matrix
  11.  
  12. 1                 00                00 01 02 03 04
  13. 2 9               10 11             10 11 12 13 14
  14. 3 8 10            20 21 22          20 21 22 23 24
  15. 4 7 11 14         30 31 32 33       30 31 32 33 34
  16. 5 6 12 13 15      40 41 42 43 44    40 41 42 43 44
  17.  
  18.  
  19.     You can find all my C programs at Dragan Milicev's pastebin:
  20.  
  21.     https://pastebin.com/u/dmilicev
  22.  
  23. */
  24.  
  25. #include<stdio.h>
  26. #include <string.h>                 // for memset()
  27.  
  28. // print triangle of numbers
  29. void number_triangle_pattern_from_top(int n){
  30.     int r,c, num=1;                 // r - row, c - column, num - number
  31.     int arr[n][n];                  // n - number of rows and columns
  32.  
  33.     // memset() is used to fill a block of memory with a particular value.
  34.     memset(arr,0,sizeof(arr));      // set all elements to 0
  35.  
  36. /*
  37.     for(r=0; r<n; r++)              // set all elements to 0, another way
  38.         for(c=0; c<n; c++)
  39.             arr[r][c]=0;
  40. */
  41.     // set all elements to num
  42.     for(c=0; c<n; c++)              // column
  43.         for (r=0; r<n-c; r++)       // row
  44.             if (c%2)                // odd column
  45.                 arr[n-r-1][c] = num++;
  46.             else
  47.                 arr[r+c][c] = num++;
  48.  
  49.     // print triangle
  50.     for(r=0; r<n; r++) {            // row
  51.         for(c=0; c<n; c++)          // column
  52.             if (arr[r][c] != 0)
  53.                 printf("%3d",arr[r][c]);
  54.         printf("\n");
  55.     }
  56.  
  57.     printf("\n");
  58. }
  59.  
  60.  
  61. int main(void){
  62.     int n;                          // n - number of rows and columns
  63.  
  64.     for(n=3; n<=6; n++){            // a few examples
  65.         printf("\n  n = %d \n\n",n);
  66.         number_triangle_pattern_from_top(n);
  67.     }
  68.  
  69.     return 0;
  70. } // main()
  71.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement