Q-32: Write a C/C++ program to find the position of given element in an array.
    

Using - C


#include<stdio.h> void main() { int size, element, i; printf("Enter the size of the Array: "); scanf("%d",&size); int arr[size]; printf("Enter %d Elements: \n"); for(i=0; i < size; i++) { scanf("%d", &arr[i]); } system("cls"); // Displaying Array printf("Given Array: "); for(i=0; i < size; i++) { printf("%d ",arr[i]); } printf("\n\nEnter the element to be searched: "); scanf("%d",&element); for(i=0; i < size; i++) { if(arr[i] == element) { printf("%d found at position: %d",element, (i+1)); return; } } printf("%d not found in this Array!",element); }

OUTPUT

Enter the size of the Array:  6
Enter 6 Elements:
12
21
54
65
98
78

Given Array:  12  21  54  65  98  78

Enter the element to be searched:  98
98 found at position:  5


        

Using - C++


#include<iostream> using namespace std; int main() { int size, element; cout<< "Enter the size of the Array: "; cin>> size; int arr[size]; cout<< "Enter "<< size << " Elements: "<< endl; for(int i=0; i < size; i++) { cin>> arr[i]; } system("cls"); //Displaying Array cout<< "Given Array: "; for(int i=0; i < size; i++) { cout<< arr[i]<< " "; } cout<< "\n\nEnter the element to be searched: "; cin>> element; for(int i=0; i < size; i++) { if(arr[i] == element) { cout<< element<< " found at position: "<< i+1<< endl; return 1; } } cout<< element<< " not found in this Array!"<< endl; return 0; }

OUTPUT

Enter the size of the Array:  6
Enter 6 Elements:
12
21
54
65
98
78

Given Array:  12  21  54  65  98  78

Enter the element to be searched:  28
28 not found in this Array!