Example 1: Prime Numbers Between Two Integers
#include <stdio.h>
int checkPrimeNumber(int n);
int main()
{
int n1, n2, i, flag;
printf("Enter two positive integers: ");
scanf("%d %d", &n1, &n2);
printf("Prime numbers between %d and %d are: ", n1, n2);
for(i=n1+1; i<n2; ++i)
{
// i is a prime number, flag will be equal to 1
flag = checkPrimeNumber(i);
if(flag == 1)
printf("%d ",i);
}
return 0;
}
// user-defined function to check prime number
int checkPrimeNumber(int n)
{
int j, flag = 1;
for(j=2; j <= n/2; ++j)
{
if (n%j == 0)
{
flag =0;
break;
}
}
return flag;
}
Output
Enter two positive integers: 12 30 Prime numbers between 12 and 30 are: 13 17 19 23 29
Example 3: Check Prime and Armstrong Number
#include <stdio.h> #include <math.h> int checkPrimeNumber(int n); int checkArmstrongNumber(int n); int main() { int n, flag; printf("Enter a positive integer: "); scanf("%d", &n); // Check prime number flag = checkPrimeNumber(n); if (flag == 1) printf("%d is a prime number.\n", n); else printf("%d is not a prime number.\n", n); // Check Armstrong number flag = checkArmstrongNumber(n); if (flag == 1) printf("%d is an Armstrong number.", n); else printf("%d is not an Armstrong number.",n); return 0; } int checkPrimeNumber(int n) { int i, flag = 1; for(i=2; i<=n/2; ++i) { // condition for non-prime number if(n%i == 0) { flag = 0; break; } } return flag; } int checkArmstrongNumber(int number) { int originalNumber, remainder, result = 0, n = 0, flag; originalNumber = number; while (originalNumber != 0) { originalNumber /= 10; ++n; } originalNumber = number; while (originalNumber != 0) { remainder = originalNumber%10; result += pow(remainder, n); originalNumber /= 10; } // condition for Armstrong number if(result == number) flag = 1; else flag = 0; return flag; }
OutputEnter a positive integer: 407 407 is not a prime number. 407 is an Armstrong number.Example 1: Program to convert binary number to decimal
#include <stdio.h> #include <math.h> int convertBinaryToDecimal(long long n); int main() { long long n; printf("Enter a binary number: "); scanf("%lld", &n); printf("%lld in binary = %d in decimal", n, convertBinaryToDecimal(n)); return 0; } int convertBinaryToDecimal(long long n) { int decimalNumber = 0, i = 0, remainder; while (n!=0) { remainder = n%10; n /= 10; decimalNumber += remainder*pow(2,i); ++i; } return decimalNumber; }
OutputEnter a binary number: 110110111 110110111 in binary = 439
0 Comments:
Post a Comment