c - Failed summing/adding every other component inside an integer array -


i continue quest store input credit card number , validate it.

1) user types hipothetic credit card number, 1234567898769999 (stored string). 2) convert string array of integers int digits[]. 3) multiply digitis in positions 1, 3, 5 ... last odd position 2, instance 2*2, 2*4, 2*6, 2*8, 2*8, 2*6, 2*9, 2*9. 4) store them in same array , position [4,8,12,16,16, 12, 18,18]. 5) sum digits in positions 0, 2, 4 ... last position.

trying run code below abnormal values appearing:

#include <cs50.h> #include <stdio.h> #include <string.h>  int main (void) {     string cc_string;      printf("please enter credit card number:\n");      //capture credit card number     cc_string = getstring();      // array of integers credit card digits int cc_digits[15];     int sum_evens, sum_odds = 0;      (int = 0; < 16; i++)     {            cc_digits[i] = cc_string[i] - '0';          //sum digits in positions (0 ... 14)         if (i % 2 == 0)         {             sum_evens = sum_evens + cc_digits[i];              //checking values             printf("cc_digits[%d] = %d; sum_evens = %d\n", i, cc_digits[i], sum_evens);         }          else if (i % 2 == 1)         {             //multiplies values in each position 2 , stores in same position             cc_digits[i] = 2 * cc_digits[i];             sum_odds = sum_odds + cc_digits[i];              //checking values             printf("cc_digits[%d] = %d; sum_odds = %d\n", i, cc_digits[i], sum_odds);         }     } } 

will have clue going on here? has been 3 days since have tried solve this. in advance help.

abnormal values appearing

int sum_evens, sum_odds = 0; 

here have not initialized value of sum_evens, using further in program way in if block of for loop:

sum_evens = sum_evens + cc_digits[i]; 

so, results in undefined behaviour , abnormal values appear. avoid this, try initializing sum_evens.

int sum_evens = 0, sum_odds = 0; 

Comments

Popular posts from this blog

account - Script error login visual studio DefaultLogin_PCore.js -

xcode - CocoaPod Storyboard error: -