[go: up one dir, main page]

0% found this document useful (0 votes)
14 views17 pages

unit III

The document contains various C programs that demonstrate mathematical concepts such as calculating the sum of digits, checking for prime numbers, finding prime factors, determining amicable numbers, and identifying perfect numbers. It also includes functions for converting numbers between different bases and their decimal equivalents. Each program is accompanied by explanations and examples of their functionality.

Uploaded by

dipali18
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views17 pages

unit III

The document contains various C programs that demonstrate mathematical concepts such as calculating the sum of digits, checking for prime numbers, finding prime factors, determining amicable numbers, and identifying perfect numbers. It also includes functions for converting numbers between different bases and their decimal equivalents. Each program is accompanied by explanations and examples of their functionality.

Uploaded by

dipali18
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 17

#include <stdio.

h>
int main()
{
// Declaring variable names
int ch, sum, x;
char num[1000];

// Take number input from the user


printf("Enter a number\n");
scanf("%s", num);

sum = ch = 0;

// Loop using a while statement


while (num[ch] != '\0') {

// Convert character input into an integer


x = num[ch] - '0';
sum = sum + x;

// Increment of character input


ch++;
}

printf("Sum of digits of %s = %d\n", num, sum);


return 0;
}

#include <string.h>
int sumOfDigits(char *s) {
int sum = 0;
for (int i = 0; i < strlen(s); i++) {

// Extract digit from character


int digit = s[i] - '0';

// Add digit to the sum


sum = sum + digit;
}
return sum;
}

int main() {
char s[] = "123456789123456789123422";

printf("%d", sumOfDigits(s));
return 0;
}
#include <stdio.h>
#include <math.h>

int main() {
long num, digit, sum = 0;
int countDigits = 0;
long temp = num;
int i;

printf("Enter the number \n");


scanf("%ld", &num);
temp = num;
while (num > 0) {
digit = num % 10;
sum = sum + digit;
num /= 10;
}
printf("Given number = %ld\n", temp);
printf("Sum of the digits %ld = %ld\n", temp, sum);

while (temp > 0) {


countDigits += 1;
temp /= 10;
}

i = 0;
sum = 0;
while (num > 0) {
digit = num % 10;
sum = sum + pow(digit, countDigits);
countDigits -= 1;
num /= 10;
}

printf("The final sum is %d\n", sum);


}

#include <stdio.h>

// Declaring a function
int digits_sum(int);

int main()
{
// Declaring variables
int number, result;

// Input from the user


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

// Calling out the function


result = digits_sum(number);
printf("The sum is %d\n", result);

return 0;
}

// Defining the function


int digits_sum(int number) {

// Base case
if (number == 0)
return 0;

// Recursive function
return (number%10 + digits_sum(number/10));
}

Program to Check Prime Number


#include <stdio.h>

int main() {

int n, i, flag = 0;
printf("Enter a positive integer: ");
scanf("%d", &n);

// 0 and 1 are not prime numbers


// change flag to 1 for non-prime number
if (n == 0 || n == 1)
flag = 1;

for (i = 2; i <= n / 2; ++i) {

// if n is divisible by i, then n is not prime


// change flag to 1 for non-prime number
if (n % i == 0) {
flag = 1;
break;
}
}

// flag is 0 for prime numbers


if (flag == 0)
printf("%d is a prime number.", n);
else
printf("%d is not a prime number.", n);

return 0;
}
Run Code
Output
Enter a positive integer: 29
29 is a prime number.
What is Prime factor?
Factors of a number that are prime numbers are called as Prime factors of that number. For
example: 2 and 5 are the prime factors of 10.
Logic to check prime factors of a number
Step by step descriptive logic to find prime factors.
1. Input a number from user. Store it in some variable say num.
2. Run a loop from 2 to num/2, increment 1 in each iteration. The loop structure should look
like for(i=2; i<=num/2; i++).
You may think why loop from 2 to num/2? Because prime number starts from 2 and any factor
of a number n is always less than n/2.
3. Inside the loop, first check if i is a factor of num or not. If it is a factor then check it is
prime or not.
Print the value of i if it is prime and a factor of num.
Program to find prime factors of a number
/**
* C program to find all prime factors of a given number
*/

#include <stdio.h>

