Dustynana
Dustynana

Reputation: 21

Function doesn't seem to modify array

I'm writing a program that is supposed to take in an input of zeroes and ones and assign them into an array. Then it passes the array to edge function and formats it in the following way.

  1. Assign a 1 to the output bit pattern whenever two consecutive bits (one bit and it’s previous bit) are different
  2. Assign a 0 to the output bit pattern whenever two consecutive bit (one bit and it’s previous bit) are the same
  3. Assign 0 to the first output bit since there is no previous bit for the first bit

The problem is that when the array is passed to the function and printf is called, it simply prints out the original input. I've looked at it from different angles and can't seem to see whats wrong.

#include <stdio.h>

void edge(int n, int a1[], int a2[])
{
    int i = 1;
    a2[0] = 0;
    int last = a1[i-1];
    printf("%d", a2[0]);
    for(i = 1; i < n; i++)
    {
        if(last == a1[i])
        {
                a2[i] = 0;
        }
        else
        {
                a2[i] = 1;
        }
    printf("%1d", a2[i]);
}
}

int main(void)
{
    int i = 0;
    int num;

    int array1[8];
    int array2[8]={0};

    printf("Enter an 8-digit barcode: \n");
    for(i = 0; i < 8; i++)
    {
        scanf("%1d", &num);
        if(num == 1)
        {
                array1[i] = 1;
        }
    }
    printf("Output: ");

    edge(8, array1, array2);

    return 0;
}

Upvotes: 0

Views: 91

Answers (1)

m.raynal
m.raynal

Reputation: 3113

If you don't update last within the loop, you'll always compare the values stored in a2[] with the same value, which does not seem to be your aim. Thus updating last in the loop.

void edge(int n, int a1[], int a2[])
{
    int i;
    a2[0] = 0;
    int last;
    printf("%d", a2[0]);
    for(i = 1; i < n; i++) {
        last = a1[i-1];
        if(last == a1[i])
            a2[i] = 0;
        else 
            a2[i] = 1;
        printf("%1d", a2[i]);
    }
}

Upvotes: 1

Related Questions