In: Computer Science
write a c program that asks the user to enter any two intger numbers and each number consist of four digits. your program should check whether the numbers are four digits or not and in case they are not a four digit number the program should print a message and exit otherwise it should do the following print a mnew as follows
select what you want to do with the number 1-3:
1-print grreatest common divisor (gcd)of the two numbers
2-print sum of odd digits of each number
3-print relation of odd sum of digits larger/smaller/equal
Code:-
#include<stdio.h>
#include<stdlib.h>
//Function to calculate gcd of two numbers
int gcd_of_numbers(int num1, int num2)
{
if (num2 == 0)
return num1;
return gcd_of_numbers(num2, num1 % num2);
}
//function to calculate odd digits sum of number
int odd_digit(int num){
int odd_sum=0;
int digit;
int remainder;
while(num>0){
digit=num%10;//stores the each
digit of number
num=num/10;
remainder=digit%2;//To know whether
it is even or odd digit
if(remainder==1)
odd_sum+=digit;
}
return odd_sum;
}
int main(){
int num1,num2;//variables for user input
printf("Enter two integers that contain four
digits\n");
scanf("%d%d",&num1,&num2);
if((num1>=1000&&num1<=9999) &&
(num2>=1000 && num2<=9999)){
printf("Select what you want to do
with numbers1-3\n");
printf("1-print greatest common
divisors of two numbers\n");
printf("2-print sum of digits of
each number\n");
printf("3-print relation of odd sum
of digits larger/smaller/equal\n");
int choice;//variable for choosing
option
int odd_digit_sum_number1;
int odd_digit_sum_number2;
scanf("%d",&choice);
switch(choice){
case 1:
printf("gcd of given two numbers is
:%d\n",gcd_of_numbers(num1,num2));
break;
case
2:printf("Sum of odd digits of first number:
%d\n",odd_digit(num1));
printf("Sum of odd digits of
second number: %d\n",odd_digit(num2));
break;
case 3:
odd_digit_sum_number1=odd_digit(num1);//Call the function and store
result in this variable
odd_digit_sum_number2=odd_digit(num2);
if(odd_digit_sum_number1>odd_digit_sum_number2)
printf("Number 1 odd digits sum= %d is larger than Number 2 odd
digits sum=
%d\n",odd_digit_sum_number1,odd_digit_sum_number2);
else
if(odd_digit_sum_number1<odd_digit_sum_number2)
printf("Number 1 odd digits sum= %d is smaller than Number 2 odd
digits sum=
%d\n",odd_digit_sum_number1,odd_digit_sum_number2);
else
printf("Number 1 odd digits sum= %d is equal to Number 2 odd digits
sum= %d\n",odd_digit_sum_number1,odd_digit_sum_number2);
break;
default:
printf("Invalid
Option");
}
}
else{
printf("The given user input does
not contain four digits\n");
exit(0);
}
return 0;
}
Output:-
Code Image:-