Array help.

This is a discussion on Array help. within the C Programming forums, part of the General Programming Boards category; I am new to C and am having trouble with arrays. The code below produces strange output specifically at a[4]. ...

  1. #1
    Registered User
    Join Date
    Jan 2012
    Posts
    2

    Array help.

    I am new to C and am having trouble with arrays. The code below produces strange output specifically at a[4].

    Code:
    #include <stdio.h>
    
    
    int main(void)
    {
     int num;
     int i = 0;
     int factor = 2;
     int a[1024];
    
        printf("Enter a number: ");
        scanf("%d", &num);
    
     while (num != factor) {
     if (num % factor == 0) {
                num = num / factor;
                a[i] = factor;
                i++;
            }
     else {
                factor++;
                i++;
            }
        }
    
        a[i] = factor;
     int j = 0;
    
     while (j <= i) {
            printf("%d\n", a[j]);
            j++;
        }
     return 0;
    }
    Output
    Code:
    Enter a number: 144
    2
    2
    2
    2
    32767
    3
    3
    Thanks in advance for your help.

  2. #2
    - - - - - - - - oogabooga's Avatar
    Join Date
    Jan 2008
    Posts
    2,808
    You shouldn't be incrementing i in your else clause (since you don't store an element there).

  3. #3
    Registered User
    Join Date
    Jan 2012
    Posts
    2
    That did it thanks!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 9
    Last Post: 08-23-2010, 02:31 PM
  2. Replies: 9
    Last Post: 04-07-2010, 10:03 PM
  3. Replies: 1
    Last Post: 10-21-2007, 07:44 AM
  4. Replies: 6
    Last Post: 11-09-2006, 02:28 AM
  5. Replies: 1
    Last Post: 04-25-2006, 12:14 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21