Question #43047

2. Compute the sum of single digit numbers obtained from step 1 above:

Sum of even single-digits = 4 + 4 + 8 + 2 + 3 + 1 + 7 + 8 = 37

3. Compute the sum of every odd digit from right to left:

Sum of odd digits = 6 + 6 + 0 + 8 + 0 + 7 + 8 + 3 = 38

4. Compute the sum of the results from step 2 and step 3:

Total sum = 37 + 38 = 75

5. If the total sum from step 4 is divisible by 10, the card number is valid. Otherwise

it’s not valid.

Is 75 divisible by 10 (without remainder)? No, the card number in this

example is Invalid.

Sum of even single-digits = 4 + 4 + 8 + 2 + 3 + 1 + 7 + 8 = 37

3. Compute the sum of every odd digit from right to left:

Sum of odd digits = 6 + 6 + 0 + 8 + 0 + 7 + 8 + 3 = 38

4. Compute the sum of the results from step 2 and step 3:

Total sum = 37 + 38 = 75

5. If the total sum from step 4 is divisible by 10, the card number is valid. Otherwise

it’s not valid.

Is 75 divisible by 10 (without remainder)? No, the card number in this

example is Invalid.

Expert's answer

`#include<iostream>`

#include<string>

**using** **namespace**std**;**

intmain**()** **{**

cout **<<** "Enterthe card number: "**;**

string cardNumber**;**

cin **>>**cardNumber**;**

bool valid **=** **true****;**

int sumOfOdd **=** 0**;**

int sumOfEven **=** 0**;**

// The credit card number muststart with 3, 4, 5 or 6.

**if** **((**cardNumber**[**0**]** **!=** '3'**)** **&&** **(**cardNumber**[**0**]** **!=** '4'**)** **&&** **(**cardNumber**[**0**]** **!=** '5'**)** **&&** **(**cardNumber**[**0**]** **!=** '6'**))** **{**

valid **=** **false****;**

**}**

// The total number of digits ofa credit card number must be between 13 to 16 digits.

**if** **((**cardNumber**.**length**()** **<** 13**)** **||** **(**cardNumber**.**length**()** **>** 16**))** **{**

valid **=** **false****;**

**}**

// Luhn Rule

**for** **(**int i **=** 0**;** i **<**cardNumber**.**length**();** i**++)** **{**

char c **=**cardNumber**[**cardNumber**.**length**()** **-** i **-** 1**];**

intnum **=** c **-** '0'**;**

**if** **((**num**<** 0**)** **||** **(**num**>** 9**))** **{**

valid **=** **false****;**

**}**

**if** **(**i **%** 2 **==** 1**)** **{**

num **=** 2 *****num**;**

**if** **(**num**>** 9**)** **{**

num **=**num **/** 10 **+**num **%** 10**;**

**}**

sumOfEven **=**sumOfEven **+** num**;**

**}**

**else** **{**

sumOfOdd **=**sumOfOdd **+** num**;**

**}**

**}**

int sum **=**sumOfOdd **+** sumOfEven**;**

**if** **(**sum**%** 10 **!=** 0**)** **{**

valid **=** **false****;**

**}**

**if** **(**valid**)** **{**

cout **<<** "Thecard is valid" **<<** endl**;**

**}**

**else** **{**

cout **<<** "Thecard is invalid" **<<** endl**;**

**}**

**return** 0**;**

**}**

Learn more about our help with Assignments: C++

## Comments

## Leave a comment