IT, Programming, & Web Development › Forums › CS50’s Introduction to Computer Science by Harvard University on Edx › Week 1: [C] – Data Types, Operators, Conditional Statements, Loops, and Command Line › Counting the number of digits
- This topic is empty.
-
AuthorPosts
-
August 28, 2022 at 11:28 am #514
[dm_code_snippet background=”yes” background-mobile=”no” slim=”yes” line-numbers=”yes” bg-color=”#abb8c3″ theme=”dark” language=”clike” wrapped=”yes” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]
int countdigit (long y) { long x = y; int c = 0; do { x = x/10; c++; } while (x%10 > 0); return c; }
[/dm_code_snippet]
For numbers such as 10000, getting 1 as count of digits. But working fine for other numbers such as 7896541236987. Clearly, this strategy fails when modulus 0. Any clue how to modify so as to count all entered numbers?
Here is the full code:
[dm_code_snippet background=”yes” background-mobile=”no” slim=”yes” line-numbers=”yes” bg-color=”#abb8c3″ theme=”dark” language=”clike” wrapped=”yes” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]
#include #include long enterccno (void);//long type as 14-digit credit card will not fit into the memory as int type int countdigit (long y); int checkifAmex (long y); int main(void) { long y = enterccno(); printf("credit card no. entered is %ld",y); long cc = countdigit(y); printf("entered credit card has this number of digit %ld",cc); if (cc == 15) { int z = checkifAmex(cc); if (z == 1) { printf("This is Amex"); return 0; } } //if (cc == 16) //{ //checkifMastercard //} //if (cc == 13 or cc == 16) //{ //checkifVisa //} else { return 0; } } long enterccno (void) //It will take void as argument as the function will not initially take any particular long value as input to begin with. { long x = get_long("enter creditcardno");//get_long function by cs50.h leveraged to accept input of creditcard no. from user. return x;//stored x value or entered creditcardno transferred inside the main function when entercccno function called. } int countdigit (long y) { long x = y; int c = 0; do { x = x/10; c++; } while (x%10 > 0); return c; } int checkifAmex (long y) { long x = y; if (x/10000000000000 == 34) { return 1; } else { return 0; } }
[/dm_code_snippet]
Reply
This works:
[dm_code_snippet background=”yes” background-mobile=”no” slim=”yes” line-numbers=”yes” bg-color=”#abb8c3″ theme=”dark” language=”clike” wrapped=”yes” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]
int countdigit (long y) { long x = y; int c = 0; do { x = x/10; c++; } while (x > 0); return c; }
[/dm_code_snippet]
[learn_press_profile]
-
AuthorPosts
- You must be logged in to reply to this topic.