Dr. A.P.J. Abdul Kalam Technical University, Lucknow
KCS151 / KCS251 Programming for Problem Solving - Using C Language
Lab Exercises
15. Write a function that returns the sum of all the odd digits of a given positive no entered through the keyboard.
/*
File: Prgrm15.c
Author: Aditya Saini
Date: Jan 17, 2021
Description: Function that returns the sum of all the odd digits of a given positive no entered
through keyboard.
through keyboard.
*/
#include <stdio.h>
#include <math.h>
int my_fun (int);
int main (void)
{
int num;
int sum;
//Input number
printf ("Input number: ");
scanf ("%d", &num);
//Function call
sum = my_fun (num);
//Print result
printf ("Sum of odd digits: %d", sum);
};
int my_fun (int num)
{
int sum_1, sum_2;
int num_of_digits;
//Calculate sum
num_of_digits = 0;
sum_1 = sum_2 = 0;
while (num != 0)
{
if (num_of_digits % 2 == 0)
sum_1 = sum_1 + num % 10;
else
sum_2 = sum_2 + num % 10;
num_of_digits++;
num = num / 10;
}
//Return sum
if (num_of_digits %2 == 0)
return sum_2;
else
return sum_1;
};
Output
Input number: 12345
Sum of odd digits: 9
No comments:
Post a Comment
Please do not post spam links.