PPS Unit 5 Important Programs

 Unit 5 - Functions

5.1 - Write a function which receives number as argument and return sum of digit of that number. [S-10]


5.2 - Write a function which takes 2 numbers as parameters and returns the gcd of the 2 numbers. Call the function in main(). [S-17]

#include <stdio.h>

int main()

{

    int n1, n2, i, gcd;

    printf("Enter two integers: ");

    scanf("%d %d", &n1, &n2);

    for(i=1; i <= n1 && i <= n2; ++i)

    {

        if(n1%i==0 && n2%i==0)

        gcd = i;

    }

    printf("G.C.D of %d and %d is %d", n1, n2, gcd);

    return 0;

}


5.3 - Write a function to swap 2 numbers. OR   Create a function to swap the values of two variables. [S-17, W-18]

#include<stdio.h>

#include<conio.h>

void swap(int *, int *);

void main() 

    int x,y,z; 

    printf("Enter the value of x and y : \n"); 

    scanf("%d %d",&x,&y);

    printf("Before Swapping\nx = %d\ny = %d\n",x,y);

    swap(&x, &y);

    printf("After Swapping\nx = %d\ny = %d\n",x,y);

    getch(); 

}

void swap(int *x, int *y) 

    int temp;

    temp = *x; 

    *x = *y; 

    *y = temp; 

}

5.4 - Create a function to check number is prime or not. If number is prime then function return value 1 otherwise return 0. [W-18, W-19, S-20]

#include<stdio.h>

int prime_num(int);

void main()

{

    int n,result=0;

    printf("Enter One Number : ");

    scanf("%d",&n);

    result=prime_num(n);

    if(result==0)

    {

        printf("\n %d is prime number. ",n);

    }

    else

    {

    printf("\n %d is not prime number. ",n);

    }

}

int prime_num(int a)

{

    int i;

    for(i=2;i<=a/2;i++)

    {

        if(a%i!=0)

        {

            continue;

        }

        else

        {

            return 1;

        }

    }

    return 0;

}


5.5 - Write a program to calculate nCr using user defined function. NCr = n! / (r! * (n-r)!) [S-19]

#include <stdio.h>

int fact(int);

void main()

{

    int n,r,ncr;

   printf("Enter a number n : ");

   scanf("%d",&n);

    printf("Enter a number r : ");

   scanf("%d",&r);

   ncr=fact(n)/(fact(r)*fact(n-r));

    printf("Value of %dC%d = %d\n",n,r,ncr);

}

int fact(int n)

{

    int i,f=1;

    for(i=1;i<=n;i++)

    {

        f=f*i;

    }

    return f;

}

No comments:

Post a Comment

If you have any doubts or suggestions, Please let me know