int main()
{
int i, j, num, isPrime;

/* Input a number from user */


printf("Enter any number to print Prime factors: ");
scanf("%d", &num);

printf("All Prime Factors of %d are: \n", num);

/* Find all Prime factors */


for(i=2; i<=num; i++)
{
/* Check 'i' for factor of num */
if(num%i==0)
{
/* Check 'i' for Prime */
isPrime = 1;
for(j=2; j<=i/2; j++)
{
if(i%j==0)
{
isPrime = 0;
break;
}
}

/* If 'i' is Prime number and factor of num */


if(isPrime==1)
{
printf("%d, ", i);
}
}
}

return 0;
}
Copy
Enter any number to print Prime factors: 15
All Prime Factors of 15 are:
3, 5,

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

void primefactors(int n) {
// Print the number of 2s that divide n
while (n % 2 == 0) {
printf("%d ", 2);
n = n / 2; }
// n must be odd at this point. So we can skip ne element (Note i = i +2)
for (int i = 3; i <= sqrt(n); i = i + 2) {
// While i divides n, print i and divide n
while (n % i == 0) {
printf("%d ", i);
n = n / i;
}
}
//This condition is to handle the case when n is a prime number greater than 2
if (n > 2) {
printf("%d ", n);
}
int main() {
int number = 24;
printf("Prime factor of the number: ");
primefactors(number);
return 0;
}
Output:-
Prime factor of the number: 2 2 2 3

Explanation
Consider the numbers 220 and 284.
The proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55, and 110. Adding all these
divisors we get the sum as 284. Now take the proper divisors of 284. The proper divisors are 1,
2, 4, 71, and 142. Adding all these divisors we get the sum as 284. Since both the sum we
obtained is equal we can say that the pair of numbers
220 and 280 are amicable pairs.
Input
num1 = 220, num2 = 280
Output
220 and 280 are not amicable pair
Explanation
Consider the numbers 220 and 280.
The proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55, and 110. Adding all these
divisors we get the sum as 284. Now take the proper divisors of 284. The proper divisors are 1,
2, 4, 5, 7, 8, 10, 14, 20, 28, 35, 40, 56, 70 and 140.
Adding all these divisors we get the sum as 440. Since both the sum we obtained in this case is
not equal we can say that the pair of numbers 220 and 280 are not amicable pairs.
Algorithm
Step 1: Input the numbers.
Step 2: Find the sum of all divisors for both numbers.
Step 3: Finally check if the sum of the divisors of one number is equal to the other number or
not.
Step 4: If yes, it is an Amicable number and otherwise not.
Below is a C program to check whether the given pair of numbers is an amicable pair or not is
given below.
Example
Open Compiler

#include<stdio.h>
int main(){
int i,n1=220,n2=284,DivSum1=0,DivSum2=0;

//Use one for loop and check for each number starting from 1 to n1 -1.
for(int i=1;i<n1;i++){

//Check for each number in the loop if it can divide the number firstNumber or not. If yes, add
this number to the DivSum1. After the loop completes, DivSum1 includes the sum of all the
divisors for firstNumber.

if(n1 % i == 0){
DivSum1 = DivSum1 + i;
}
}

//Same way, determine the sum of all divisors for the second number and save it in DiviSum2.
for(int i=1;i<n2;i++){
if(n2 % i == 0){
DivSum2= DivSum2+ i;
}
}

//Last, check if the sum of divisors of the first number is equal to the second number or not. If
it is equal, then print that the numbers are Amicable numbers. Otherwise the numbers are not
amicable pairs.

if((n1== DivSum2) && (n2 == DivSum1)){


printf("%d and %d are Amicable numbers\n",n1,n2);
}else{
printf("%d and %d are not Amicable numbers\n",n1,n2);
}
}

Output
On execution, it will produce the following output:
220 and 284 are Amicable numbers.
Perfect Number
In mathematics, a perfect number is a positive integer that is equal to the sum of its positive
divisors, excluding the number itself.
For example, 6 is a positive number that is completely divisible by 1, 2, and 3. We know that
the number is also divisible by itself but we will include it in the addition of divisors. When
we add these divisors (1 + 2 + 3 = 6), it produces 6, which is equal to the number that we
have considered. So, we can say that 6 is a perfect number.

/*C program to check whether the given number is the Perfect number*/
#include<stdio.h>
#include<conio.h>
void main()
{
// declare and initialize the variables
int num, rem, sum = 0, i;
// take an input from the user.
printf("Enter a number\n");
scanf("%d", &num);
// find all divisors and add them
for(i = 1; i < num; i++)
{
rem = num % i;
if (rem == 0)
{
sum = sum + i;
}
}
if (sum == num)
printf(" %d is a Perfect Number");
else
printf("\n %d is not a Perfect Number");
getch();
}

/*Create a C Program to find the perfect number using while loop*/


#include<stdio.h>
#include<conio.h>
void main()
{
int i = 1, num, Sum = 0;
printf(" Enter any number to check Perfect Number \n");
scanf("%d", &num);

while(i < num )


{
if(num % i == 0)
Sum = Sum + i;
i++;
}
if(Sum == num)
printf("\n %d is Perfect Number", num);
else
printf("\n %d is not a Perfect Number", num);
getch();
}
Output

Convert from any base to decimal and vice versa


Given a number and its base, convert it to decimal. The base of number can be anything such that
all digits can be represented using 0 to 9 and A to Z. The value of A is 10, the value of B is 11
and so on. Write a function to convert the number to decimal.
Examples:
Input number is given as string and output is an integer.

Input: str = "1100", base = 2


Output: 12

Input: str = "11A", base = 16


Output: 282

Input: str = "123", base = 8


Output: 83
We strongly recommend you to minimize your browser and try this yourself first.
We can always use the below formula to convert from any base to decimal.
"str" is input number as a string
"base" is the base of the input number.

Decimal Equivalent is,


1*str[len-1] + base*str[len-2] + (base)2*str[len-3] + ...
Below is implementation of above formula.

// C program to convert a number from any base


// to decimal
#include <stdio.h>
#include <string.h>

// To return value of a char. For example, 2 is


// returned for '2'. 10 is returned for 'A', 11
// for 'B'
int val(char c)
{
if (c >= '0' && c <= '9')
return (int)c - '0';
else
return (int)c - 'A' + 10;
}

// Function to convert a number from given base 'b'


// to decimal
int toDeci(char *str, int base)
{
int len = strlen(str);
int power = 1; // Initialize power of base
int num = 0; // Initialize result
int i;

// Decimal equivalent is str[len-1]*1 +


// str[len-2]*base + str[len-3]*(base^2) + ...
for (i = len - 1; i >= 0; i--)
{
// A digit in input number must be
// less than number's base
if (val(str[i]) >= base)
{
printf("Invalid Number");
return -1;
}

num += val(str[i]) * power;


power = power * base;
}

return num;
}

// Driver code
int main()
{
char str[] = "11A";
int base = 16;
printf("Decimal equivalent of %s in base %d is "
" %d\n", str, base, toDeci(str, base));
return 0;
}

Output
Decimal equivalent of 11A in base 16 is 282
Time Complexity: O(N) n represents the length of string
Auxiliary Space: O(1)

How to do reverse?
Let the given input decimal number be “inputNum” and target base be “base”. We repeatedly
divide inputNum by base and store the remainder. We finally reverse the obtained string. Below
is C implementation.

// C Program to convert decimal to any given base


#include <stdio.h>
#include <string.h>

// To return char for a value. For example '2'


// is returned for 2. 'A' is returned for 10. 'B'
// for 11
char reVal(int num)
{
if (num >= 0 && num <= 9)
return (char)(num + '0');
else
return (char)(num - 10 + 'A');
}

// Utility function to reverse a string


void strev(char *str)
{
int len = strlen(str);
int i;
for (i = 0; i < len/2; i++)
{
char temp = str[i];
str[i] = str[len-i-1];
str[len-i-1] = temp;
}
}

// Function to convert a given decimal number


// to a base 'base' and
char* fromDeci(char res[], int base, int inputNum)
{
int index = 0; // Initialize index of result

// Convert input number is given base by repeatedly


// dividing it by base and taking remainder
while (inputNum > 0)
{
res[index++] = reVal(inputNum % base);
inputNum /= base;
}
res[index] = '\0';

// Reverse the result


strev(res);

return res;
}

// Driver program
int main()
{
int inputNum = 282, base = 16;
char res[100];
printf("Equivalent of %d in base %d is "
" %s\n", inputNum, base, fromDeci(res, base, inputNum));
return 0;
}

Output
Equivalent of 282 in base 16 is 11A

C Program for Number System Conversion


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void strrev(char*);
// Function to convert decimal to binary and return as a
// string
char* decimalToBinary(int decimal)
{
// Allocate space for a 32-bit binary string + '\0'
char* binary = (char*)malloc(33);
int i = 0;
// converting to binary
while (decimal) {
binary[i++] = '0' + (decimal & 1);
decimal >>= 1;
}
binary[i] = '\0';
strrev(binary);
return binary;
}
// Function to convert binary to decimal and return as an
// integer
int binaryToDecimal(char binary[])
{
int decimal = 0;
int length = strlen(binary);
for (int i = 0; i < length; i++) {
decimal = decimal * 2 + (binary[i] - '0');
}
return decimal;
}
// Function to convert decimal to octal and return as a
// string
char* decimalToOctal(int decimal)
{
// Allocate space for an octal string
char* octal = (char*)malloc(12);
if (octal == NULL) {
printf("Memory allocation failed.\n");
exit(1);
}
// Convert decimal to octal
sprintf(octal, "%o", decimal);
return octal;
}
// Function to convert octal to decimal and return as an
// integer
int octalToDecimal(char octal[])
{
int decimal = 0;
int length = strlen(octal);
for (int i = 0; i < length; i++) {
decimal = decimal * 8 + (octal[i] - '0');
}
return decimal;
}
// Function to convert hexadecimal to binary and return as a
// string
char* hexadecimalToBinary(char hex[])
{
// converting hexadecimal string to integer
unsigned int hexNum;
sscanf(hex, "%x", &hexNum);
// string to store binary number
char binary[33] = "";
// converting to hexadecimal
int i = 0;
while (hexNum) {
binary[i++] = '0' + hexNum % 2;
hexNum /= 2;
}
binary[i] = '\0';
strrev(binary);
return strdup(binary);
}
// Function to convert binary to hexadecimal and return as a
// string
char* binaryToHexadecimal(char binary[])
{
// Pad the binary string with leading zeros to ensure
// it's a multiple of 4
int length = strlen(binary);
int padding = (4 - (length % 4)) % 4;
char paddedBinary[129];
memset(paddedBinary, '0', padding);
strcpy(paddedBinary + padding, binary);
// Define a mapping of binary strings to their
// hexadecimal representations
char* binaryHexDigits[]
= { "0000", "0001", "0010", "0011", "0100", "0101",
"0110", "0111", "1000", "1001", "1010", "1011",
"1100", "1101", "1110", "1111" };
char hexadecimal[33] = ""; // Allocate space for an
// 8-digit hexadecimal string
// Iterate through groups of 4 binary digits and convert
// to hexadecimal
for (int i = 0; i < length + padding; i += 4) {
char group[5];
strncpy(group, paddedBinary + i, 4);
group[4] = '\0';
// Find the corresponding hexadecimal digit
for (int j = 0; j < 16; j++) {
if (strcmp(group, binaryHexDigits[j]) == 0) {
// Append the corresponding hexadecimal
// digit
char hexDigit[2];
sprintf(hexDigit, "%X", j);
strcat(hexadecimal, hexDigit);
break;
} }
}
return strdup(hexadecimal);
}

// driver code
int main()
{
int choice;
while (1) {
printf("\nMenu:\n");
printf("1. Decimal to Binary\n");
printf("2. Binary to Decimal\n");
printf("3. Decimal to Octal\n");
printf("4. Octal to Decimal\n");
printf("5. Hexadecimal to Binary\n");
printf("6. Binary to Hexadecimal\n");
printf("7. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
if (choice == 7) {
printf("Goodbye!\n");
break;
}
char input[100]; // Buffer for user input
switch (choice) {
case 1:
printf("Enter a decimal number: ");
scanf("%d", &choice);
char* result = decimalToBinary(choice);
printf("Decimal to Binary: %s\n", result);
free(result);
break;
case 2:
printf("Enter a binary number: ");
scanf("%s", input);
int binaryResult = binaryToDecimal(input);
printf("Binary to Decimal: %d\n", binaryResult);
break;
case 3:
printf("Enter a decimal number: ");
scanf("%d", &choice);
result = decimalToOctal(choice);
printf("Decimal to Octal: %s\n", result);
free(result);
break;
case 4:
printf("Enter an octal number: ");
scanf("%s", input);
int octalResult = octalToDecimal(input);
printf("Octal to Decimal: %d\n", octalResult);
break;

case 5:
printf("Enter a hexadecimal number: ");
scanf("%s", input);
result = hexadecimalToBinary(input);
printf("Hexadecimal to Binary: %s\n", result);
free(result);
break;
case 6:
printf("Enter a binary number: ");
scanf("%s", input);
result = binaryToHexadecimal(input);
printf("Binary to Hexadecimal: %s\n", result);
free(result);
break;
default:
printf("Invalid choice. Please enter a valid "
"option.\n");
}
}
return 0;
}
// reversing string
void strrev(char* str)
{
int i = 0;
int j = strlen(str) - 1;
while (i < j) {
char c = str[i];
str[i] = str[j];
str[j] = c;
i++;
j--;
}
}
Output
1. Decimal to Binary
Menu:
1. Decimal to Binary
2. Binary to Decimal
3. Decimal to Octal
4. Octal to Decimal
5. Hexadecimal to Binary
6. Binary to Hexadecimal
7. Exit
Enter your choice: 1
Enter a decimal number: 128
Decimal to Binary: 10000000
2. Binary to Decimal
Menu:
1. Decimal to Binary
2. Binary to Decimal
3. Decimal to Octal
4. Octal to Decimal
5. Hexadecimal to Binary
6. Binary to Hexadecimal
7. Exit
Enter your choice: 2
Enter a binary number: 10000000
Binary to Decimal: 128
3. Decimal to Octal
Menu:
1. Decimal to Binary
2. Binary to Decimal
3. Decimal to Octal
4. Octal to Decimal
5. Hexadecimal to Binary
6. Binary to Hexadecimal
7. Exit
Enter your choice: 3
Enter a decimal number: 100
Decimal to Octal: 144
4. Octal to Decimal
Menu:
1. Decimal to Binary
2. Binary to Decimal
3. Decimal to Octal
4. Octal to Decimal
5. Hexadecimal to Binary
6. Binary to Hexadecimal
7. Exit
Enter your choice: 4
Enter an octal number: 144
Octal to Decimal: 100
5. Hexadecimal to Binary
Menu:
1. Decimal to Binary
2. Binary to Decimal
3. Decimal to Octal
4. Octal to Decimal
5. Hexadecimal to Binary
6. Binary to Hexadecimal
7. Exit
Enter your choice: 5
Enter a hexadecimal number: a10
Hexadecimal to Binary: 101000010000
6. Binary to Hexadecimal
Menu:
1. Decimal to Binary
2. Binary to Decimal
3. Decimal to Octal
4. Octal to Decimal
5. Hexadecimal to Binary
6. Binary to Hexadecimal
7. Exit
Enter your choice: 6
Enter a binary number: 101000010000
Binary to Hexadecimal: A10
C program to read an array of 8 integer values and find sum, average, greatest number
and lowest number.

Solution:
#include <stdio.h>
int main()
{
int a[8],i,s=0,g,l;
float avg;
printf("Enter 8 Numbers:\n");
for(i=0;i<8;i++)
{
scanf("%d",&a[i]);
s=s+a[i];
avg=s/8.0;
}
printf("Sum of Array Elements = %d\n",s);
printf("Average of Elements = %.2f\n",avg);
g=a[0];
for(i=0;i<8;i++)
if(a[i]>g)
g=a[i];
printf("Greatest Element = %d\n",g);
l=a[0];
for(i=0;i<8;i++)
if(a[i]<l)
l=a[i];
printf("Lowest Element = %d",l);
return 0;
}

Output:

#include<stdio.h>
int main()
{
int a[2500], n, i, t, j, max=0, c=0, mode=0;
float s=0, mean, median;
printf(“Enter how many data you want to input: “);
scanf(“%d”,&n);
printf(“Enter %d Data:\n”, n);
for(i=0; i<n; i++)
{
scanf(“%d”,&a[i]);
s+=a[i];
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(a[i]<a[j])
{
t=a[i];
a[i]=a[j];
a[j]=t;
}
}
}
// to find mean
mean = s/(float)n;
printf(“mean or average is: %.1f\n”,mean);
//to find median
if(n%2==0)
median=( (a[(n-1)/2] + a[(n-1)/2+1] ) / 2.0);
else
median=( (a[(n-1)/2]) / 2.0);
printf(“median is: %.1f\n”, median);
//to find mode
for(i=0; i<n; i++)
{
t=a[i];
c=0;
for(j=0; j<n; j++) { if(t==a[j]) c++; if(c>max)
{
max=c;
mode=t;
}
}
}
printf(“mode is %d”,mode);
return 0;
}
Output:

You might also like