Thursday, 18 August 2016

HCF and LCM

HCF and LCM

#include < stdio.h >

long gcd(long, long);
int main() {
  long x, y, hcf, lcm;

  printf("Enter two integers\n");
  scanf("%ld%ld", &x, &y);

  hcf = gcd(x, y);
  lcm = (x*y)/hcf;

  printf("Greatest common divisor of %ld and %ld = %ld\n", x, y, hcf);
  printf("Least common multiple of %ld and %ld = %ld\n", x, y, lcm);

  return 0;
}

/*if 1st no is 0 then 2nd no is gcd
make 2nd no 0 by subtracting smallest from largest and return 1st no as gcd*/
long gcd(long x, long y) {
  if (x == 0) {
  return y;
  }

  while (y != 0) {
  if (x > y) {
    x = x - y;
  }
  else {
    y = y - x;
  }
}

return x;
}

Reverse number

Reverse number

#include < stdio.h >

int main()
{
  int n, reverse = 0;

  printf("Enter a number to reverse\n");
  scanf("%d",&n);

  while (n != 0)
{
  reverse = reverse * 10;
  reverse = reverse + n%10;
  n = n/10;
}
/*taking unit place digit of no and moving to reverse
Dividing the no to discard unit place digit*/

  printf("Reverse of entered number is = %d\n", reverse);

  return 0;
}

Prime numbers

Prime numbers

#include < stdio.h >

int check_prime(int);

main()
{
  int i, n, result;

  printf("Enter the number of prime numbers required\n");
  scanf("%d",&n);
  printf("First %d prime numbers are :\n", n);

  for(i=0; i < n; i++){
  result = check_prime(i);
  /*if i is prime then it will return 1*/

  if ( result == 1 )
    printf("%d \n", i);
  }
  return 0;
}

int check_prime(int a)
{
  int c;
  /*starting from 2, if no is completely divisible by any no then it is not prime*/
  for ( c = 2 ; c <= a - 1 ; c++ )
  {
  if ( a%c == 0 )
    return 0;
  }
  if ( c == a )
    return 1;
}

Temperature conversion

Temperature conversion

#include < stdio.h >

void main()
{
int from , to;
float value;

printf("Temperature Conversion\n");
printf("Enter no of Unit to covert from : \n 1.celcius\n 2. Farenheit\n 3. Kelvin");
scanf("%d",&from);

printf("Enter no of Unit to covert to : \n 1.celcius\n 2. Farenheit\n 3. Kelvin");
scanf("%d",&to);

printf("Enter The value to convert: ");
scanf("%f",&value);

/*converting given value from specified unit to Kelvin*/
switch(from) {
  case 1:
  value= value + 273.15; break;
  case 2:
  value= (value+459.67)*5/9; break;
  case 3: break;
  default: break;
  }

/*converting value from Kelvin to specified unit*/
switch(to) {
  case 1:
  value= value-273.15; break;
  case 2:
  value= value*9/5-459.67; break;
  case 3: break;
  default: break;
  }

printf("Converted Value : %f", value);
}