Code Examples
  Home arrow Code Examples arrow Page 10 - 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 
 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: Arithmetic with Values of Type char


    (Page 10 of 13 )

    Let’s look at another example in which you apply arithmetic operations to values of type char:

    /* Program 2.14 Using type char */
    #include <stdio.h>
    void main()
    {
      char first ='A';
      char second ='B'’;
      char last ='Z';
      char number = 40;
      char ex1 = first + 2;        /* Add 2 to 'A'         */
      char ex2 = second - 1;       /* Subtract 1 from 'B'  */
      char ex3 = last + 2;         /* Add 2 to 'Z'         */
      printf("Character values   %-5c%-5c%-5c", ex1, ex2, ex3);
      printf("\nNumerical equivalents %-5d%-5d%-5d", ex1, ex2,
        ex3);
      printf("\nThe number %d is the code for the character %
        c\n", number, number);
    }

    When you run the program you should get the following output:

    =======================================================
    Character values      C   A  \
    Numerical equivalents 67 65 92
    The number 40 is the code for the character (

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

    HOW IT WORKS

    This program demonstrates how you can happily perform arithmetic with char variables that you’ve initialized with characters. The first three statements in the body of main() are as follows:

     char first = 'A';
     char second = 'B';
     char last = 'Z';

    These initialize the variables first, second, and last to the character values you see. The numerical value of these variables will be the ASCII codes for the respective characters. Because you can treat them as numeric, as well as characters, you can perform arithmetic operations with them.

    The next statement initializes a variable of type char with an integer value:

     char number = 40;

    The initializing value must be within the range of values that a 1-byte variable can store, so with my compiler where char is a signed type it must be between –128 and 127. Of course, you can interpret the contents of the variable as a character. In this case, it will be the character that has the ASCII code value 40, which happens to be a left parenthesis.

    The next three statements declare three more variables of type char:

     char ex1 = first + 2;        /* Add 2 to 'A'        */
     char ex2 = second - 1;       /* Subtract 1 from 'B' */
     char ex3 = last + 2;         /* Add 2 to 'Z'        */

    These statements create new values and therefore new characters from the values stored in the variables first, second, and last; the results of these expressions are stored in the variables ex1, ex2, and ex3.

    The next two statements output the three variables ex1, ex2, and ex3 in two different ways:

     printf("Character values %-5c%-5c%-5c", ex1, ex2, ex3); 
     printf("\nNumerical equivalents %-5d%-5d%-5d", ex1, ex2,
        ex3);

    The first statement interprets the values stored as characters by using the %-5c conversion specifier. This specifies that the value should be output as a character left-aligned in a field width of 5. The second statement outputs the same variables again, but this time interprets the values as integers by using the %-5d specifier. The alignment and the field width are the same but d specifies the output is an integer. You can see that the two lines of output show the three characters with their ASCII codes aligned below on the next line.

    The last line outputs the variable number as a character and as an integer:

     printf("\nThe number %d is the code for the character %
         c\n", number, number);

    To output the variable twice, you just write it twice—as the second and third arguments to the printf() function. It’s output first as an integer value and then as a character.

    This ability to perform arithmetic with characters can be very useful. For instance, to convert from uppercase to lowercase, you simply add the result of 'a'-'A' (which is 32 for ASCII) to the uppercase character. To achieve the reverse, just subtract 'a'-'A'. You can see how this works if you have a look at the decimal ASCII values for the alphabetic characters in Appendix B.


    Unsigned Integers: Using Positive Integers

    If you’re sure that you’ll be dealing with just positive integers, there’s a way of increasing the maximum value that you can use. The unsigned modifier can be used with all of the basic integer types that I’ve covered, to define types that store only positive integers. This allows you to handle integers roughly twice as large as you otherwise might. You use the unsigned modifier as follows:

    unsigned char a_value;     /* Can be from 0 to +255      */
    unsigned int number;       /* Can be from 0 to +65,535   */
    unsigned long big_number;  /* Can be from 0 to
        4,294,967,295  */

    You must be absolutely sure that you need only positive values if you want to use these. Unsigned variables can’t store negative values at all.

    When you want to specify an integer constant as unsigned, you append the letter U as upper- or lowercase to the numeric value. For example, you could write

    number = 25U;

    This sets the unsigned variable number of type int to 25.

    If you want to define a constant that is of type unsigned long, you need a U and an L as a suffix to the numeric value. You can specify the letters in upper- or lowercase, for example:

    big_number = 100000000UL;

    This stores the value 100,000,000 in the variable big_number.

    You use the format specifier %u to output an unsigned integer. You can also include a field width specification and a-for left alignment in the field if you wish.

    For example, you could output the value of the unsigned integer variable called number with this statement:

    printf("The value of number is %-12u", number);

    The field width is 12 here and the value will be left-aligned in the field. I’ve now covered all the numeric data types in C; Table 2-6 presents all of them.

    Table 2-6. Numeric Data Types

    NumberRange
    Variable TypeKeywordof Bytesof Values
    Characterchar1–128 to +127 or 0 to 255
    Unsigned characterunsigned char10 to 255
    Integerint2 or 4–32,768 to +32,767 or
    –2,147,438,648 to
    +2,147,438,647
    Unsigned integerunsigned int2 or 40 to 65,535 or 0 to
    4,294,967,295
    Short integershort2–32,768 to +32,767
    Unsigned short integerunsigned short20 to 65,535
    Long integerlong4–2,147,438,648 to
    +2,147,438,647
    Unsigned long integerunsigned long40 to 4,294,967,295
    Single precisionfloat4±3.4E38 (6 digits)
    floating-point
    Double precisiondouble8±1.7E308 (15 digits)
    floating-point
    Extended doublelong double10±1.2E4932 (19 digits)
    precision floating-point


    Finding the Limits

    I mentioned earlier and in various other places in this chapter how the limits for the range of values for some of these numerical types can vary from one system and/or compiler to another. This is obviously going to be a problem in some situations in which you really need to be able to determine within your program what the limits are in a particular instance. The C standard library includes header files that can provide you with this information. The limits.h header file provides information about integer types and the float.h header file does the same for floating-point types.

    The limits.h header file contains definitions for symbols (not variables) such that define the upper and lower limits for each signed integer type. For instance,INT_MIN and INT_MAX are the symbols representing the upper and lower limits for type int, and CHAR_MIN   and CHAR_MAX represent the limits for type char. For unsigned types only symbols for upper limits are defined because the lower limit is always zero. There are symbols with similarly formed names for each of the integer types in Table 2-6.

    In the float.h header are symbols with the names FLT_MIN and FLT_MAX that represent the minimum and maximum positive values of type float. There are similar symbols such as DBL_MIN, DBL_MAX, LDBL_MIN, and LDBL_MAX for the double and long double types. If you look in the documentation for the library that comes with your compiler, you’ll find many other symbols that represent values for other parameters relating to the implementation of the floating-point types on your system.

    Let’s see how you can access some of these with an example.


    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 1 hosted by Hostway