Write a function that returns the sum of all the odd digits of a given positive number
Example:
Input: num = 12345 Output: Sum of odd digits is 9
Approach
C
#include <stdio.h>int sumOfOdd(int num){int sum = 0;while (num > 0){int temp = num % 10;if (temp % 2 == 1)sum += temp;num = num / 10;}return sum;}int main(){int num;printf("Enter a number : ");scanf("%d", &num);int sum = sumOfOdd(num);printf("Sum of odd digits is %d", sum);return 0;}
Java
import java.util.Scanner;public class Main{public static void main(String[] args) {System.out.println("enter the number");Scanner sc = new Scanner(System.in);int sum =0;int num = sc.nextInt();while(num>0){int digit = num%10;if(digit%2!=0){sum+=digit;}num=num/10;}System.out.println("sum of odd digit is "+sum);}}
No comments:
Post a Comment