Search code examples
cswitch-statementfunction-call

Lefttriangle(), Righttringle(), Pascaltriangle()


Q : Write three different functions Lefttriangle(),Righttriangle(),Pascaltriangle() in a single C-program and display the triangle as asked by the user interactively.

So I have tried this one. It is printing the options, then I am entering an option, suppose 1 then it is asking for the number "n". Then ,I am entering the number, suppose 4 and pressing enter. But then it isn't showing the left triangle corresponding to 4. It is printing the options again.

#include<stdio.h>
#include<conio.h>
#include<math.h>

void pascaltriangle(int i,int j,int k,int n,int m)
{   

for(i=0;i<n;i++)
{
    for(k=1;k<=n-i;k++)
    {   
        printf("The Pascal triangle of numbers is as follows - \n");
        printf(" ");
    }
    for(j=0;j<=i;j++)
    {
        if(j==0||i==0)
        m=1;
        else
        m=m*(i-j+1)/j;
        printf(" %d",m);
    }
    printf("\n",m);
}

}

void lefttriangle(int i,int j,int n)
{
printf("Enter the value of n : ");
scanf("%d",&n);

for(i=1;i<=n;i++)
{
    for(j=1;j<=i;j++)
        printf("The left triangle of numbers is as follows - \n");
        printf("%d",j);
    printf("\n");
}   
}

void righttriangle(int i,int j,int k,int n)
{
printf("Enter the value of n : ");
scanf("%d",&n);

for(i=1;i<=n;i++)
{
    for(j=i;j<=n;j++)
    {
        printf("The right triangle of numbers is as follows - \n");
        printf(" ");
    }
    for(k=1;k<=i;k++)
    {
        printf("%d",k);
    }
    printf("\n");
}

}

int main()
{
int choice;
int i,j,k,n, m=1;
do
{
    printf("\nEnter the choice below.\n");
    printf("*************************\n");
    printf("1-> Left Traingle.\n");
    printf("2-> Right Triangle.\n");
    printf("3-> Pascal Triangle.\n");
    printf("*************************\n");
    scanf("%d",&choice);
    switch(choice)
    
    {
        case 1:
            printf("Enter the value of n : ");
            scanf("%d",&n);
            void lefttriangle( i,j, n);
            break;
            
        case 2:
            printf("Enter the value of n : ");
            scanf("%d",&n);
            void righttriangle(i,j,k,n);
            break;
            
        case 3:
            printf("Enter the value of n : ");
            scanf("%d",&n);
            void pascaltriangle(i, j, k, n, m);
            break;
        case 4:
            printf("Thank you!\n");
            exit(0);
        default:
            printf("Enter a valid number.\n");
    } 
    
}while(1);
return(0);

}

Solution

  • In your switch, when 4 is entered, that case corresponds to:

    printf("Thank you!\n");
    exit(0);
    

    Only if the user enters 1 will the left triangle function be called.

    Further, when calling these functions, you don't put the return type in front of them. You only do that when declaring and/or implementing them.