Write a program to search for a number in a sequence of numbers. Your program sh
ID: 3821146 • Letter: W
Question
Write a program to search for a number in a sequence of numbers. Your program should first ask the user to input ten real numbers (You can use double or float data type). You should store all values in a one-dimensional array. After entering the sequence, the program should ask the user input as a number, which should be searched in the array. If the number exists in the sequence of numbers stored earlier, then the program should print the “NUMBER FOUND” as well the position of the number in the sequence. You should also consider the scenario that the same number can be repeated in the sequence more than once.
Explanation / Answer
#include <iostream>
#include <string>
using namespace std;
int main()
{
double nums[10];
cout<<"Enter 10 real numbers: "<<endl;
for(int i=0; i<10; i++){
cin >> nums[i];
}
double searchNum;
cout<<"Enter the search number: ";
cin >> searchNum;
string s;
bool found = false;
for(int i=0; i<10; i++){
if(nums[i] == searchNum){
found = true;
s = s+ to_string(i)+", ";
}
}
if(found){
cout<<"NUMBER FOUND at "<<s.substr(0,s.length()-2)<<endl;
}
else {
cout<<"NUMBER NOT FOUND"<<endl;
}
return 0;
}
Output:
sh-4.2$ g++ -std=c++11 -o main *.cpp
sh-4.2$ main
Enter 10 real numbers:
1.1
2.2
3.3
3.3
4.4
4.5
5.5
6.6
5.5
8.8
Enter the search number: 9.9
NUMBER NOT FOUND
sh-4.2$ g++ -std=c++11 -o main *.cpp
sh-4.2$ main
Enter 10 real numbers:
1.1
1.1
1.1
2.2
3.3
4
5
6
7
8
Enter the search number: 1.1
NUMBER FOUND at 0, 1, 2
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.