How to fill an array with distinct values

无人久伴 提交于 2019-12-11 09:47:02

问题


I want my array input such that it cannot have the same number twice: this however will have an output of "value exist please re enter: "; two times. how do i check if it is unique and only display once if it has been initialised before?

int main(){
  int arr_size = 10;
  int value;
  int aArray[10];
  for(int i=0;i<arr_size;i++)
  {
        cout<<"enter value of slot"<<i+1<<": ";
        cin>>value;

        for(int j=0;j<arr_size;j++){

          if(value == aArray[j])
          {
            cout<<"value exist please re enter: ";
            cin>>value;
          }
          else{

          aArray[i] = value;
          }
        }
    }

  }

回答1:


Change to:

  for(int i=0;i<arr_size;i++)
  {
      cout<<"enter value of slot"<<i+1<<": ";
      while(1) { //You must keep reading until you have read a valid value
        cin>>value;
        bool alreadyPresent = false;    

        for(int j=0;j<i;j++){ //You only have to check against already inserted values!
                              //Before you were checking against uninitialized values!!
          if(value == aArray[j])
          {
            alreadyPresent = true;
            break; //I don't need to further iterate the array
          }

        }

        if (alreadyPresent)
          cout<< std::endl << value exists, please re enter: ";
        else
          break; //I can proceed with the next value, user has not to reenter the value
       }
     aArray[i] = value;

     std::cout << std::endl; //next line...
  }

Alternative:

  for(int i=0;i<arr_size;i++)
  {
      cout<<"enter value of slot"<<i+1<<": ";

      bool alreadyPresent;
      do { //You must keep reading until you have read a valid value
        cin>>value;
        alreadyPresent = false;    

        for(int j=0;j<i;j++){ //You only have to check against already inserted values!
                              //Before you were checking against uninitialized values!!
          if(value == aArray[j])
          {
            alreadyPresent = true;
            cout<< std::endl << value exists, please re enter: ";
            break; //I don't need to further iterate the array
          }

        }

      } while (alreadyPresent);
     aArray[i] = value;

     std::cout << std::endl; //next line...
  }


来源:https://stackoverflow.com/questions/24782859/how-to-fill-an-array-with-distinct-values

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!