Program to print inverted pyramid in c using function

Here we are going to write a program to print inverted pyramid pattern in c using function. Previously we have done this similar program but without using function. C program to print inverted pyramid. This time we will do using function.

Pattern inverted pyramid

Pattern that we will print is given below.

1 2 3 4 5

1 2 3 4

1 2 3

1 2

1

Let us discuss about the approach.

First we will create a function named pattern() of void return type that is it won't return anything and it will take one integer as parameter. The integer which we are sending as parameter is the number which is the number of rows. Then within that function we will print the pattern. Then in main() function we will call the pattern() function, that's it. Now lets code it.

Program to print inverted pyramid in c using function 

#include &lt!stdio.h>

void pattern(int n){
   for(int i=n; i>0; i--)
    {
        for(int j=1; j<=i; j++)
        {
             printf("%d ",j);
        }
        printf("\n");
    }
}

int main(){
    int n;

    printf("Enter number of rows: ");

    scanf("%d", &n);
    pattern(n);
    
    return 0;
}


Output

Enter number of rows: 5

1 2 3 4 5
1 2 3 4
1 2 3
1 2
1

What's happening inside loop let's have a look

Nested loop algorithm -
Suppose n=5.

When i=5 , j=1 to 5 (as j<=i and i=n=5) so 1 2 3 4 5 will be printed.

When i=4, j=1 to 4 (as j<=i and i=4) so 1 2 3 4 will be printed. 

When i=3, j=1 to 3 (as j<=i and i=3) so 1 2 3 will be printed. 

When i=2, j=1 to 2 (as j<=i and i=2) so 1 2 will be printed. 

When i=1, j=1 to 1 (as j<=i and i=1) so 1 will be printed. 

So at the end the result that we are going to see on the screen is

1  2  3  4  5

1  2  3  4

1  2  3

1  2

1

More like this 


• Factorial of a number program in c using function 


• Prime Number check in C using function

• Palindrome Number in C using function 

• Add two numbers in C using function  

• Palindrome String program in c using function 

Post a Comment

If you have any doubts, please let me know

Previous Post Next Post