Feb 27, 2009

Count number of 2's in a given range (0 to n)? (ex: range between 0-20, Ans: 3 (i.e [2], 1[2], [2]0))

#include
int main()
{
int n,i,j;
int ctr=0;
scanf("%d",&n);
for(i=0;i<=n;i++)
{
for(j=i;j>0;j=j/10)
{
if((j%10)==2)
ctr++;
}

}

printf("The number of 2's is >> %d ",ctr);

}

No comments:

Post a Comment