Tuesday 22 January 2013

Diamond Shape

/*C code to print a diamond shape when an odd number is entered*/

#include <stdio.h>

/*Function to check whether the number entered is valid or not*/
int check_validity(n)
{
    if (n%2 ==0 || n<=0)
        return 0;
       
    else
        return 1;
}

/*Function to print upper part of the diamond shape for an odd entered number*/
void diamond_upper_shape(n)
{
    int  i , j ,  m ;

    for (i=1 ; i<=n ; i=i+2)
    {       
        for (m=1 ; m<=(n-i)/2 ; m++)
            printf ("  ");
               
        for (j=1;j<=i;j=j+1)           
            printf (" *");                                           

        printf ("\n");
    }       
}

/*Function to print the lower part of the diamond shape for an odd entered number*/
void diamond_lower_shape(n)
{
    int  i , j ,  m ;
   
    for (i=n-2 ; i>=1 ; i=i-2 )
    {   
        for (m=1 ; m<=(n-i)/2  ; m++)
            printf ("  ");
                                       
        for (j=1 ; j<=i ; j=j+1)
            printf (" *");                                           
                                       
        printf ("\n");   
    }

}
/*main function*/
int main()
{
    int  i , j ,  n  , m ;
   
    printf ("enter an odd no.");
    scanf ("%d",&n);
   
    if (check_validity(n)!=0)
    {
        diamond_upper_shape(n);   
        diamond_lower_shape(n);
    }
   
    else
        printf("Enter an odd number\n");
}

No comments:

Post a Comment