0

I am hoping someone can help me with this. I am a complete and utter C newbie.

This is for a school assignment in a class on C (just plain old C, not C# or C++), and the professor is insistent that the only compiler we're allowed to use is Borland 5.5.

The general assignment is to run an algorithm that can check the validity of a credit card number. I've successfully gotten the program to pick up the user-input CC number, then portion that number out into an array. It prints out mostly what I want.

However, when I entered the last function (the one I commented as such) and then compiled, the program just started to hang. I have no idea what could be causing that.

#include <stdio.h>
#include <math.h>
#include <stdlib.h>

  //global variables declared. 
  //in an earlier version, I was going to use multiple functions, but I couldn't make them work
  float array[16]; 
  double num, ten; 
  int i, a, b, x, y, check; 

int main()
{


  ten = 10; 

  //pick up user-input number
  printf("Enter your credit card number\n>");
  scanf("%lf", &num); 

  //generate the array
  for (i = 15; i >= 0; i--)
    {
      array[i] = fmod(num, ten); 
      num /= 10;
      printf("Array is %1.1lf\n", array[i]);
    }


    //double every other number. If the number is greater than ten, test for that, then parse and re-add. 
    //this is where the program starts to hang (I think). 
  {for (i = 2; i <= 16; i + 2)
    {
      array[i] = array[i] * 2;
        if (array[i] >= 10)
          {
            a = (int)array[i] % 10;
            b = (int)array[i] / 10;
            array[i] = a + b; 
           }
    }
    printf("%f", array[i]); 
    }        

    //add the numbers together
    x = array[2] + array[4] + array[6] + array[8] + array[10] + array[12] + array[14] + array[16];
    y = array[1] + array[3] + array[5] + array[7] + array[9] + array[11] + array[13] + array[15];

    check = x + y;  

    //print out a test number to make sure the program is doing everything correctly. 
    //Right now, this isn't happening
    printf("%d", check);

return 0;


}
TeraBat
  • 3
  • 1
  • 4

2 Answers2

0
for (i = 2; i <= 16; i + 2)

should be

for (i = 2; i <= 16; i = i + 2)

or

for (i = 2; i <= 16; i += 2)

As you have it, the value of i is never modified, so the loop never terminates.

happydave
  • 7,127
  • 1
  • 26
  • 25
  • No problem. But note valter's observation too - in your first loop you go from 15 to 0 inclusive, which is probably correct. But in this one you go from 2 to 16 inclusive, which is wrong. You either want to go from 0 to 14, or 1 to 15. 16 is out of the array bounds. – happydave Feb 07 '14 at 04:23
0

You declare your array

array[16] so array[0] .. array[15]

In the second for loop you have

when i = 16 array[16]!

valter

  • Thank you for pointing this out! One thing I will say for C, it is teaching me to be detailed oriented like wow. – TeraBat Feb 07 '14 at 05:59