scanning and saving input into an array. Then printing the input with certain stipulations

0

What I am supposed to do is to scan 20 integers from the user, and save the integers into an array, then print the input. If an integer is repeated, print the first instance.

So, when I run the code in Cpp I get an error code, and I have no clue what the error means. The error code is "0x80070002" and "Unable to open file" with the description of file location. What do I miss?

#include <iostream>
#include "stdafx.h"
#include <stdio.h>

int main()
{
    const int SIZE = 20;
    int input[SIZE];

    printf("Please enter up to 20 positive numbers.");

    //saveVar used for scan and saving into the array
    int saveVar;

    for (int i = 0; i < SIZE; i++)
    {
        scanf("%d", saveVar);
        input[i] = saveVar;
    }
    for (int i = 0; i < SIZE; i++)
        printf("%d, ", input[i]);

    for (int i = 0; i < SIZE; i++)
    {
        for (int j = 0; j < SIZE; j++)
        {
            if (input[i] != input[j])
            {
                printf("%d, ", input[i]);
            }
        }
    }
return 0;
}
c++
arrays
scanf
error-code
asked on Stack Overflow Apr 3, 2018 by DoNotResuscitate • edited Apr 5, 2018 by MartinJokes

1 Answer

0
int main() 
{
    int i,j,k,n,a[20];
    cout<<"Enter the number of elements in the array:\n";
    cin>>n;
    cout<<"\nEnter elements of array:\n";


    for(i=0;i<n;++i) {
       cin>>a[i];
    }


    for(i=0;i<n;++i)
        for(j=i+1;j<n;) 
        {
            if(a[i]==a[j])
            {
                for(k=j;k<n-1;++k)
                    a[k]=a[k+1];

                --n;
            }
            else
               ++j;
        }

    cout<<"\n";

    for(i=0;i<n;++i)
        cout<<a[i]<<" ";

    return 0;
 }

So basically, we ask the user for how many inputs they want to make in the array, a, and we use cin for that (because it is C++).

Your logic for removal of duplicate elements is incorrect. Have a look at mine, it is straightforward and a naive approach.

Please do have a look and let me know for any further doubts.

answered on Stack Overflow Apr 5, 2018 by Sahil Shah

User contributions licensed under CC BY-SA 3.0