Monday, October 17, 2022

[FIXED] how can I make a loop print out missing elements in my int array?

Issue

I've been trying to solve an assignment where you:

  1. Enter the size N of an array of ints
  2. Enter the max value M of the ints that you want to populate the array with
  3. Enter N values that are of a value between 1 and M, into a second array.
  4. compare these two and print out the missing numbers...

Like this:

Size of array? 10        // => N = 10
Max value in array? 8    // => M = 8

Please enter 10 values between 1 and 8:
4 1 3 1 7 3 4 4 6 1

Missing values: 2 5 8

for some reason, my for loop just prints out all the numbers between 1 and M instead, no matter what I try... What am I missing??

code:

#include <stdio.h>

int main(void)
{
    int aSize, mValue;



    printf("Size of array? ");
    scanf(" %d", &aSize);
    printf("Max value in array: ");
    scanf(" %d", &mValue);

    int table[aSize];
    int values[mValue];

    for (int i = 0; i < aSize; i++)
    {
        table[i] = i+1;
        if ((i+1) > mValue)
        {
            table[i] = 0;
        }
    }

    printf("Please enter %d values between 1 and %d:\n", aSize, mValue);

    for (int i = 0; i < mValue; i++)
    {
        scanf(" %d", &values[i]);
    }

    for(int i = 0; i < aSize; i++)
    {
        for (int j = 0; j < mValue; j++)
        {
            if(table[i] != values[j] && table[i] != 0)
            {
                printf("%d ", table[i]);
                break;
            }
        }
    }
}

Solution

#include <stdio.h>
   int main()
   {
    int aSize, mValue;
    printf("Size of array? ");
    scanf(" %d", &aSize);
    printf("Max value in array: ");
    scanf(" %d", &mValue);

    int table[aSize];
    int values[aSize]; // not 'mSize' because it is just max value not size of array

    for (int i = 0; i < aSize; i++)
    {
        table[i] = i+1;
        if ((i+1) > mValue)
        {
            table[i] = 0;
        }
    }

    printf("Please enter %d values between 1 and %d:\n", aSize, mValue);

    for (int i = 0; i < aSize; i++)
    {
        scanf(" %d", &values[i]);
    }

    for(int i = 0; i < aSize; i++)
    {
        int flag=0;
        for (int j = 0; j < aSize; j++)
        {
            if(table[i] == 0 || table[i] == values[j]) // numbers in common or zero
            {
                flag=1;
                break;
            }
        }
        if(flag == 0) printf("%d",table[i]); // missing numbers
    }
}


Answered By - Prabhand Reddy
Answer Checked By - Terry (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.