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.
/*
* C++ Program to Count the Number of ones in the given Number
*/
#include<iostream>
using namespace std;
int main()
{
int num, temp, count = 0;
cout << "Enter the number : ";
cin >> num;
temp = num;
while (temp != 0)
{
if (temp % 10 == 1)
count++;
temp = temp / 10;
}
cout << "The number of ones in " << num
<< " is " << count << endl;
}
$ 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.
If you find any mistake above, kindly email to [email protected]Related Posts:
- Check C++ Books
- Check Programming Books
- Practice Programming MCQs
- Apply for Computer Science Internship
- Practice Computer Science MCQs