C Programming Absolute Beginner's Guide (3rd Edition)

(Romina) #1
At this point, it’s important for you to concentrate on what you do with arrays after the
arrays get filled with values. One of the most important things to do is find values that
you put in the arrays.

Finders, Keepers


Think about the following scenario: Your program contains an array that holds customer ID numbers
and an array that holds the same number of customer balances. Such arrays are often called parallel
arrays because the arrays are in synch—that is, element number 14 in the customer ID array contains
the customer number that owes a balance found in element 14 of the balance array.


The customer balance program might fill the two arrays from disk data when the program first starts.
As a customer places a new order, it’s your program’s job to find that customer balance and stop the
order if the customer owes more than $100 already (the deadbeat!).


In a nutshell, here is the program’s job:



  1. Ask for a customer ID number (the key).

  2. Search the array for a customer balance that matches the key value.

  3. Inform you if the customer already owes more than $100.


The following program does just that. Actually, the program maintains a list of only 10 customers
because you’re not yet ready to tackle disk input (but you’re almost there!). The program initializes
the arrays when the arrays are first defined, so maintaining only 10 array element pairs (the customer
ID and the corresponding balance arrays) keeps the array definitions simple.


Study this program before typing it in and running it. See if you can get the gist of the program from
the code and comments. Following this code listing is an explanation.


Click here to view code image


// Example program #1 from Chapter 22 of Absolute Beginner's Guide
// to C, 3rd Edition
// File Chapter22ex1.c
/* This program takes an ID number from the user and then checks the
ID against a list of customers in the database. If the customer
exists, it uses that array element to check their current balance,
and warns the user if the balance is more than 100 */
#include <stdio.h>
main()
{
int ctr; // Loop counter
int idSearch; // Customer to look for (the key)
int found = 0; // Will be 1 (true) if customer is found
// Defines the 10 elements in the two parallel arrays
int custID[10] = {313, 453, 502, 101, 892,
475, 792, 912, 343, 633};
float custBal[10] = {0.00, 45.43, 71.23, 301.56, 9.08,
Free download pdf