Home > Enterprise >  how can I use less variables in my program?
how can I use less variables in my program?

Time:06-17

I had to make a program that have an array of numbers, and then I need to make a function that get the arr[0] and the length of the array, and then it will print all the numbers without the duplicate ones.

I made this program and it worked good but I feel like I used too much variables for this program. (I started to learned in the last few weeks so its not looks very good)

#include <stdio.h>

#define N 10

void print_set(int *arr, int n) {
    int i = 1;
    int duplicate_num, check_num, count;
  
    printf(" %d", *arr); //printing the first number (arr[0]).
    
    //starting to check the other number. if they new I'll print them. (start from arr[1]).
    arr  ;
    while (i < n) {
        if (*arr != duplicate_num) {
            printf(" %d", *arr);
            check_num = *arr;
            // becouse I found new number, I change it no be equal to the first duplicate_num. (if there are more like him, I change them too).
            while (i < n) {
                if (*arr == check_num) {
                    *arr = duplicate_num;
                }
                arr  ;
                i  ;
                count  ;
            }
            i = i - count;
            arr = arr - count;
            count = 0;
        }
        arr  ;
        i  ;
    }
}



int main() {
    int arr[N] = {4, 6, 9, 8, 6, 9, 6, 1, 6, 6};
    print_set(&arr[0], N);
    return 0;
}

output for this program: 4 6 9 8 1

I'll be happy to see good method to make this program less messy.

CodePudding user response:

For starters the function has undefined behavior. The user can pass 0 as the second argument. It means that the array is empty and has no elements. In this case the expression *arr is undefined.

The second problem is using the uninitialized variable duplicate_num in this if statement

if (*arr != duplicate_num) {

and the uninitialized variable count

count  ;

Another problem is that the function changes the array

if (*arr == check_num) {
    *arr = duplicate_num;
}

If you need only to output unique values in an array then the source array shall not be changed.

The function can be defined for example the following way

void print_set( const int *a, size_t n ) 
{
    for ( size_t i = 0; i < n; i   )
    {
        size_t j = 0;
        while ( j != i && a[i] != a[j] )   j;

        if ( j == i ) printf( "%d ", a[i] );
    }

    putchar( '\n' );
}
  • Related