Answer using C Assume the availability of a function named printStars that can b
ID: 3668249 • Letter: A
Question
Answer using C
Assume the availability of a function named printStars that can be passed a non-negative integer n and print a line of asterisks. Write a function named printTriangle that receives a non-negative integer n and prints a triangle of asterisks as follows: first a line of n asterisks, followed by a line of n-1 asterisks, and then a line of n-2 asterisks, and so on. For example, if the function received 5 it would print:
* * * * *
* * * *
* * *
* *
*
The function must not use a loop of any kind (for, while, do-while) to accomplish its job. The function should invoke printStars to accomplish the task of printing a single line.
Explanation / Answer
#include<stdio.h>
int printTriangle(int);
int printStars(int);
main()
{
int n;
printf("Please enter a number: ");
scanf("%d",&n);
printTriangle(n);
return 0;
}
int printTriangle(int n)
{
if(n == 0)
return 0;
else
{
printStars(n);
printf(" ");
printTriangle(--n);
}
}
int printStars(int n)
{
if(n == 0)
return 0;
else
{
printf("* ");
printStars(--n);
}
}
If you have any confusion or any query, please leave a comment, I’ll try to explain in more details.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.