• 🏆 Texturing Contest #33 is OPEN! Contestants must re-texture a SD unit model found in-game (Warcraft 3 Classic), recreating the unit into a peaceful NPC version. 🔗Click here to enter!
  • It's time for the first HD Modeling Contest of 2024. Join the theme discussion for Hive's HD Modeling Contest #6! Click here to post your idea!

Problem with Simple Program

Status
Not open for further replies.
Level 16
Joined
Mar 27, 2011
Messages
1,349
I've just started programming in C++. I'm learning from a textbook. I'm trying to create a program outline
in the textbook. The program is a database of items for a shop. The user searches for a product number,
and the program will display information about it using what I'm learning called a binary search. Should be
pretty simple I think.

All seems to run well except one problem. The program freezes when I input the number 914. It can't handle
that number for some reason.

Here's the code:

Code:
// Publisher - Case Study 8.2.cpp : Defines the entry point for the console application.
// Created the program as outlined in chapter 8.2 (Case study), page 462.
// The program should prompt the user to enter a product number, and will display the
// title, description and price of the product.

#include "stdafx.h"
#include <iostream>
using namespace std;

// Constant variables
const int ProIDLowest = 914;
const int ProIDHighest = 922;
const int NUMPRODUCTS = 9;
const int TITLE_SIZE = 30;
const int DESC_SIZE = 15;


// Setup prototypes
int SearchProID(int array[], int elements, int value); // Binary search function


int _tmain(int argc, _TCHAR* argv[])
{
	// Setup variables
	int ID[NUMPRODUCTS] = {914, 915, 916, 917, 918, 919, 920, 921, 922};
	char title[NUMPRODUCTS][TITLE_SIZE] = { "Six Steps to Leadership", 
		                                    "Six steps to Leadership",
							                "The Road to Excellence",
							                "Seven Lessons of Quality",
							                "Seven lessons of Quality",
							                "Seven Lessons of Quality",
							                "Teams are Made, Not Born",
							                "Leadership for the Future",
											"Leadership for the Future" };
	char description[NUMPRODUCTS] [DESC_SIZE] = { "Book", "Audio Cassette", "Video",
		                                          "Book", "Audio Cassette", "Video",
												  "Book", "Book", "Audio Cassette" };
	double prices[NUMPRODUCTS] = {12.95, 14.95, 18.95, 16.95, 21.95, 31.95, 14.95, 14.95, 16.95};
	int pronum;
	int searchresult;
	char again = 'n';
	bool idinputvalid = false;

	
	// Describe and instruct the  program to user
	cout << "The Demetris Leadship Center (DLC, Inc.)\n";
	cout << "----------------------------------------\n";
	cout << "This program can search the database for items\n";
    cout << "and display their details.\n\n";
	// The do loop used in case user wants to search multiple items
	do
	{
	    // Will add a new line
		// Will only run on the iteration of loop if user wants to 
		// search another item
		if (again == 'y' || again == 'Y')
			cout << endl;
		// Ask for ID from user
		cout << "Enter a product's ID: ";
		cin >> pronum;
		idinputvalid = false;
		// Check the ID is valid, if not reask for ID
		while (pronum < ProIDLowest || pronum > ProIDHighest)
		{
			// These statements will run if pronum is invalid
			// If so, asks for a new product ID
			cout << "Please enter a valid product number (914-922).\n";
	        cout << "Enter a Product's ID: ";
		    cin >> pronum;
		};
		
		// Will search for product details
		searchresult = SearchProID(ID, NUMPRODUCTS, pronum);
		// Displays the details of the searched product
		if (searchresult == -1)
			cout << "That product number was not found.\n";
	    else 
		{
	        cout << endl;
	        cout << "Item: " << title[searchresult] << endl;
	        cout << "Description: " << description[searchresult] << endl;
	        cout << "Price: $" << prices[searchresult] << endl;
		}
		// Asks if the user wants to search another item. If so, will repeat the do loop.
		cout << endl << "Would you like to search another item (Y/N)? ";
	    cin >> again;
	
	} while (again == 'y' || again == 'Y'); // The user may enter lower or upper case.

	return 0;
}

// This is a binary search. More complex but more efficient than a
// Linear search. Used to search for a particular value within an
// index.

int SearchProID(int array [], int elements, int value)
{
	int first = 0,           // First array element
		last = elements - 1, // Last array element
		middle,              // Mid point of search
		position = -1;       // Position of search value
	bool found = false;      // The flag
	
	while (!found && first <= last)
	{
		middle = (first + last) / 2; // Calculate mid point
		if (array[middle] == value) // If value is found at mid
		{
			found = true;
			position = middle;
		}
		else if (array[middle] > value) // If value is in lower half
			last = middle + 1;
		else
			first = middle + 1; // If value is in uper half
	}
	return position;
}

Edit: It seems some code is too long for this website. Sorry, might make it harder to read.
 
Last edited:
Level 29
Joined
Jul 29, 2007
Messages
5,174
Let's run your input manually and see what happens.

Iteration 1
first = 0
last = 8
middle = (0 + 8) / 2 = 4
array[middle] = 918 > 914

Iteration 2
first = 0
last = 4 + 1 = 5
middle = (0 + 5) / 2 = 2
array[middle] = 916 > 914

Iteration 3
first = 0
last = 2 + 1 = 3
middle = (0 + 3) / 2 = 1
array[middle] = 915 > 914

Iteration 4
first = 0
last = 1 + 1 = 2
middle = (0 + 2) / 2 = 1
array[middle] = 915 > 914

Iteration 5
first = 0
last = 1 + 1 = 2
middle = (0 + 2) / 2 = 1
array[middle] = 915 > 914

Iteration 6
first = 0
last = 1 + 1 = 2
middle = (0 + 2) / 2 = 1
array[middle] = 915 > 914

....and so on.

To avoid this, don't increment last when middle > value.

Also, please use [code=cpp] instead of [code].
 
Status
Not open for further replies.
Top