disclaimer this is not my code and this code is from Remove Duplicate Elements from an Array in C - Javatpoint
What I want to know is in the Example 2 coding part. (I edit code a bit for me or you can see the code clearly.)
/* program to delete the duplicate elements from sorted array in C. */
#include <stdio.h>
int duplicate_element ( int arr[], int num)
{
// check num is equal to 0 and num == 1
if (num == 0 || num == 1)
{
return num;
}
// create temp array to store same number
int temp [num];
// declare variable
int i, j = 0;
// use for loop to check duplicate element
for (i = 0; i < num - 1; i++)
{
// check the element of i is not equal to (i + 1) next element
if (arr [i] != arr[i + 1])
{
temp[j++] = arr[i];
}
}
temp[j++] = arr[ num - 1];
// check the original array's elements with temporary array's elements
for (i = 0; i < j; i++)
{
arr[i] = temp[i];
}
return j;
}
int main ()
{
int num;
printf (" Define the no. of elements of the array: ");
scanf (" %d", &num);
int arr[num], i;
printf (" Enter the elements: ");
// use loop to read elements one by one
for ( i = 0; i < num; i++)
{
scanf (" %d", &arr[i]);
}
printf (" \n Elements before removing duplicates: ");
for ( i = 0; i < num; i++)
{
printf (" %d", arr[i]);
}
num = duplicate_element (arr, num);
// print array after removing duplicates elements
printf (" \n Display array's elements after removing duplicates: ");
for ( i = 0; i < num; i++)
{
printf (" %d", arr[i]);
}
return 0;
}
Here's the question, what does all j++ in function duplicate_element do? (If possible I would like to know what the code is doing since line // use for loop to check duplicate element until before return too. This part I'm just curious if I know it correctly or not.)
This is my understanding (j is the final size of arr[]). In the first question, when executed
j right now is 0
temp[j++]
is it plus the value of j by 1 first then assign value arr[i] to temp[1]. (Does this right?)
The second question, in the first for loop checks when the value in arr[i] is not equal to the value in arr[i + 1] then assign value in temp[j++] with value in arr[i] until for loop is over then assign temp[j++] with arr[num - 1]
(j++ right now is dependent on the if condition for example when all value is not equal to the value of j++ == value of num - 1 and num - 1 is equal to the last value of arr)
and in the last for loop, it assigns every value in Array arr with Array temp. (Does this right?)