Categories
c programming Programs

C Program to Convert Binary Number to Decimal

// convert binary to decimal

#include <stdio.h>
#include <math.h>

// function prototype
int convert(long long);

int main() {
  long long n;
  printf("Enter a binary number: ");
  scanf("%lld", &n);
  printf("%lld in binary = %d in decimal", n, convert(n));
  return 0;
}

// function definition
int convert(long long n) {
  int dec = 0, i = 0, rem;

  while (n!=0) {
    rem = n % 10;
    n /= 10;
    dec += rem * pow(2, i);
    ++i;
  }

  return dec;
}

Output

Enter a binary number: 1101
1101 in binary = 13 in decimal

In the program, we have included the header file math.h to perform mathematical operations in the program.

We ask the user to enter a binary number and pass it to the convert() function to convert it decimal.

Suppose n = 1101. Let’s see how the while loop in the convert() function works.

n != 0rem = n % 10n /= 10idec += rem * pow(2, i)
1101 != 01101 % 10 = 11101 / 10 = 11000 + 1 * pow (2, 0) = 1
110 != 0110 % 10 = 0110 / 10 = 1111 + 0 * pow (2, 1) = 1
10 != 011 % 10 = 111 /10 = 121 + 1 * pow (2, 2) = 5
1 != 01 % 10 = 11 / 10 = 035 + 1 * pow (2, 3) = 13
0 != 0Loop terminates

So, 1101 in binary is 13 in decimal.

Now, let’s see how we can change the decimal number into a binary number.

Example 2: C Program to convert decimal number to binary

// convert decimal to binary

#include <stdio.h>
#include <math.h>

long long convert(int);

int main() {
  int n, bin;
  printf("Enter a decimal number: ");
  scanf("%d", &n);
  bin = convert(n);
  printf("%d in decimal =  %lld in binary", n, bin);
  return 0;
}

long long convert(int n) {
  long long bin = 0;
  int rem, i = 1;

  while (n!=0) {
    rem = n % 2;
    n /= 2;
    bin += rem * i;
    i *= 10;
  }

  return bin;
}

Output

Enter a decimal number: 13
13 in decimal = 1101 in binary

Suppose n = 13. Let’s see how the while loop in the convert() function works.

n != 0rem = n % 2n /= 2ibin += rem * ii * = 10
13 != 013 % 2 = 113 / 2 = 610 + 1 * 1 = 11 * 10 = 10
6 != 06 % 2 = 06 / 2 = 3101 + 0 * 10 = 110 * 10 = 100
3 != 03 % 2 = 13 / 2 = 11001 + 1 * 100 = 101100 * 10 = 1000
1 != 01 % 2 = 11 / 2 = 01000101 + 1 * 1000 = 11011000 * 10 = 10000
0 != 0Loop terminates

Thus, 13 in decimal is 1101 in binary.

Categories
c programming Programs

Simple Calculator using switch Statement

This program takes an arithmetic operator +, -, *, / and two operands from the user. Then, it performs the calculation on the two operands depending upon the operator entered by the user.

Simple Calculator using switch Statement

#include <stdio.h>
int main() {
  char op;
  double first, second;
  printf("Enter an operator (+, -, *, /): ");
  scanf("%c", &op);
  printf("Enter two operands: ");
  scanf("%lf %lf", &first, &second);

  switch (op) {
    case '+':
      printf("%.1lf + %.1lf = %.1lf", first, second, first + second);
      break;
    case '-':
      printf("%.1lf - %.1lf = %.1lf", first, second, first - second);
      break;
    case '*':
      printf("%.1lf * %.1lf = %.1lf", first, second, first * second);
      break;
    case '/':
      printf("%.1lf / %.1lf = %.1lf", first, second, first / second);
      break;
    // operator doesn't match any case constant
    default:
      printf("Error! operator is not correct");
  }

  return 0;
}

Output

Enter an operator (+, -, *,): *
Enter two operands: 1.5
4.5
1.5 * 4.5 = 6.8

The * operator entered by the user is stored in op. And, the two operands, 1.5 and 4.5 are stored in first and second respectively.

