Answer to Question #152413 in C++ for ajmal

Question #152413
Write a program to search the array element. Enter a value from the keyboard and find out the location of the entered value in the array.
1
Expert's answer
2020-12-21T12:47:48-0500
#include <iostream>
#include <ctime>


int main() {
	int N, *Array,value, index =-1;
	std::cout << "Enter namber of elements in array: ";
	std::cin >> N;
	if (N <= 0) {
		std::cout << "Incorrect data." << std::endl;
		system("pause");
		return 1;
	}
	Array = new int[N];//dynamic memory allocation
	srand(time(NULL));
	for (int i = 0; i < N; i++)
		Array[i] = rand() % (N * 5);//fill array rand numbers
	for (int i = 0; i < N; i++)
		std::cout << Array[i] << ' ';// print array 
	std::cout << std::endl;
	std::cout << "Enter value: ";
	std::cin >> value;
	
	for (int i = 0; i < N && index == -1; i++)//a loop that finds the value index
		if (Array[i] == value)
			index = i;
	if (index == -1)
		std::cout << "The value does not exist in the array." << std::endl;
	else
		std::cout << "Index of value: " << index << std::endl;
	delete []Array;// clearing memory
	system("pause");
	return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog