Tuesday 10 January 2012

Common C Programs

1. Write a program for factorial of a given number.
#include<stdio.h>
int factorial(int n);
int main()
{
int x,i;
printf("Enter a value for x \n");
scanf("%d",&x);
i=factorial(x);
printf("\n Factorial of %d is %d"x,i);
return 0;
}
int factorial(int n)
{
if(n<=0)
{
return(1);
}
else
{
return(n*factorial(n-1));
}
}

2. Write a program for detecting Even and odd number.
#include<stdio.h>
int main()
{
int a;
printf("Enter the number");
scanf("%d"&a);
if(a%2==0)
{
printf("given number is Even");
}
else
{
printf("given number is Odd");
}
return 0;
}

3. Write a program to swap two numbers using a temporary variable.
#include<stdio.h>
int main()
{
int temp,a,b;
printf("Enter the value of a and b");
scanf("a=%d,b=%d"&a,&b);
temp=a;
a=b;
b=temp;
printf(new value of a=%d and b=%d"a,b);
return 0;
}


4.Write a program for the prime number.
#include<stdio.h>
int main()
{
int n,c;
c=0;
printf("Enter the number");
scanf("%d"&n);
for(int i=1;i<=n;i++)
{
if(n%i==0)
{
c++;
}
}
if(c==2)
{
printf("Number is prime");
}
else
{
printf("number is not prime");
}
return 0;
}

No comments:

Post a Comment