Shop OBEX P1 Docs P2 Docs Learn Events
Coming from PBASIC to Prop C: LookUp, LookDown — Parallax Forums

Coming from PBASIC to Prop C: LookUp, LookDown

John KauffmanJohn Kauffman Posts: 653
edited 2014-02-18 18:11 in Propeller 1
Does this seem right? It works but is there a better technique?
PBASIC
LOOKUP IndexNumberIn,[item1,item2,item3], VarToReceiveValue
LOOKDOWN ValueIn,[item1,item2,item3], VarToReceiveIndexNumber
‘if item list is strings then: [“item1”,”item2”,”item3”]

Prop C
Lookup: refer to the [element#] in the array
char myResultHolder;
  int myLookUpNumber = 2;
  char myArrayOfLetters1[] = "abcd";
  myResultHolder = myArrayOfLetters1[myLookUpNumber];
  print("myLookUpNumber = 2 returned %c",myResultHolder);

Lookdown: start with a value and get the index of the match in the array
char myArrayOfLetters2[] = "wxyz";
  char myLookUpValue = 'y';
  int myResultIndexNumber;
  int myArrayCounter;

  for (myArrayCounter=0; myArrayCounter<sizeof(myArrayOfLetters2); myArrayCounter++){
  	if (myArrayOfLetters2[myArrayCounter] == myLookUpValue){
    myResultIndexNumber=myArrayCounter;} //found
    } // loop thorugh all members of array
  print("myLookUpValue of 'y' returned index number of %d",myResultIndexNumber);

Comments

  • SRLMSRLM Posts: 5,045
    edited 2014-02-18 15:59
    Lookup: yes, a simple index.
    Lookdown: yes, a linear search. One small optimization is adding a "break;" if the item is found.

    For the particular case of finding a letter in a string you can use the strchr function: http://www.cplusplus.com/reference/cstring/strchr/
  • John KauffmanJohn Kauffman Posts: 653
    edited 2014-02-18 18:11
    Thanks, SRLM - good catch on break
      	if (myArrayOfLetters2[myArrayCounter] == myLookUpValue){
                myResultIndexNumber=myArrayCounter;
                break;} //found
        } // loop through members of array until find a match
    
Sign In or Register to comment.