235k views
3 votes
int sequence[10] = { 3, 4, 5, 6, 7, 8, 9, 10, 1, 2 }; Write a C++ program to ask the user to enter a number, if the number can be found in the array, your program should display "Found". Otherwise, your program should display "Not found". For example, if the user enters 7, your program should display "Found". If the user enters 11, your program should display "Not found".

User Kamsiinov
by
5.7k points

1 Answer

1 vote

Answer:

The c++ program to implement search through an array is shown.

#include <iostream>

using namespace std;

int main()

{

int sequence[10] = { 3, 4, 5, 6, 7, 8, 9, 10, 1, 2 };

int input;

int found = 0;

cout << " This program confirms whether your element is present in the array. " << endl;

cout << " Enter any number " << endl;

cin >> input;

for( int k = 0; k < 10; k++ )

{

if( input == sequence[k] )

found = found + 1;

}

if( found == 0 )

cout << " Not Found " << endl;

else

cout << " Found " << endl;

return 0;

}

OUTPUT

This program confirms whether your element is present in the array.

Enter any number

7

Found

Step-by-step explanation:

The program uses the given integer array.

User is prompted to input any number. No validation is implemented for user input since it is not mentioned. The user input is taken in an integer variable, input.

int input;

cout << " Enter any number " << endl;

cin >> input;

Another integer variable found is declared and initialized to 0.

int found = 0;

Inside for loop, each element is compared with the user input.

If the user input is present in the given array, variable found is incremented by 1.

for( int k = 0; k < 10; k++ )

{

if( input == sequence[k] )

found = found + 1;

}

If value of variable found is 0, program displays “ Not Found ”.

If the value of variable found is greater than 0, program displays “ Found ”.

if( found == 0 )

cout << " Not Found " << endl;

else

cout << " Found " << endl;

This program can be tested for both positive and negative numbers.

User ChristopheCVB
by
4.9k points