Since the operator * matches case '*':, the control of the program jumps to

printf("%.1lf * %.1lf = %.1lf", first, second, first * second);

This statement calculates the product and displays it on the screen.

To make our output look cleaner, we have simply limited the output to one decimal place using the code %.1lf.

Finally, the break; statement ends the switch statement.

Categories
c programming Programs

Factors of a Positive Integer

This program takes a positive integer from the user and displays all the positive factors of that number.

Factors of a Positive Integer

#include <stdio.h>
int main() {
    int num, i;
    printf("Enter a positive integer: ");
    scanf("%d", &num);
    printf("Factors of %d are: ", num);
    for (i = 1; i <= num; ++i) {
        if (num % i == 0) {
            printf("%d ", i);
        }
    }
    return 0;
}

Output

Enter a positive integer: 60
Factors of 60 are: 1 2 3 4 5 6 10 12 15 20 30 60

In the program, a positive integer entered by the user is stored in num.

The for loop is iterated until i is false.

In each iteration, whether num is exactly divisible by i is checked. It is the condition for i to be a factor of num.

if (num % i == 0) {
            printf("%d ", i);
}

Then the value of i is incremented by 1.

Categories
c programming Programs

Armstrong Numbers Between Two Integers

A positive integer is called an Armstrong number (of order n) if

abcd... = an + bn + cn + dn + 

In the case of an Armstrong number of 3 digits, the sum of cubes of each digit is equal to the number itself. For example, 153 is an Armstrong number because

153 = 1*1*1 + 5*5*5 + 3*3*3

In this program, we will print all the Armstrong numbers between two integers. This means that the two integers will not be part of the range, but only those integers that are between them.

For example, suppose we want to print all Armstrong numbers between 153 and 371. Both of these numbers are also Armstrong numbers.

Then, this program prints all Armstrong numbers that are greater than 153 and less than 371 i.e. 153 and 371 won’t be printed even though they are Armstrong numbers.

Armstrong Numbers Between Two Integers

#include <math.h>
#include <stdio.h>
int main() {
  int low, high, number, originalNumber, rem, count = 0;
  double result = 0.0;
  printf("Enter two numbers(intervals): ");
  scanf("%d %d", &low, &high);
  printf("Armstrong numbers between %d and %d are: ", low, high);

  // swap numbers if high < low
  if (high < low) {
    high += low;
    low = high - low;
    high -= low;
  }
   
  // iterate number from (low + 1) to (high - 1)
  // In each iteration, check if number is Armstrong
  for (number = low + 1; number < high; ++number) {
    originalNumber = number;

    // number of digits calculation
    while (originalNumber != 0) {
      originalNumber /= 10;
      ++count;
    }

    originalNumber = number;

    // result contains sum of nth power of individual digits
    while (originalNumber != 0) {
      rem = originalNumber % 10;
      result += pow(rem, count);
      originalNumber /= 10;
    }

    // check if number is equal to the sum of nth power of individual digits
    if ((int)result == number) {
      printf("%d ", number);
    }

    // resetting the values
    count = 0;
    result = 0;
  }

  return 0;
}

Output

Enter two numbers(intervals): 200
2000
Armstrong numbers between 200 and 2000 are: 370 371 407 1634 

In the program, the outer loop is iterated from (low+ 1) to (high – 1). In each iteration, it’s checked whether number is an Armstrong number or not.

Inside the outer loop, the number of digits of an integer is calculated first and stored in count. And, the sum of the power of individual digits is stored in the result variable.

If number is equal to result, the number is an Armstrong number.

Notes:

  • You need to swap low and high if the user input for high is less than that of low. To learn more, check our example on swapping two numbers.
  • You need to reset count and result to 0 in each iteration of the outer loop.
Categories
c programming Programs

Check Armstrong Number of three digits

A positive integer is called an Armstrong number (of order n) if

abcd... = an + bn + cn + dn + 

In the case of an Armstrong number of 3 digits, the sum of cubes of each digit is equal to the number itself. For example, 153 is an Armstrong number because

