Programming with C

⌘K
  1. Home
  2. Docs
  3. Programming with C
  4. Functions and Pointers
  5. Additional Programs Func Pointers

Additional Programs Func Pointers

Devise a C function that checks whether a given number is prime of not and illustrate its use

#include<stdio.h>
int prime(int n);
int main()
{
	int num;
	printf("Enter the number to be checked");
	scanf("%d",&num);
	if(prime(num) == 0)
		printf("Number is not prime \n");
	else
		printf("Number is prime \n");
	return 0;
}
int prime(int no)
{
	int i;
	for(i=2;i<no;i++)
	{
		if(no%i == 0) // if number is divisible by any number from 2 to n-1
		{	
			return 0;
		}
	}
	return 1;
}

Output

Enter the number to be checked 5
Number is prime

Devise a C function to sum the digits in a number

#include<stdio.h>
int add_digit(int a);
int main()
{
	int num, sum;
	printf("Enter the number:");
	scanf("%d",&num);
	sum = add_digit(num);
	printf("Sum of digits is: %d", sum);
	return 0;
}
int add_digit(int n)
{
	int digit, s=0;
	while(n!=0)
	{
		digit = n % 10;
		s = s + digit;
		n = n / 10;
	}
	return s;
}

Output

Enter the number:541
Sum of digits is: 10

Devise a c function to reverse the given number

#include<stdio.h>
int rev_number(int a);
int main()
{
	int num, rev;
	printf("Enter the number:");
	scanf("%d",&num);
	rev = rev_number(num);
	printf("Reverse of number is: %d", rev);
	return 0;
}
int rev_number(int n)
{
	int digit, r=0;
	while(n!=0)
	{
		digit = n % 10;
		n = n / 10;
		r = r * 10 + digit;
	}
	return r;
}

Output

Enter the number:541
Reverse of number is: 145

Devise a C function to check whether a number is palindrome or not

#include<stdio.h>
int rev_number(int a);
int main()
{
	int num, rev;
	printf("Enter the number:");
	scanf("%d",&num);
	rev = rev_number(num);
	printf("Reverse of number is: %d", rev);
	if ( num == rev)
	{
		printf("\n%d is palindrom", num);
	}
	else
	{
		printf("\n%d is not palindrome",num);
	}
	return 0;
}
int rev_number(int n)
{
	int digit, r=0;
	while(n!=0)
	{
		digit = n % 10;
		n = n / 10;
		r = r * 10 + digit;
	}
	return r;
}

Output

Enter the number:541
Reverse of number is: 145
541 is not palindrome

Views: 0

How can we help?

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments