Showing posts with label search a number. Show all posts
Showing posts with label search a number. Show all posts

Friday, June 13, 2014

Search a Number in C++

There are many ways to write a program using a particular programming language just like C++ but the question is how we can construct a program without properly identity the nature of the problem. In this article I will show you how to write a program using C++ as our programming language to search a number in a given list by our user.

I called this program search a number using C++ what the program will do is very simple it will ask the user how many numbers to be process by our program. For example let say the user type 5 it means there are five items to be accepted by our program. Assuming that the five items has a value of 1,2,3,4,5 and then our program will ask again our user what number to be search. If our user give 3 our program will look in the list if the number 3 is found in the given list. Our program will tell our user that the number 3 is in the list and its location can be found at number three.

I hope you  will find my program useful enough in your programming assignments and projects.

Thank you very much.


This is the output if the given number is found in a given list.


This is the output if the given number is not found in a given list.


I am using Code:Blocks as my text editor in writing this program.


Program Listing

#include <iostream>
#include <stdlib.h>

using namespace std;

int main()
{
 int a[30],x=0,number=0,i=0;


system("cls");
cout << "====== Searching a Number =====";
cout << "\n\n";
cout <<"Enter many items :";
cin >> number;
cout << "\n";

for(i=0;i < number;i++)
{
cout << "Enter a number in item no. " << i+1 << " : ";
cin >> a[i];
}
cout << "\n\n";
cout <<"Enter the number to be search :=> ";
cin >> x;

i=0;
while(i < number && x!=a[i])
i++;

if(i < number)
{
cout << "\n\n";
cout <<"The number " <<x<<" found at the location = " <<i+1 << ".";
}
else
{
cout << "\n\n";
cout <<"The number " << x << " not found in a given list.";
}

cout << "\n\n";
system("pause");
}