Monday, February 17, 2020

Pattern programs

    *
   ***
  *****
 *******
*********
We have shown five rows above; in the program, a user inputs the numbers of rows to print.

Pattern program in C

#include <stdio.h>
int main()
{
  int row, c, n;
  printf("Enter the number of rows in pyramid of stars to print\n");
  scanf("%d", &n);
  for (row = 1; row <= n; row++)  // Loop to print rows
  {
    for (= 1; c <= n-row; c++)  // Loop to print spaces in a row
      printf(" ");
    for (= 1; c <= 2*row - 1; c++) // Loop to print stars in a row
      printf("*");
    printf("\n");
  }
  return 0;
}
Output of program:
Stars pyramid C program output

For more patterns or shapes on numbers and characters see codes on following pages:
Floyd triangle
Pascal triangle

Consider the following triangle pattern

*
**
***
****
*****
to print above pattern see the code below:

#include <stdio.h>
int main()
{
  int n, c, k;
  printf("Enter number of rows\n");
  scanf("%d", &n);
  for (= 1; c <= n; c++)
  {
    for(= 1; k <= c; k++)
      printf("*");
    printf("\n");
  }
  return 0;
}

Pattern:

   
   *
  *A*
 *A*A*
*A*A*A*
C pattern program of stars and alphabets:
#include <stdio.h>
int main()
{
  int n, c, k;
  printf("Enter number of rows\n");
  scanf("%d", &n);
  for (= 1; c <= n; c++)
  {
    for (= 1; k <= n-c; k++)
      printf(" ");
    for (= 1; k < c; k++)
      printf("*A");
    printf("*\n");
  }
  return 0;
}
Pattern:
    1
   232
  34543
 4567654
567898765
C program:
#include <stdio.h>
int main()
{
  int n, c, row, t = 1;
  scanf("%d", &n);
  for (row = 1; row <= n; row++) {
    for (= 1; c <= n - row; c++)
      printf(" ");
    t = row;
    for (= 1; c <= row; c++) {
      printf("%d", t);
      t++;
    }
    t = t - 2;
    for (= 1 ; c < row; c++) {
      printf("%d", t);
      t--;
    }
    printf("\n");
  }
  return 0;
}
Pattern:
1  2  4  7
3  5  8 11
6  9 12 14
10 13 15 16

Matrix pattern C program

#include <stdio.h>
int main()
{
  int n, p = 1, a[100][100], j, m, k, r;
  scanf("%d", &r);
  for (= 1; j <= r; j++) {
    m = 0;
    n = j;
    for (= 1; k <= j; k++)
      a[m++][--n] = p++;
  }
  for (= 1; j <= r-1; j++) {
    m = j;
    n = r-1;
    for (= 1; k<= r-j; k++)
      a[m++][n--] = p++;
  }
  for (= 0; j <= r-1; j++) {
    for (= 0; k <= r-1; k++)
      printf("%d ", a[j][k]);
    printf("\n");
  }
  return 0;
}

No comments:

Post a Comment