C++ Program to Count the Number of Ones in the Given Number

«
»
This C++ Program which counts the number of ones in the given number. The program uses a while loop to go through each and every digit of the given number and increments the variable count if the current digit is 1.

Here is source code of the C++ program which counts the number of ones in the given number. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C++ Program to Count the Number of ones in the given Number
  3.  */
  4.  
  5. #include<iostream>
  6. using namespace std;
  7.  
  8. int main()
  9. {
  10.     int num, temp, count = 0;
  11.  
  12.     cout << "Enter the number : ";
  13.     cin >> num;
  14.     temp = num;
  15.     while (temp != 0)
  16.     {
  17.         if (temp % 10 == 1)
  18.             count++;
  19.         temp = temp / 10;
  20.     }
  21.     cout << "The number of ones in " << num
  22.          << " is " << count << endl;
  23. }

$ g++ main.cpp
$ ./a.out
Enter the number : 101
The number of ones in 101 is 2

Sanfoundry Global Education & Learning Series – 1000 C++ Programs.

advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & technical discussions at Telegram SanfoundryClasses.