Thursday, May 16, 2013

c programming for mathematical calculations....


-->


  1) How to convert a decimal integer to hexadecimal?








#include<stdio.h>
main()
{
int a;
scanf("%d",&a);
printf("%x",a);
}

This program converts a decimal integer to hexadecimal integer.
To convert hexadecimal integer to decimal integer by replacing %d by %x and %x by %b.

#include<stdio.h>
main()
{
int a;
scanf("%x",&a);
printf("%d",a);
}







 2) Write a program to find sum of digit of a number ?




#include<stdio.h>
main()
{
int n,i,j,sum=0;
printf("enter a number:");
scanf("%d",&n);
printf("sum of digits of %d is \n",n);
while(n)
{
i=n;
j=i%10;
n=i/10;
sum=sum+j;
}
printf("%d \n",sum);
}







 3) Write a c program to check a number prime or not?




#include<stdio.h>
main()
{
int a,b,count=0;
printf("enter no:");
scanf("%d",&b);
for(a=2;a<b;a++)
{
if(b%a==0)
{
count++;
break;
}
}
if(count==0)
{
printf("prime \n");
}
else
{
printf("not prime \n");
}
}









4) Write a c program to find the LCM & HCF of two given numbers?





#include<stdio.h>
main()
{
int n1,n2,d,lcm,hcf,r,product;
printf("enter two numbers:");
scanf("%d%d",&n1,&n2);
product=n1*n2;
while(n1!=n2)
{
if(n1>n2)
n1=n1-n2;
else
n2=n2-n1;
}
hcf=n1;
lcm=product/hcf;
printf("HCF: %d",hcf);
printf("\nLCM: %d",lcm);
}








5) Write a c program to list Fibonacci Series up to n terms?





#include<stdio.h>
main()
{
int a=1,b=0,c=0,n;
printf("enter the number:");
scanf("%d",&n);
while(c<=n)
{
printf("%d \n",c);
c=a+b;
a=b;
b=c;
}
}




 Algorithm for fibonacci series

1)Declare all variables a=1,b=0,c=0 &n.
   (because, first two numbers are 0 & 2)
2)store input(a integer value) to a variable.
3)Answer-----0 1 1 2 3 5 8
  so, current number should be sum of two previous numbers.
  c=a+b;
  a=b;
  This command is used to store previous value of
  b to a.
  b=c;
  This command is used to store previous value of
  c to a.





No comments:

Post a Comment