Header Ads Widget

Write a function that return sum of all the odd digits of a given positive no entered through keyboard in c++

 Write a function that return sum of all the odd digits of a given positive no entered through keyboard in c++

Given a number , write a function that return sum of all the odd digits of a given positive no entered through keyboard in c++ . 

Sample input

4567

Sample Output:

Sum of odd digits of 4567 is: 12

 Write a function that return sum of all the odd digits of a given positive no entered through keyboard in c++

The objective of the code is to write a function that return sum of all the odd digits of a given positive number entered by the user .

Algorithm:-

  1. Define a function called sumOddDigits which takes a positive integer as its argument.
  2. Initialize a variable called sum to zero.
  3. While the given positive integer is greater than zero: a. Extract the last digit of the integer using the modulus operator (%). b. Check if the extracted digit is odd or not using the modulus operator (%). c. If the digit is odd, add it to the sum variable. d. Divide the integer by 10 to remove the last digit.
  4. Return the final sum variable.

Code(C++):-

#include <iostream>
using namespace std;

int sumOddDigits(int n) {
int sum = 0;
while (n > 0) {
int digit = n % 10;
if (digit % 2 != 0) {
sum += digit;
}
n /= 10;
}
return sum;
}

int main() {
int num;
cout << "Enter a positive integer: ";
cin >> num;
cout << "Sum of odd digits of " << num << " is: " << sumOddDigits(num) << endl;
return 0;
}

Output:-

Enter a positive integer: 4567
Sum of odd digits of 4567 is: 12


Recommended Post :-

HCL Coding Questions:-

Capgemini Coding Questions:-

Companies interview:-

Full C course:-    

Key points:-

Cracking the coding interview:-

 Array and string:-

Tree and graph:-

Hackerearth Problems:-

Hackerrank Problems:-

Data structure:-

 MCQs:-