SunQuest
 
       Code Examples
  Home arrow Code Examples arrow Page 9 - First Steps in Programming
Iron Speed
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
     
    IBM developerWorks
     
    ADVERTISEMENT

    Ajax Application Generator Generate database and reporting .NET Web apps in minutes. Quickly create visually stunning, feature-rich apps that are easy to customize and ready to deploy. Download Now!

    First Steps in Programming - Type Casting in Arithmetic Expressions


    (Page 9 of 13 )

    Let’s look at the original expression to calculate the quarterly revenue again and see how you can control what goes on so that you end up with the correct result:

     RevQuarter = QuarterSold/150*Revenue_Per_150;

    You know that if the result is to be correct, this statement has to be amended so that the expression is calculated in floating-point form. If you cast the value of Quarter-Sold to type float, then the expression will be evaluated as floating-point and your problem will be solved. To convert the value of a variable to another type, you place the type that you want to cast the value to in parentheses in front of the variable. The statement to calculate the result correctly will thus be

     RevQuarter = (float)QuarterSold/150.0f*Revenue_Per_150;

    This is exactly what you require. You’re using the right types of variables in the right places. You’re also ensuring you don’t use integer arithmetic when you want to keep the fractional part of the result of a division.

    Automatic Casting

    Look at the output from the second version of the program again:

    ======================================================
    Sales revenue this quarter is: $1930.50
    ======================================================

    Even without the explicit cast statement in the expression, the result was in floating-point form, even though it was still wrong. This is because the compiler automatically casts one or other of the operands when it’s dealing with an operation that involves values of different types. Your computer can perform only binary arithmetic operations (add, subtract, multiply, divide, and remainder) when both operands are of the same type. When the operands that are involved in an operation are of different types, the compiler arranges for the value that is of a type with a more limited range to be converted to the type of the other variable. So, referring back to the expression to calculate revenue:

     QuarterSold / 150 * Revenue_Per_150

    This was evaluated as 64400 (int)/150 (int), which equals 429 (int). Then 429 (intconverted to float) is multiplied by 4.5 (float), giving 1930.5 (float).

    An automatic conversion applies when a binary operator applies operands of different types. With the first operation, the numbers are both of type int, so the result is of type int. With the second operation, the first value is type int and the second value is type float. Type int is more limited in its range than type float, so the value of type int is automatically cast to type float. Whenever there is a mixture of types in an arithmetic expression, C will use a set of specific rules to decide how the expression will be evaluated. Let’s have a look at some of these conversion rules now.

    Conversion Rules in Casting

    As I’ve said, for each operation in an expression that involves operands of different types, your compiler will promote the operand with the type that has the more restricted range of values to be the same type as the other operand. The order of types in this context from highest to lowest is long double, then double, then float, followed by long, then int, then short, and finally the lowest, char. You haven’t seen type char yet, but you’ll be looking at it in a moment.

    Let’s see how these conversion rules apply in practice. Suppose you declare three variables:A as type double,B as type float, and C as type long. You can see how the expression A + B - C will be evaluated.

    The operation A + B will be carried out first. Because A is type double and B is type long, B will be converted to type double and the result will therefore be type double. To subtract C from this result, C is first converted to double and you end up with the final result as type double.

    Casts in Assignment Statements

    You can also cause an implicit cast to be applied by assigning the value of one type to a variable of a different type. This can cause values to be truncated so information is lost.

    For instance, if you assign a float or double value to a variable of type int or long, the fractional part of the float or double will be lost, and just the integer part will be stored. The following code fragment illustrates this situation:

    int number = 0;
    float value = 2.5f;
    number = value;

    The value stored in number will be 2. Because you’ve assigned the value of decimal (2.5) to the variable, number, which is of type int, the fractional part,.5, will be lost and only the 2 will be stored. Notice how I’ve used a specifier f at the end of 2.5f.

    Note that an assignment statement that may lose information because an automatic cast has to be applied will usually result in a warning from the compiler. However, the code will still compile, so there’s a risk that your program may be doing things that will result in incorrect results. Generally, it’s better to put explicit casts in your code wherever conversions that may result in information being lost are necessary.

    More Numeric Data Types

    To complete the set of numeric data types, I’ll now cover those that I haven’t yet discussed. The first is one that I mentioned previously: type char. A variable of type char can store the code for a single character. Because it stores a character code, which is an integer, it’s considered to be an integer type. Because it’s an integer type, the value stored can be treated just as an integer and can participate in arithmetic calculations.

    The Character Type

    Values of type char occupy the least amount of memory of all the data types. They require just 1 byte. The integer that’s stored in a variable of type char can be interpreted as a signed or unsigned value, depending on your compiler. An unsigned integer type is simply one that allows negative as well as positive integral values to be stored. As an unsigned type, the value stored in a variable of type char can range from 0 to 255. As a signed type, a variable of type char can store values from –128 to +127. Of course, both ranges correspond to the same set of bit patterns: from 0000 0000 to 1111 1111. With unsigned values, all 8 bits are data bits, so 0000 0000 corresponds to 0 and 1111 1111 corresponds to 255. With unsigned values, the leftmost bit is a sign bit, so –128 is the binary value 1000 0000, 0 is 0000 0000, and 127 is 0111 1111. The value 1111 1111 as a signed binary value is the decimal value –1.

    Thus, from the point of view of representing character codes, which are bit patterns, it doesn’t matter whether type char is regarded as signed or unsigned. Where it does matter is when you perform arithmetic operations on values of type char.

    A char variable can hold any single character, so you can specify the initial value for a variable of type char by a character constant. A character constant is a character written between single quotes. Here are some examples:

    char letter = 'A';
    char digit = '9';
    char exclamation = '!';

    You can use escape sequences to specify character constants too:

    char newline = '\n';
    char tab = '\t';
    char single_quote = '\'';

    Of course, in every case the variable will be set to the code for the character between single quotes. The actual code value will depend on your computer environment, but by far the most common is American Standard Code for Information Interchange (ASCII). You can find the ASCII character set in Appendix B.

    You can also initialize a variable of type char with an integer value, as long as the value fits into the range for type char with your compiler, for example:

    char character = 74; /* ASCII code for the letter J */

    A variable of type char has a sort of dual personality: you can interpret it as a character or as an integer. Here’s an example of an arithmetic operation with a value of type char:

    char letter = 'C';    /* letter contains the decimal code
        value 67 */
    letter = letter +3;   /* letter now contains 70, which is
        'F'      */

    Thus, you can perform arithmetic on a value of type char and still treat it as a character.

    Character Input and Character Output

    You can read a single character from the keyboard and store it in a variable of type char using the scanf()function with the format specifier %c:

    char ch = 0;
    scanf("%c", &ch);   /* Read one character */

    To write a single character to the command line with the printf()function, you use the same format specifier,%c:

    printf("The character is %c", ch);

    Of course, you can output the numeric value of a character too:

    printf("The character is %c and the code value is %d", ch,
          ch);


    This statement will output ch as a character and as a numeric value.


    Try It Out: Character Building

    If you’re completely new to programming, you may be wondering how on earth the computer knows whether it’s dealing with a character or an integer. The reality is that it doesn’t. It’s a bit like in Alice’s Adventures in Wonderland when Humpty Dumpty told Alice, “When I use a word, it means just what I choose it to mean—neither more nor less.” An item of data in memory can mean whatever you choose it to mean. A byte containing the value 70 is a perfectly good integer. It’s equally correct to regard as the code for the letter J.

    Let’s look at an example that should make it clear. Here, you’ll use the conversion specifier %c, which indicates that you want to output a value of type char as a character rather than an integer:

    /* Program 2.13 Characters and numbers */
    #include <stdio.h>
    void main()
    {
      char first = 'T';
      char second = 20;
      printf("\nThe first example as a letter looks like this -      %c", first);
      printf("\nThe first example as a number looks like this -      %d", first);
      printf("\nThe second example as a letter looks like this-      %c", second);
      printf("\nThe second example as a number looks like this-
          %d\n", second);
    }

    The output from this program is

    =======================================================
    The first example as a letter looks like this - T
    The first example as a number looks like this - 84
    The second example as a letter looks like this - ¶
    The second example as a number looks like this - 20

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

    HOW IT WORKS

    The program starts off by declaring two variables of type char:

     char first = 'T';
     char second = 20;

    One is initialized with a letter and the other with a number.

    The next four statements output each of the variables in two ways:

    printf("\nThe first example as a letter looks like this -     %c", first_example);
    printf("\nThe first example as a number looks like this - 
         %d", first_example);
    printf("\nThe second example as a letter looks like this -     %c", second_example);
    printf("\nThe second example as a number looks like this -     %d\n", second_example);

    The %c conversion specifier interprets the contents of the variable as a single character, and the % dspecifier interprets it as an integer. The numeric values that are output are the codes for the corresponding characters. These are ASCII codes in this instance, and will be in most instances, so that’s what you’ll assume throughout this book.

    As I’ve noted, not all computers use the ASCII character set, so you may get different values than those shown previously. As long as you use the notation 'character' for a character constant, you’ll get the character that you want regardless of the character coding in effect.

    You could also output the integer values of the variables of type char as hexadecimal values by using the format specifier %x instead of %d. You might like to try that.



    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

    Iron Speed




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