Code Scrappers

Categories of Function

For better understanding of arguments and return type in functions, user-defined functions can be categorized as:

C programs to check if the number entered is prme or not

Function with no arguments and no return value.

#include <stdio.h>

void prime();

void main()

{

  prime();

}


void prime()

{

  int n, i, count=0;

  printf("Enter a positive integer:\n");

  scanf("%d",&n);

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

{

       if(n%i==0)

       {

           count=1;

        }

}

   if (count==1)

       {

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

      }
   else

       {

        printf("%d is prime",n);

       }
}

Function prime() is used for asking user a input, check for whether it is prime or not and display it accordingly. No argument is passed and returned form prime() function.

Function with no arguments but return value



#include <stdio.h>

int input();

void main()

{

  int number,i;
  int count = 0;

  number=input();

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

  {

    if(number%i==0)

    {



        count = 1;

        break;

    }

}

   if(count == 1)

      {

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

     }
     else

     {
       printf("%d is prime", number);
     }

}


int input()

{


  int n;

  printf("Enter a positive integer:\n");

  scanf("%d",&n);

  return n;

}

There is no argument passed to input() function But, the value of n is returned from input() tomain() function.

Function with arguments and no return value


#include <stdio.h>

void prime(int n);

void main()

{

  int number;

  printf("Enter positive integer:\n");

  scanf("%d",&number);

  prime(number);


}

void prime(int n)

{
  int i;
  int count = 0;

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

{

    if(n%i==0)

{

        count = 1;

        break;

}


}

   if(count == 1)

   {

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

   }
   else

   {

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

   }
}

Here, prime() function is used for check whether it is prime or not and display it accordingly. Here, argument is passed to user-defined function but, value is not returned from it to calling function.

Function with argument and a return value


#include <stdio.h>

int check(int n);

void main()

{

  int number,numbercheck=0;

  printf("Enter positive number:\n");

  scanf("%d",&number);

  numbercheck=check(number);

  if(numbercheck==1)

     {

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

      }

  else

     {

      printf("%d is prime",number);

     }
}


int check(int n)

{


  int i;

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

{

   if(n%i==0)

      {
        return 1;
      }
}

 return 0;

}

Here, check() function is used for checking whether a number is prime or not. In this program, input from user is passed to function check() and integer value is returned from it. If input the number is prime, 0 is returned and if number is not prime, 1 is returned.

<< Back Next >>