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:
Figure: Screen shot for number pyramid using function C program |
This Program is Wrong.
ReplyDelete@Jitendra,
DeleteWhat you find an error in above program? Write Down here?
The Correct Program is :
ReplyDelete#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();
}
@Jitendra,
DeleteWhat 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!!