Guest User

Untitled

a guest
Aug 17th, 2018
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.65 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <cs50.h>
  3.  
  4. int main(void)
  5. {
  6. printf("This program is designed to check whether your credit card number is valid or not.\n");
  7. long long card_number = get_long_long("Please enter your credit card number: ");
  8.  
  9. int valid = 0; // Initialize the condition under which the loop will run.
  10.  
  11. while(valid == 0) // Initialize the validation loop. Loop will cease once a valid credit card number is entered.
  12. if(card_number > 0) // Validate the number as a positive integer.
  13. {
  14. // Now validate the checksum.
  15. int digits = 0;
  16. int checksum = 0;
  17. long long x = card_number;
  18. while(x > 0) // If our working number is greater than 0, we can continue calculating the checksum.
  19. {
  20. digits++; // Adds the last digit to the checksum. (This will target every other digit).
  21. checksum = checksum + (x % 10);
  22. x = x / 10; // Removes the last digit to continue processing.
  23. if(x > 0)
  24. {
  25. digits++; // Adds the last digit multiplied by 2 (this targets every other digit) to the checksum.
  26. checksum = checksum + (2 *(x % 10));
  27. x = x / 10;
  28. }
  29. }
  30. if(checksum % 10 == 0) // If the checksum is evenly divisible by 10, it is valid.
  31. {
  32. printf("Checksum is valid. Now checking which type of card you have.\n");
  33. // Now, validate the type. If 15 digits and starts with 34 or 37, it's American Express.
  34. if(digits == 15 && (card_number / 10000000000000 == 34 || card_number / 10000000000000 == 37))
  35. {
  36. printf("Your card is a valid AmEx card.\n");
  37. valid = 1;
  38. }
  39. // If it's 16 digits and begins with 51-55, it's Master Card.
  40. else if(digits == 16 && card_number / 100000000000000 >= 51 && card_number / 100000000000000 <= 55)
  41. {
  42. printf("Your card is a valid Master Card card.\n");
  43. valid = 1;
  44. }
  45. // If it's 13 or 16 digits and starts with 4, it's Visa.
  46. else if(digits == 16 && card_number / 1000000000000000 == 4)
  47. {
  48. printf("Your card is a valid Visa card.\n");
  49. valid = 1;
  50. }
  51. else
  52. {
  53. // If the number passes the checksum test but isn't a recognized AmEx, Visa, or Master Card, this will handle it.
  54. card_number = get_long_long("Valid checksum, but not a recognized company. Please retry: ");
  55. }
  56. }
  57. else
  58. {
  59. card_number = get_long_long("Invalid checksum. Please retry: ");
  60. }
  61. }
  62. }
Add Comment
Please, Sign In to add comment