SunQuest
 
       Code Examples
  Home arrow Code Examples arrow Page 12 - First Steps in Programming
Click Here
IBM developerWorks
ASP Free Forums 
.NET  
ASP  
ASP Code  
ASP.NET  
ASP.NET Code  
BrainDump  
C#  
Code Examples  
Database  
Database Code  
IIS  
Microsoft Access  
MS SQL Server  
Visual Basic.NET  
Windows Scripting  
Windows Security  
XML  
ASP Web Hosting  
ASP.NET Web Hosting 
Dedicated Servers 
Actuate Whitepapers 
VeriSign Whitepapers 
Windows Web Hosting
 
IBM® developerWorks 
Sun Developer Network 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
CODE EXAMPLES

First Steps in Programming
By: Apress Publishing
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 58
    2005-03-23

    Table of Contents:
  • First Steps in Programming
  • Variables That Store Numbers
  • Naming Variables
  • Basic Arithmetic Operations
  • Try It Out: Division and the Modulus Operator
  • Variables and Memory
  • Division Using Floating-Point Values
  • Defining Constants
  • Type Casting in Arithmetic Expressions
  • Try It Out: Arithmetic with Values of Type char
  • Try It Out: Finding the Limits
  • Designing a Program
  • Summary

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
    Iron Speed
     
    ADVERTISEMENT

    Generate data entry and reporting .NET Web apps in minutes, straight from your database. Read our FREE whitepaper “Build Web 2.0 Applications Without Hand-Coding” Download now!

    First Steps in Programming - Designing a Program


    (Page 12 of 13 )

    Now it’s time for the end-of-chapter real-life example. It would be a great idea to try out some of the numeric types in a new program. I’ll take you through the basic elements of the process of writing a program from scratch. This involves receiving an initial specification of the problem, analyzing the problem, preparing a solution, writing the program and, of course, running the program and testing it to make sure it works. Each step in the process can introduce problems, beyond just the theory.

    The Problem

    The height of a tree is of great interest to many people. For one thing, if a tree is being cut down, knowing its height tells you how far away safe is. This is very important to those with a nervous disposition. Your problem is to find out the height of a tree without using a very long ladder, which itself would introduce risk to life and limb. To find the height of a tree, you’re allowed the help of a friend—preferably a short friend. You should assume that the tree you’re measuring is taller than both you and your friend. Trees that are shorter than you present little risk, unless they’re of the spiky kind.

    The Analysis

    Real-world problems are rarely expressed in terms that are directly suitable for programming. Before you consider writing a line of code, you need to be sure that you have a complete understanding of the problem and how it’s going to be solved. Only then can you estimate how much time and effort will be involved in creating the solution.

    The analysis phase involves gaining a full understanding of the problem and determining the logical process for solving it. Typically this requires a significant amount of work. It involves teasing out any detail in the specification of the problem that is vague or missing. Only when you fully understand the problem can you begin to express the solution in a form that’s suitable for programming.

    You’re going to determine the height of a tree using some simple geometry and the heights of two people: you and one other. Let’s start by naming the tall person (you) Lofty and the shorter person (your friend) Shorty. If you’re vertically challenged, the roles can be reversed. For more accurate results, the tall person should be significantly taller than the short person. Otherwise the tall person could consider standing on a box. The diagram in Figure 2-2 will give you an idea of what you’re trying to do in this program.

     
    Figure 2-2.  The height of a tree

    Finding the height of the tree is actually quite simple. You can get the height of the tree, h3, if you know the other dimensions shown in the illustration: h1and h2, which are the heights of Shorty and Lofty, and d1and d2, which are the distances between Lofty and Shorty, and from Lofty to the tree, respectively. You can use the technique of similar triangles to work out the height of the tree. You can see this in the simplified diagram in Figure 2-3.


    Figure 2-3.  Similar triangles

    Here, because the triangles are similar, height1 divided by distance1 is equal to height2 divided by distance2. Using this relationship, you can get the height of the tree from the height of Shorty and Lofty and the distances to the tree as shown in Figure 2-4.

    The triangles ADE and ABC are the same as those shown in the previous diagram. Using the fact that the triangles are similar, you can calculate the height of the tree as shown in the bottom equation in the diagram.

    This means that you can calculate the height of the tree in your program from four values:

    • The distance between Shorty and Lofty, d1in the diagram. You’ll use the variable shorty_to_lofty to store this value.

    • The distance between Lofty and the tree, d2in the diagram. You’ll use the variable lofty_to_tree to store this value.

    • The height of Lofty to the top of his head, h2in the diagram. You’ll use the variable lofty to store this value.

    • The height of Shorty, but only up to the eyes, h1in the diagram. You’ll use the variable shorty to store this value.

    You can then plug these values into the equation for the height of the tree.


    Figure 2-4.  Calculating the tree height

    Your first task is to get these four values into the computer. You can then use your ratios to find out the height of the tree, and finally output the answer. The steps are as follows:

    1. Input the values you need.

    2. Calculate the height of the tree using the equation in the diagram.

    3. Display the answer.

    The Solution

    This section outlines the steps you’ll take to solve the problem.

    Step 1

    Your first step is to get the values that you need to work out the height of the tree. This means that you have to include the stdio.h header file, because you need to use both printf() and scanf(). You then have to decide what variables you need to store these values in. After that, you can use printf() to prompt for the input and scanf() to read the values from the keyboard.

    You’ll provide for the heights of the participants to be entered in feet and inches for the convenience of the user. Inside the program, though, it will be easier to work with all heights and distances in the same units, so you’ll convert all measurements to inches. You’ll need two variables to store the heights of Shorty and Lofty in inches. You’ll also need a variable to store the distance between Lofty and Shorty, and another to store the distance from Lofty to the tree—both distances in inches, of course.

    In the input process, you’ll first get Lofty’s height as a number of whole feet and then as a number of inches, prompting for each value as you go along. You can use two more variables for this: one to store the feet value and the other to store the inches value. You’ll then convert these into just inches and store the result in the variable you’ve reserved for Lofty’s height. You’ll do the same thing for Shorty’s height (but only up to the height of his or her eyes) and finally the same for the distance between them. For the distance to the tree, you’ll use only whole feet, because this will be accurate enough—and again you’ll convert the distance to inches. You can reuse the same variables for each measurement in feet and inches that is entered. So here goes with the first part of the program:

    /* Program 2.17 Calculating the height of a tree */ #include <stdio.h>
    void main()
    {
      long shorty = 0L;         /* Shorty's height in
         inches      */
      long lofty = 0L;          /* Lofty's height in
         inches      */
      long feet = 0L;           /* A whole number of  
         feet        */
      long inches = 0L;         /* A whole number of
         inches      */
      long shorty_to_lofty = 0; /* Distance from Shorty to
         Lofty in inches */
      long lofty_to_tree = 0;   /* Distance from Lofty to the
         tree in inches  */
      const long inches_per_foot = 12L;
      /* Get Lofty's height */
      printf("Enter Lofty's height to the top of his/her head,
         in whole feet: ");
      scanf("%ld", &feet);
      printf("     ...and then inches: ");
      scanf("%ld", &inches);
      lofty = feet*inches_per_foot + inches;
      /* Get Shorty's height up to his/her eyes */
      printf("Enter Shorty's height up to his/her eyes, in
         whole feet: ");
      scanf("%ld", &feet);
      printf("                   ... and then inches: ");
      scanf("%ld", &inches);
      shorty = feet*inches_per_foot + inches;
      /* Get the distance from Shorty to Lofty */
      printf("Enter the distance between Shorty and Lofty, in
         whole feet: ");
      scanf("%ld", &feet);
      printf("                         ... and then inches: ");
      scanf("%ld", &inches);
      shorty_to_lofty = feet*inches_per_foot + inches;
      /* Get the distance from Lofty to the tree            */
      printf("Finally enter the distance to the tree to the
         nearest foot: ");
      scanf("%ld", &feet);
      lofty_to_tree = feet*inches_per_foot;
      /* The code to calculate the height of the tree will go
         here      */
      /* The code to display the result will go here        */
    }

    Notice how the program code is spaced out to make it easier to read. You don’t have to do it this way, but if you decide to change the program next year, it will make it much easier to see how the program works if it’s well laid out. You should always add comments to your programs to help with this. It’s particularly important to at least make clear what the variables are used for and to document the basic logic of the program.

    You use a variable that you’ve declared asconstto convert from feet to inches. The variable name, inches_per_foot, makes it reasonably obvious what’s happening when it’s used in the code. This is much better than using the “magic number” 12 explicitly. Here you’re dealing with feet and inches, and most people will be aware that there are 12 inches in a foot. In other circumstances, the significance of numeric constants may not be so obvious, though. If you’re using the value 0.22 in a program calculating salaries, it’s much less apparent what this might be; therefore, the calculation may seem rather obscure. If you create a const variable tax_rate that you’ve initialized to 0.22 and use that instead, then the mist clears.

    Step 2

    Now that you have all the data you need, you can calculate the height of the tree. All you need to do is implement the equation for the tree height in terms of your variables. You’ll need to declare another variable to store the height of the tree.

    You can now add the code that’s shown here in bold type to do this:

    /* Program 2.17 Calculating the height of a tree */ #include <stdio.h>
    void main()
    {
      long shorty = 0L;         /* Shorty's height in
         inches     */
      long lofty = 0L;          /* Lofty's height in
         inches     */
      long feet = 0L;           /* A whole number of
         feet       */
      long inches = 0L;         /* A whole number of 
         inches     */
      long shorty_to_lofty = 0; /* Distance from Shorty to
         Lofty in inches */
      long lofty_to_tree = 0;   /* Distance from Lofty to the
         tree in inches  */
      long tree_height = 0;     /* Height of the tree in 
         inches     */
      const long inches_per_foot = 12L;
      /* Get Lofty's height */
      printf("Enter Lofty's height to the top of his/her head,
         in whole feet: ");
      scanf("%ld", &feet);
      printf("       ...and then inches: ");
      scanf("%ld", &inches);
      lofty = feet*inches_per_foot + inches;
      /* Get Shorty's height up to his/her eyes      */
      printf("Enter Shorty's height up to his/her eyes, in
         whole feet: ");
      scanf("%ld", &feet);
      printf("               ... and then inches: ");
      scanf("%ld", &inches);
      shorty = feet*inches_per_foot + inches;
      /* Get the distance from Shorty to Lofty       */
      printf("Enter the distance between Shorty and Lofty, in
        whole feet: ");
      scanf("%ld", &feet);
      printf("                     ... and then inches: ");
      scanf("%ld", &inches);
      shorty_to_lofty = feet*inches_per_foot + inches;
      /* Get the distance from Lofty to the tree     */
      printf("Finally enter the distance to the tree to the
         nearest foot: ");
      scanf("%ld", &feet);
      lofty_to_tree = feet*inches_per_foot;
      /* Calculate the height of the tree in inches  */  
      tree_height = shorty + (shorty_to_lofty + lofty_to_tree) 
          *(lofty-shorty)/
                                            shorty_to_lofty;
      /* The code to display the result will go here */
    }

    The statement to calculate the height is essentially the same as the equation in the diagram. It’s a bit messy, but it translates directly to the statement in the program to calculate the height.

    Step 3

    Finally, you need to output the answer. To present the result in the most easily understandable form, you’ll convert the result that you’ve stored in tree_height, which is in inches, back into feet and inchches:

    /* Program 2.17 Calculating the height of a tree */ #include <stdio.h>

    void main()

    {

    long shorty = 0L;

    /* Shorty's height in inches

    */

    long lofty = 0L;

    /* Lofty's height in inches

    */

    long feet = 0L;

    /* A whole number of feet

    */

    long inches = 0L;

    /* A whole number of inches

    */

    long shorty_to_lofty = 0;

    /* Distance from Shorty to Lofty in inches

    */

      long lofty_to_tree = 0;     /* Distance from Lofty to 
        the tree in inches */
      long tree_height = 0;       /* Height of the tree in
        inches */
      const long inches_per_foot = 12L;
      /* Get Lofty's height */
      printf("Enter Lofty's height to the top of his/her head,
        in whole feet: ");
      scanf("%ld", &feet);
      printf("                    ... and then inches: ");
      scanf("%ld", &inches);
      lofty = feet*inches_per_foot + inches;
      /* Get Shorty's height up to his/her eyes */
      printf("Enter Shorty's height up to his/her eyes, in
        whole feet: ");
      scanf("%ld", &feet);
      printf("          ... and then inches: ");
      scanf("%ld", &inches);
      shorty = feet*inches_per_foot + inches;
      /* Get the distance from Shorty to Lofty */
      printf("Enter the distance between Shorty and Lofty, in 
         whole feet: ");
      scanf("%ld", &feet);
      printf("                      ... and then inches: ");
      scanf("%ld", &inches);
      shorty_to_lofty = feet*inches_per_foot + inches;
     
    /* Get the distance from Lofty to the tree */
      printf("Finally enter the distance to the tree to the
         nearest foot: ");
      scanf("%ld", &feet);
      lofty_to_tree = feet*inches_per_foot;
     
    /* Calculate the height of the tree in inches */  
      tree_height = shorty + (shorty_to_lofty + lofty_to_tree)*
         (lofty-shorty)/
                                     shorty_to_lofty;
      /* Display the result in feet and inches         */ 
      printf("The height of the tree is %ld feet and %ld
         inches.\n",
               tree_height/inches_per_foot, tree_height% 
         inches_per_foot);
     
    }

    And there you have it. The output from the program looks something like this:

    ======================================================
    Enter Lofty's height to the top of his/her head, in whole
       feet first: 6
                     ... and then inches: 2
    Enter Shorty's height up to his/her eyes, in whole feet: 
       4
              ... and then inches: 6
    Enter the distance between Shorty and Lofty, in whole feet : 5
                ... and then inches: 0
    Finally enter the distance to the tree to the nearest foot:   20
    The height of the tree is 12 feet and 10 inches.

    ======================================================

    This article is excerpted from Beginning C by Ivor Horton (Apress, 2004; ISBN 1590592530). Check it out at your favorite bookstore today. Buy this book now.

    More Code Examples Articles
    More By Apress Publishing


     

    CODE EXAMPLES ARTICLES

    - Handling Animations and Bitmaps Using GDI+ f...
    - Download a Web Page using the WebClient
    - Creating a Chart using Data from a Database ...
    - The Basics of Charting with the MS Chart Con...
    - Searching Body Text with textRange: Enter th...
    - Searching Body Text with textRange: Building...
    - Searching Body Text with textRange, part 1: ...
    - First Steps in Programming
    - Programming in C
    - Quick Introduction to ASF,ASX, and Networkin...
    - SatView: Pointer Perfect, Part 2: Constructi...
    - SatView: Pointer Perfect, Part 1
    - Style Case Studies: Construction Unions
    - Creating an Engine for Games for Windows
    - Style Case Studies: Generic Callbacks

    SunQuest




    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 1 hosted by Hostway