153 = 1*1*1 + 5*5*5 + 3*3*3 

Check Armstrong Number of three digits

#include <stdio.h>
int main() {
    int num, originalNum, remainder, result = 0;
    printf("Enter a three-digit integer: ");
    scanf("%d", &num);
    originalNum = num;

    while (originalNum != 0) {
       // remainder contains the last digit
        remainder = originalNum % 10;
        
       result += remainder * remainder * remainder;
        
       // removing last digit from the orignal number
       originalNum /= 10;
    }

    if (result == num)
        printf("%d is an Armstrong number.", num);
    else
        printf("%d is not an Armstrong number.", num);

    return 0;
}

Output

Enter a three-digit integer: 371
371 is an Armstrong number.

Check Armstrong Number of n digits

#include <math.h>
#include <stdio.h>

int main() {
   int num, originalNum, remainder, n = 0;
   float result = 0.0;

   printf("Enter an integer: ");
   scanf("%d", &num);

   originalNum = num;

   // store the number of digits of num in n
   for (originalNum = num; originalNum != 0; ++n) {
       originalNum /= 10;
   }

   for (originalNum = num; originalNum != 0; originalNum /= 10) {
       remainder = originalNum % 10;

      // store the sum of the power of individual digits in result
      result += pow(remainder, n);
   }

   // if num is equal to result, the number is an Armstrong number
   if ((int)result == num)
    printf("%d is an Armstrong number.", num);
   else
    printf("%d is not an Armstrong number.", num);
   return 0;
}

Output

Enter an integer: 1634
1634 is an Armstrong number.

In this program, the number of digits of an integer is calculated first and stored in n. And, the pow() function is used to compute the power of individual digits in each iteration of the second for loop.

Categories
c programming Programs

Display Prime Numbers Between Two Intervals

Display Prime Numbers Between Two Intervals

#include <stdio.h>

int main() {
   int low, high, i, flag;
   printf("Enter two numbers(intervals): ");
   scanf("%d %d", &low, &high);
   printf("Prime numbers between %d and %d are: ", low, high);

   // iteration until low is not equal to high
   while (low < high) {
      flag = 0;

      // ignore numbers less than 2
      if (low <= 1) {
         ++low;
         continue;
      }

      // if low is a non-prime number, flag will be 1
      for (i = 2; i <= low / 2; ++i) {

         if (low % i == 0) {
            flag = 1;
            break;
         }
      }

      if (flag == 0)
         printf("%d ", low);

      // to check prime for the next number
      // increase low by 1
      ++low;
   }

   return 0;
}

Output

Enter two numbers(intervals): 20 
50
Prime numbers between 20 and 50 are: 23 29 31 37 41 43 47

In this program, the while loop is iterated ( high-low-1) times.

In each iteration, whether low is a prime number or not is checked, and the value of low is incremented by 1 until low is equal to high.

Visit this page to learn more about how to check whether a number is prime or not.

If the user enters the larger number first, the above program doesn’t work as intended. You can solve this issue by swapping the numbers.

Display Prime Numbers when Larger Number is Entered first

#include <stdio.h>

int main() {
   int low, high, i, flag, temp;
   printf("Enter two numbers(intervals): ");
   scanf("%d %d", &low, &high);

   // swap numbers if low is greather than high
   if (low > high) {
      temp = low;
      low = high;
      high = temp;
   }

   printf("Prime numbers between %d and %d are: ", low, high);
   while (low < high) {
      flag = 0;

      // ignore numbers less than 2
      if (low <= 1) {
         ++low;
         continue;
      }

      for (i = 2; i <= low / 2; ++i) {
         if (low % i == 0) {
            flag = 1;
            break;
         }
      }
      if (flag == 0)
         printf("%d ", low);
      ++low;
   }

   return 0;
}
Categories
c programming Programs

Program to Check Prime Number

A prime number is a positive integer that is divisible only by 1 and itself. For example: 2, 3, 5, 7, 11, 13, 17

Program to Check Prime Number

