Counting by 2’s

Problem

Write a C++ program to count the number of 2’s between 0 and (n) where (n) is a positive integer.

Solution

We need two loops, one goes from 0 to n and the other one examines the number digit by digit. One way to get the decimal digits of a number is to shift the number to the right. Shifting is nothing but a division by 10. The current digit can be extracted by taking the remainder of the division operation. Here is an example:

This is not an efficient algorithm. In the next article we will solve it in a better way.

Code

Here is the code in C++

Tags:

Add a Comment

Your email address will not be published. Required fields are marked *