Home > Backend Development > C++ > body text

C program to calculate the difference between odd number of digits and even number of digits

王林
Release: 2023-09-10 14:05:06
forward
1181 people have browsed it

C program to calculate the difference between odd number of digits and even number of digits

Given a number, find the difference between the odd number of digits and the even number of digits. This means we will count all the even digits and all the odd digits and subtract their sum.

Example

Input:12345
Output:3
Copy after login

Instructions

the odd digits is 2+4=6
the even digits is 1+3+5=9
odd-even=9-6=3
Copy after login

Take each digit in the number and check if the number is even or odd, if it is even then sum it with the even number Add, if not, add with the odd sum and take the difference.

Example

#include <iostream>
using namespace std;
int main() {
   int n, r=0;
   int diff =0;
   int even=0;
   int odd=0;
   n=12345;
   while(n != 0){
      r = n%10;
      if(r % 2 == 0) {
         even+=r;
      } else {
         odd+=r;
      }
      n/=10;
   }
   diff=odd-even;
   printf("%d",diff);
   return 0;
}
Copy after login

The above is the detailed content of C program to calculate the difference between odd number of digits and even number of digits. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template