Thread: A C program to count the number of "sevens" in any given number.

  1. #1
    Registered User
    Join Date
    Apr 2013
    Posts
    2

    A C program to count the number of "sevens" in any given number.

    Here is what I have done so far:

    Code:
    #include<stdio.h>
    #include<math.h>
    
    int main()
    {
        int x,n,i,f;
        printf("Please enter an integer: \n");
        scanf("%d",&x);
        n=10;
        f=x;
        i=0;
        while((f/n)>0)
        {
            if((f%10)==7)
            {
                i+=1;
            }
            f=f/10;
        }
        printf("The number %d has %d sevens.",x,i);
    
    }
    The only problem with this code is that it does not count the first "seven" in the integer, for example:
    If I input "77777", it will say that it has 4 sevens. I know here the problem is, I just don't know how to overcome it. Any ideas?
    Last edited by Birosso; 04-19-2013 at 12:51 PM.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    37,484
    So start with just inputting 7, then step through the code to see what happens.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Aug 2005
    Location
    Austria
    Posts
    1,990
    you could try
    Code:
     while(f>0)
    Kurt

  4. #4
    Registered User
    Join Date
    Apr 2013
    Posts
    2
    Can't believe I was so stupid. Thank you,Zuk.

  5. #5
    Registered User
    Join Date
    Apr 2013
    Posts
    1,646
    If you change that to if (f>0), then you don't need n or n=10 anymore.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problem with coding "Random Number Guessing Game" (Beginner)
    By DecoratorFawn82 in forum C++ Programming
    Replies: 13
    Last Post: 03-02-2013, 01:38 AM
  2. Replies: 1
    Last Post: 02-27-2012, 06:38 AM
  3. Replies: 31
    Last Post: 11-25-2009, 01:10 PM
  4. Replies: 7
    Last Post: 07-03-2007, 01:49 PM
  5. Count the number of letter "a" on a sentence
    By imbecile in C in forum C Programming
    Replies: 6
    Last Post: 07-27-2003, 02:32 PM