当我在代码中的计算机要求时不输入数组中存在的键时,如何打印"The key(element) is not present in your array"

How to print "The key(element) is not present in your array" when I don't enter a key present in my array when asked for by the computer in my code

本文关键字:打印 The key is your array in present not element 计算机      更新时间:2024-09-28

假设我输入{1,3,3,5}作为我的数组,当被要求输入我想知道其索引的键时,我输入6。我如何编辑我的代码以打印";输入的密钥不在您的数组中";?

我的代码如下:

#include <iostream>
using namespace std;
void linearsearch(int arr[], int n, int key) {
int i;
for (i = 0; i < n; i++) {
if (arr[i] == key) {
cout << " nthe index is: " << i;
}
}
}
int main() {
int n;
cout << "enter the size of your array : ";
cin >> n;
int arr[n];
cout << "nenter the keys of your array: ";
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
int key;
cout << "n enter the key whose index you want to know: ";
cin >> key;
linearsearch(arr, n, key);
}

//您可以在void函数中使用布尔控制变量,当您找到数字时,您可以将其值设置为true,并在循环结束时插入if语句来检查bool变量的值,如果循环中的if语句没有执行,意味着没有找到数字,变量的值为假,因此它将打印您询问的行//

#include <iostream>
using namespace std;
void linearsearch(int arr[], int n, int key) {
int i;
bool found = false;
for (i = 0; i < n; i++) {
if (arr[i] == key) {
cout << " nthe index is: " << i;
found = true;
}
}
if (found == false){
cout << "The key entered is not in your array." << endl;
}
}
int main() {
int n;
cout << "enter the size of your array : ";
cin >> n;
int arr[n];
cout << "nenter the keys of your array: ";
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
int key;
cout << "n enter the key whose index you want to know: ";
cin >> key;
linearsearch(arr, n, key);
}