Searching an array for an entered value
Take 10 integer inputs from the user and store them in an array. Again ask the user to enter an integer, then the program should tell the user whether the entered integer exists or not.
Step 1: Create a single dimensional array with a size of 10.
int array[10];
Step 2: Prompt the user to enter 10 integer values using a loop to pass through array elements.
std::cout << "Enter ten integers:\n";
for (int i = 0; i < 10; i++)
{
std::cout << "Integer #" << i + 1 << ": ";
std::cin >> array[i];
}
Step 3: Create an integer variable and name it "key" for example.
int key;
Step 4: Prompt the user to input a value for the "key" integer variable.
std::cout << "\n" << "Now enter an integer number to search for: ";
std::cin >> key;
Step 5: Create a bool variable and name it "isPresent" for example.
bool isPresent = false;
Step 6: Search for the "key" value in the 10 array elements using the following steps:
1) Create a for loop to pass through array elements.
2) Create a conditional if statement with the condition that the current element equals to the "key" variable.
3) If the condition in the if statement returns true, then the variable "isPresent" is assigned to "true" and then break out of the loop. Otherwise, the loop is going to keep working until its condition returns "false".
for (int i = 0; i < 10; i++)
{
if (array[i] == key)
{
isPresent = true; break;
}
}
Step 7: After the for loop body, create if / else statements with the condition of , if "isPresent" returns "true", then the program should notify the user that the entered integer value does exist in the array. If "isPresent" returns "false", the program says that the entered number doesn't exist.
if (isPresent)
std::cout << key << " is present in the array.\n\n";
else
std::cout << key << " isn't present in the array.\n\n";
Putting it all together:
#include <iostream>
int main()
{
int array[10];
std::cout << "Enter ten integers:\n";
for (int i = 0; i < 10; i++)
{
std::cout << "Integer #" << i + 1 << ": ";
std::cin >> array[i];
}
int key;
std::cout << "\n" << "Now enter an integer number to search for: ";
std::cin >> key;
bool isPresent = false;
for (int i = 0; i < 10; i++)
{
if (array[i] == key)
{
isPresent = true;
break;
}
}
if (isPresent)
std::cout << key << " is present in the array.\n\n";
else
std::cout << key << " isn't present in the array.\n\n";
system("pause");
return 0;
}
Comments
Post a Comment