Friday, July 31, 2009

In C Programming, how do I search within arrays?

I'm having a hard time creating this program homework. It's written in C Language, not C++.





This is the instruction given by our teacher:





The program will accept 5 numbers. It will also accept a number to be searched (search among the inputted numbers). The program will also display the number of occurence of the number searched for and its exact location (location in the memory).





SAMPLE OUTPUT:


Enter 5 numbers: /* User inputs: 23 4 23 1 2 */


Enter number to be searched: /* user inputs: 23 */


/* the result is below */


Occurence(s): 2


Location: 0 2





I hope someone can help. It will be great if someone can show a source code. Thanks in advance. :)

In C Programming, how do I search within arrays?
int iOriginalNumbers[ 5 ];


int iNumberToBeSearched;


int iLocationArray[ 5 ] = {-1, -1, -1, -1, -1};


int iNumOccurences = 0;


int iCnt = 0, jCnt = 0;


char szDummy[1];





printf( "Enter 5 numbers, separated by a space, hit enter when done: " );





scanf( "%d %d %d %d %d", %26amp;iOriginalNumbers[0], %26amp;iOriginalNumbers[1], %26amp;iOriginalNumbers[2], %26amp;iOriginalNumbers[3], %26amp;iOriginalNumbers[4] );





printf( "\nEnter Number to be Searched: " );


scanf( "%d", %26amp;iNumberToBeSearched );





for( iCnt = 0; iCnt %26lt; 5; iCnt++ )


{


if( iOriginalNumbers[ iCnt ] == iNumberToBeSearched )


{


iNumOccurences++;


iLocationArray[ jCnt ] = iCnt;


jCnt++;


}


}





printf( "\nOccurence(s): %d\n", iNumOccurences );


printf( "\nLocation: ");


if( iNumOccurences %26lt;= 0 )


{


printf( "N/A" );


}


else


{


for( iCnt = 0; iCnt %26lt; 5; iCnt++ )


{


if( iLocationArray[ iCnt ] == -1 ) break;


printf( "%d ", iLocationArray[ iCnt ] );


}


}





printf( "\nPress enter to quit" );


scanf( "%s", szDummy );


return;





DISCLAIMER: I just typed it up on the space provided by answers, so it may have typos, silly mistakes, oversights etc. You need to #include header files like stdio.h, etc.

peacock plant

No comments:

Post a Comment