12.09.2012

Number Pryamid By Function

Q. Write a C program to print the following triangle using function.

 1
 2 3
 4 5 6
 7 8 9 1
 2 3 4 5 6

Ans.

/*C program for number pyramid using function*/
#include<stdio.h>
void pyramid(int );
int main()
{
 int num;
 printf("Enter the number of rows : ");
 scanf("%d", &num);
 pyramid(num);
 return 0;
}

void pyramid(int n)
{
 int r,c,x=1,y=1;
 for(r=1; r<=n; r++)
 {
  for(c=1; c<=r; c++,x++)
  {
    if(x<=9)
       printf(" %d",x);
    else
    {
       printf(" %d",y);
       y++;
    }
  }
  printf("\n");
 }
}

The output of above program would be:

Output of create number pyramid using function C program
Figure: Screen shot for number pyramid
using function C program

4 comments:

  1. Replies
    1. @Jitendra,
      What you find an error in above program? Write Down here?

      Delete
  2. The Correct Program is :

    #include
    void pyramid(int );
    int main()
    {
    int num;
    printf("Enter the number of rows : ");
    scanf("%d", &num);
    pyramid(num);
    return 0;
    }

    void pyramid(int n)
    {
    int r,c,x=1;
    for(r=1; r<=n; r++)
    {
    for(c=1; c<=r; c++,x++)
    {
    if(x<=9)
    printf(" %d",x);
    else
    {
    x=1;
    printf(" %d",x);
    }
    }
    printf("\n");
    }
    getch();
    }

    ReplyDelete
    Replies
    1. @Jitendra,
      What is difference my and your program?
      You copy above program and paste in comment session?

      Plz write any comment if you have a real problem!!

      Delete