Code Examples
  Home arrow Code Examples arrow Page 11 - First Steps in Programming
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 
Moblin 
Windows Web Hosting
 
IBM® developerWorks 
Sun Developer Network 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
IBM developerWorks
 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
     
     
    ADVERTISEMENT

    Stay one step ahead of the competition. Evaluate and give feedback on some of the hottest web development tools on the market today. Make your opinion heard! Click Here

    First Steps in Programming - Try It Out: Finding the Limits


    (Page 11 of 13 )

    This program just outputs the values corresponding to the symbols defined in the header files:

    /* Program 2.15 Finding the limits */
    #include <stdio.h>
    #include < limits.h >     /* For limits on integer types */ #include <float.h>        /* For limits on floating-point
        types */
    void main()
    {
      printf("Variables of type char store values from %d to %
                               d", CHAR_MIN, CHAR_MAX);
      printf("\nVariables of type unsigned char store values
                             from 0 to %u", UCHAR_MAX);
      printf("\nVariables of type short store values from %
                         d to %d", SHRT_MIN, SHRT_MAX);
      printf("\nVariables of type unsigned short store values
                              from 0 to %u",
    USHRT_MAX);
      printf("\nVariables of type int store values from %d to %
                                 d", INT_MIN, INT_MAX);
      printf("\nVariables of type unsigned int store values
                              from 0 to %u", UINT_MAX);
      printf("\nVariables of type long store values from %d to
                               %d",
    LONG_MIN, LONG_MAX);
      printf("\nVariables of type unsigned long store values
                             from 0 to %u", ULONG_MAX);
      printf("\n\nThe size of the smallest non-zero value of
                          type float is %.3e",
    FLT_MIN);
      printf("\nThe size of the largest value of type float is
                                       %.3e", FLT_MAX);
      printf("\nThe size of the smallest non-zero value of  
                         type double is %.3e",
    DBL_MIN);
      printf("\nThe size of the largest value of type double is
                                       %.3e", DBL_MAX);
      printf("\nThe size of the smallest non-zero value of 
                    type long double is %.3e",
    DBL_MIN);
      printf("\nThe size of the largest value of type long
                           double is %.3e\n", DBL_MAX);
    }

    You’ll get output somewhat similar to the following:

    ===================================================
    Variables of type char store values from -128 to 127 Variables of type unsigned char store values from 0 to 255 Variables of type short store values from -32768 to 32767 Variables of type unsigned short store values from 0 to 
              65535
    Variables of type int store values from -2147483648 to
              2147483647
    Variables of type unsigned int store values from 0 to
              4294967295
    Variables of type long store values from -2147483648 to
              2147483647
    Variables of type unsigned long store values from 0 to
              4294967295
    The magnitude of the smallest non-zero value of type float
              is 1.175e-038
    The magnitude of the largest value of type float is
              3.403e+038
    The magnitude of the smallest non-zero value of type  
              double is 2.225e-308        
    The magnitude of the largest value of type double is
              1.798e+308
    The magnitude of the smallest non-zero value of type long
              double is 2.225e-308
    The magnitude of the largest value of type long double is
              1.798e+308

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

    HOW IT WORKS

    You just output the values of the symbols in a series of printf() function calls. You have used the %u specifier to output the unsigned integer values. If you use %d for the maximum value of an unsigned type, values that have the leftmost bit (the sign bit for signed types) as 1 won’t be interpreted correctly.

    You use the %e specifier for the floating-point limits, which presents the values in exponential form. You also specify just three digits precision, as you don’t need the full accuracy in the output. The %f specifier presents values without an exponent, so it’s rather inconvenient for very large or very small values. If you try it in the example, you’ll see what I mean.


    Introducing the sizeof Operator

    You can find out how many bytes are occupied by a given type by using the sizeof operator. Of course, sizeof is a keyword in C. The expression sizeof(int) will result in the number of bytes occupied by a variable of type int. The sizeof operator has other uses too, but for the moment let’s just use it to find out how many bytes are occupied by each type.


    Try It Out: Discovering the Number of Bytes Occupied by a Given Type

    This program will output the number of bytes occupied by each numeric type:

    /* Program 2.16 Finding the size of a type */
    #include <stdio.h>
    void main()
    {
      printf("\nVariables of type char occupy %d bytes", size
          of (char));
      printf("\nVariables of type short occupy %d bytes", size
          of (short));
      printf("\nVariables of type int occupy %d bytes", size of
          (int));
      printf("\nVariables of type long occupy %d bytes", size
          of (long));
      printf("\nVariables of type float occupy %d bytes", size
          of(float));
      printf("\nVariables of type double occupy %d bytes", 
          size of(double));
      printf("\nVariables of type long double occupy %d
          bytes",  sizeof(long double));
     }

    On my system I get the following output:

    ======================================================
    Variables of type char occupy 1 bytes
    Variables of type short occupy 2 bytes
    Variables of type int occupy 4 bytes
    Variables of type long occupy 4 bytes
    Variables of type float occupy 4 bytes
    Variables of type double occupy 8 bytes
    Variables of type long double occupy 8 bytes

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

    HOW IT WORKS

    Because the sizeof operator results in an integer value, you can output it using the %d specifier. Note that you can also obtain the number of bytes occupied by avariable, var_name, with the expression sizeof var_name. Obviously, the space between the sizeof keyword and the variable name in the expression is essential.

    Now you know the range limits and the number of bytes occupied by each numeric type with your compiler.


    The op= Form of Assignment

    C is fundamentally a very concise language, so it provides you with abbreviated shortcuts for some operations. Consider the following line of code:

    number = number + 10;

    This sort of assignment, in which you’re incrementing or decrementing a variable by some amount, occurs very often, so there’s a shorthand version:

    number += 10;

    The +=operator after the variable name is one example of a family of op=operators. This statement has exactly the same effect as the previous one and it saves a bit of typing. The op in op= can be any of the following arithmetic operators:

    + - * / %

    If you suppose number has the value 10, then you can write the following statements:

    number *= 3;        /* number will be set to number*3
         which  is 30 */
    number /= 3;        /* number will be set to number/3
         which  is 3 */
    number %= 3;        /* number will be set to number%3   
         which is 1 */

    The op in op= can also be a few other operators that you haven’t encountered yet:

    << >> & ^ |

    I’ll defer discussion of these to Chapter 3, however.

    The op= set of operators always works in the same way. If you have a statement of the form

    lhs op= rhs;

    then the effect is the same as a statement of the form

    lhs = lhs op (rhs);

    Note the parentheses around the rhs expression. This means that op applies to the value that results from evaluating the entire rhs expression, whatever it is. So just to reinforce your understanding of this, let’s look at few more examples. The statement

    variable *= 12;
    is the same as
    variable = variable * 12;

    You now have two different ways of incrementing an integer variable by 1. Both of the following statements increment count by 1:

    count = count+1;
    count += 1;

    You’ll learn about yet another way of doing this in the next chapter. This amazing level of choice tends to make it virtually impossible for indecisive individuals to write programs in C.

    Because the op in op= applies to the result of evaluating the rhs expression, the statement

    a /= b+1;
    is the same as
    a = a/(b+1);

    Your computational facilities have been somewhat constrained so far. You’ve been able to use only a very basic set of arithmetic operators. You can get more power to your calculating elbow using standard library facilities, so before you come to the final example in this chapter, you’ll take a look at some of the mathematical functions that the standard library offers.

    Mathematical Functions

    The math.h header file includes declarations for a wide range of mathematical functions. To give you a feel for what’s available, you’ll take a look at those that are used most frequently. All the functions return a value of type double.

    You have the set of functions shown in Table 2-7 available for numerical calculations of various kinds. These all require arguments to be of type double.

    Table 2-7. Functions for Numerical Calculations

    Function

    floor(x) ceil(x) fabs(x) log(x) log10(x) exp(x) sqrt(x) pow(x, y)

    Operation

    Returns the largest integer that isn’t greater thanxas typedoubleReturns the smallest integer that isn’t less thanxas typedoubleReturns the absolute value ofxReturns the natural logarithm (base e) ofxReturns the logarithm to base 10 ofxReturns the value of exReturns the square root ofxReturns the value ofxy


    Here are some examples of using these functions:

    double x = 2.25;
    double less = 0.0;
    double more = 0.0;
    double root = 0.0;
    less = floor(x);   /* Result is 2.0 */
    more = ceil(x);    /* Result is 3.0 */
    root = sqrt(x);    /* Result is 1.5 */

    You also have a range of trigonometric functions available, as shown in Table 2-8. Arguments and values returned are again of type double and angles are expressed in radians.

    Table 2-8. Functions for Trigonometry

    FunctionOperation
    sin(x)Sine ofxexpressed in radians
    cos(x)Cosine ofx
    tan(x)Tangent ofx

    If you’re into trigonometry, the use of these functions will be fairly self-evident. Here are some examples:

    double angle = 45.0;          /* Angle in degrees */
    double pi = 3.14159265;
    double sine = 0.0;
    double cosine = 0.0;
    sine = sin(pi*angle/180.0);   /* Angle converted to
        radians  */
    cosine = sin(pi*angle/180.0); /* Angle converted to 
        radians  */

    Because 180 degrees is the same angle as π radians, dividing an angle measured in degrees by 180 and multiplying by the value of π will produce the angle in radians, as required by these functions.

    You also have the inverse trigonometric functions available:asin(),acos(), and atan(), as well as the hyperbolic functions sinh(),cosh(), and tanh(). Don’t forget, you must include math.h into your program if you wish to use any of these functions. If this stuff is not your bag, you can safely ignore this section.

    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





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