Q1. Given an unordered list [3,]9, 100, 100, 98]. User inputs a number. Write a C program to check whether this number is in the list.
Requirements:
. If the number is in the list, report the number and its position. Otherwise, report that the number is not in the list.
. The position to report starts from 1.
Note:
. If the user inputs the number which is in the list and have multiple occurrences (e.g., 100), you either can just reports it is in the list and the one occurrence. Or you can report all the occurrences. Think about the differences.
Sample run1:
please enter a number to check: 32
number 32 is not in the list.
Sample run2:
please enter a number to check: 98
number 98 is in the list, position: 5
Sample run3:
please enter a number to check: 100
number 100 is in the list, position: 3
1
Expert's answer
2012-03-15T09:52:07-0400
#include <iostream>
using namespace std;
void main() {
int n[] = {3,9,100,100,98};
int num;
bool f = false;
cout << "Enter the number: ";
cin >> num;
for(int i = 0; i < 5; i++){
if(n[i] == num){
cout << "number " << num << " is in the list, position: " << i+1;
f = true;
break;
}
}
if(!f)
cout << "number " << num << " is not in the list";
Comments
Leave a comment