#include <stdio.h>
int main() {
  int n, i, flag = 0;
  printf("Enter a positive integer: ");
  scanf("%d", &n);

  for (i = 2; i <= n / 2; ++i) {
    // condition for non-prime
    if (n % i == 0) {
      flag = 1;
      break;
    }
  }

  if (n == 1) {
    printf("1 is neither prime nor composite.");
  } 
  else {
    if (flag == 0)
      printf("%d is a prime number.", n);
    else
      printf("%d is not a prime number.", n);
  }

  return 0;
}

Output

Enter a positive integer: 29
29 is a prime number.

In the program, a for loop is iterated from i = 2 to i < n/2.

In each iteration, whether n is perfectly divisible by i is checked using:

if (n % i == 0) {
    flag = 1;
    break;
}

If n is perfectly divisible by in is not a prime number. In this case, flag is set to 1, and the loop is terminated using the break statement.

Notice that we have initialized flag as 0 during the start of our program.

So, if n is a prime number after the loop, flag will still be 0. However, if n is a non-prime number, flag will be 1.

Categories
c programming Programs

Program to Check Palindrome

An integer is a palindrome if the reverse of that number is equal to the original number.

Program to Check Palindrome

#include <stdio.h>
int main() {
  int n, reversed = 0, remainder, original;
    printf("Enter an integer: ");
    scanf("%d", &n);
    original = n;

    // reversed integer is stored in reversed variable
    while (n != 0) {
        remainder = n % 10;
        reversed = reversed * 10 + remainder;
        n /= 10;
    }

    // palindrome if orignal and reversed are equal
    if (original == reversed)
        printf("%d is a palindrome.", original);
    else
        printf("%d is not a palindrome.", original);

    return 0;
}

Output

Enter an integer: 1001
1001 is a palindrome.

Here, the user is asked to enter an integer. The number is stored in variable n.

We then assigned this number to another variable orignal. Then, the reverse of n is found and stored in reversed.

If original is equal to reversed, the number entered by the user is a palindrome.

Categories
c programming Programs

Power of a Number Using the while Loop

The program below takes two integers from the user (a base number and an exponent) and calculates the power.

For example: In the case of 23

  • 2 is the base number
  • 3 is the exponent
  • And, the power is equal to 2*2*2

Power of a Number Using the while Loop

#include <stdio.h>
int main() {
    int base, exp;
    long double result = 1.0;
    printf("Enter a base number: ");
    scanf("%d", &base);
    printf("Enter an exponent: ");
    scanf("%d", &exp);

    while (exp != 0) {
        result *= base;
        --exp;
    }
    printf("Answer = %.0Lf", result);
    return 0;
}

Output

Enter a base number: 3
Enter an exponent: 4
Answer = 81

We can also use the pow() function to calculate the power of a number.

Power Using pow() Function

#include <math.h>
#include <stdio.h>

int main() {
    double base, exp, result;
    printf("Enter a base number: ");
    scanf("%lf", &base);
    printf("Enter an exponent: ");
    scanf("%lf", &exp);

    // calculates the power
    result = pow(base, exp);

    printf("%.1lf^%.1lf = %.2lf", base, exp, result);
    return 0;
}

Output

Enter a base number: 2.3
Enter an exponent: 4.5
2.3^4.5 = 42.44

The programs above can only calculate the power of the base number if the exponent is positive. For negative exponents, use the following mathematical logic:

base(-exponent) = 1 / (baseexponent)

For example,

2-3 = 1 / (23)
Categories
c programming Programs

Reverse an Integer

#include <stdio.h>
int main() {
    int n, rev = 0, remainder;
    printf("Enter an integer: ");
    scanf("%d", &n);
    while (n != 0) {
        remainder = n % 10;
        rev = rev * 10 + remainder;
        n /= 10;
    }
    printf("Reversed number = %d", rev);
    return 0;
}

Output

Enter an integer: 2345
Reversed number = 5432

This program takes an integer input from the user. Then the while loop is used until n != 0 is false (0).

In each iteration of the loop, the remainder when n is divided by 10 is calculated and the value of n is reduced by 10 times.

Inside the loop, the reversed number is computed using:

rev = rev*10 + remainder;