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.
#include#include #include void main() { int arr[100],i,element,no; clrscr(); printf("\nEnter the no of Elements: "); scanf("%d", &no); for(i=0;i Output:
Enter the no of Elements: 5 Enter Element 1: 12 Enter Element 2: 23 Enter Element 3: 52 Enter Element 4: 23 Enter Element 5: 10 Enter the element to be searched: 23 Element found at position 2
that is so nice
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?
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.
Sir is it necessary to use exit(1) instead can we use break keyword??
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: https://www.learnconline.com/2010/03/break-statement-in-c-programming-language.htmlIf 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
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.
*why we used exit(1) here?what is it??
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.