0

I wrote the following code to try to find the first digit of a long number (this is for the CS50x "Credit" exercise), but it's not working. Any tips?

// Conditions and relational operators
#include <stdio.h>
#include <cs50.h>
#include <unistd.h>
#include <math.h>

// Main programme
int main(void)
{
    int sum0 = 0;

    //Prompt for card number
    long cardnumber = get_long("Enter credit card number: ");

    //find first digit as part of validity check
    int getfirstdigit = cardnumber;
    while (getfirstdigit >= 10)
    {
        sum0 = getfirstdigit / 10;
    }
}

The code's compiling, and I'm using printf("first digit: %i\n", sum0); to see what the process is returning. Each time it returns 0. (I thought maybe it might be because I'm converting a long into an int, but when getfirstdigit is a long the programme doesn't work at all (i.e., I have other code after this that's carrying out other processes, which works, ordinarily; but nothing happens at all if getfirstdigit is a long.)

What might be going on? Thanks!

(My reasoning for the code is that the credit card number is divided by 10 over and over again to keep removing the last digit until only the first remains.)

  • Isn't simplier to get a string a then convert some portion of it to integers? – Alex Void Jul 1 at 15:13
0

To find the last digit of a number, we use the modulo operator %. When the module divided by 10 returns its last digit.

Suppose that if n = 1234

the last digit = n% 10 => 4

Finding the first digit of a number is less expensive than the last digit. To find the first digit of a number, we divide the given number by 10 until the number is greater than 10. At the end, we are left with the first digit.

#include <unistd.h>
#include <math.h>

// Main programme
int main(void)
{

    //Prompt for card number
    long cardnumber = get_long("Enter credit card number: ");

    //find first digit as part of validity check
    int getfirstdigit = cardnumber;
    while (getfirstdigit > 10)
    {
        getfirstdigit /= 10;
    }

    printf(" %d\n", getfirstdigit);
}
| improve this answer | |
  • Thank you. I'm not sure why, but I guess it's the sum0 part that was the main problem. –  kittensyzygy Jul 2 at 12:53
  • The real problem is in the variable "getfirstdigit", if you look closely you will see that it never changes so that you enter an infinite loop (I don't know why but I love that word) – MARS Jul 2 at 13:54

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .