Search first occurrence of element in an array

Write a program in C language that will accepts n of integer values from the user, accepts the integer element to be searched and displays the position of the element in the array.

Output:

You may also like...

9 Responses

  1. kiven says:

    that is so nice

  2. Anonymous says:

    sir ,is it necessary to give the getch() statement in the second for loop ?i.e. after the printf() statement.I tried removing the getch(), but the program didnt show the printf statement.Why is that?

  3. LearnCOnline says:

    If you use getch() statement, the program will wait until user input some input like keyboard {ENTER}. In the above program, if you won’t use it then program will exit without showing you the output screen.

  4. nishank says:

    Sir is it necessary to use exit(1) instead can we use break keyword??

  5. Prashant N. says:

    Hello Nishank,

    exit(1) is used to exit the program execution.

    Here, we have used exit(1) to exit the program execution once the element is found. So, once the element is found, the program will display the message:

    and exit the program.

    break keyword is used to break the loop execution and not the program execution. Refer: http://www.learnconline.com/2010/03/break-statement-in-c-programming-language.html

    If we use the break keyword, it will display the message:

    and break the for loop execution. But after exit from the for loop, it will continue its execution after for loop. That is, it will execute the following piece of code:

    Hence, if we use break keyword, the output would be something like below:

    which is incorrect.

    And if we use exit(1) then the output would be:
    Element found at position X

    which is logically correct.

    Hope we have answered your question.

    Thanks,
    LearnCOnline Team

  6. Tanvir says:

    Sir,why we used #include here??is it for exit(1)……and thanks for helping us.it will be more helpful if you give us more problems for beginners.

    • Tanvir says:

      *why we used exit(1) here?what is it??

      • Prashant N. says:

        exit(1) has been used for the termination of the program. We have found the element at a particular position and now we do not need the program to execute any of the further steps. Hence, we have used exit(1) so that the program gets terminated automatically. Please note that you can also use exit(0) to terminate the program.

  1. March 2, 2014

    […] Search first occurrence of element in an array […]

Leave a Reply

Your email address will not be published. Required fields are marked *