I'm working on the credit problem in pset1, and this is only part of what should be done. All I'm trying to do here is to multiply every other number (from the cc number entered by the user) by two, starting with the second-to-last digit, and add the digits of the products of those numbers, and save the result in a variable called "sum". For some reason, every time i run the code, i get a different "sum" number. Does anyone know why this is happening? Thank you! Here's the code:
#include <stdio.h>
#include <cs50.h>
int main (void)
{
long long cc_number;
do
{
cc_number = get_long_long ("Please enter a credit card number: ");
}
while (cc_number <= 0);
//the following long_long variable is for the sum of the digits that start with the last digit, skip one, then third digit, and
//so on, so it is the sum of the digits that are in the "odd number positions". eg: positions 1,3,5,..etc., with the last digit
//position being position 1.
//long long previous_sum = 0;
int count = 0;
//long long digit;
while (cc_number > 0)
{
cc_number /= 10;
count ++;
cc_number--;
}
//int indv_numbers [count];
int indv_digit [16];
while (cc_number > 0)
{
indv_digit [count] = (cc_number % 10);
cc_number /= 10;
count ++;
}
//the following int variable: int indv_digit_addition, was made to enable adding the digits of the products of the numbers starting from the second-to-last
// digit, skipping one, then adding the next, then skipping one, etc.
int sum = 0;
for (count = 1; count <=14; count+=2)
{
int indv_digit_times_two = (indv_digit [count] * 2);
if (indv_digit_times_two != 0)
{
int remainder = indv_digit_times_two % 10;
sum = sum + remainder;
indv_digit_times_two = indv_digit_times_two / 10;
}
else
{
int remainder = indv_digit_times_two;
sum = sum + remainder;
}
}
printf ("%d", sum);
}