Code Examples
  Home arrow Code Examples arrow Page 4 - 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 
Mobile Linux 
App Generation ROI 
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 / 60
    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


    First Steps in Programming - Basic Arithmetic Operations


    (Page 4 of 13 )

    In C, an arithmetic statement is of the following form:

     Variable_Name = Arithmetic_Expression;

    The arithmetic expression on the right of the=operator specifies a calculation using values stored in variables and/or explicit numbers that are combined using arithmetic operators such as addition (+), subtraction (-), multiplication (*), and division (/). There are also other operators, as you’ll see.

    In the previous example, the arithmetic statement was

     Total_Pets = Cats + Dogs + Ponies + Others;

    The effect of this statement is to calculate the value of the arithmetic expression to the right of the=and store that value in the variable specified on the left.

    In C, the=symbol defines an action. It doesn’t specify that the two sides are equal, as it does in mathematics. It specifies that the value resulting from the expression on the right is to be stored in the variable on the left. This means that you could have

     Total_Pets = Total_Pets + 2;

    This would be ridiculous as a mathematical equation, but in programming it’s fine. Let’s look at it in context. Imagine you’d rewritten the last part of the program to include the preceding statement. Here’s a fragment of the program as it would appear with the statement added:

     Total_Pets = Cats + Dogs + Ponies + Others;     /* Value
         stored is 50 */
     Total_Pets = Total_Pets + 2;                    /* Value
         stored is 52 */
     printf("The total number of pets is: %d", Total_Pets);

    After executing the first statement here, Total_Pets contains the value 50. Then, in the second line, you add 2 to that value and store the result back in the variable Total_Pets. The final total that will be displayed is therefore 52.


    NOTE In assignment operations, the expression on the right side of the=sign is evaluated first, and the result is then stored in the variable on the left. The new value replaces the value that was previously contained in the variable to the left of the assignment operator.


    Any expression that results in a numeric value is described as an arithmetic expression. The following are all arithmetic expressions:

     3
     1+2
     Total_Pets
     Cats + Dogs - Ponies

    Evaluating any of these expressions produces a single numeric value. In a moment, you’ll take a closer look at how an expression is made up, and you’ll look into the rules governing its evaluation. First, though, you’ll try some simple examples using the basic arithmetic operators that you have at your disposal. Table 2-1 shows these operators.

    Table 2-1. Basic Arithmetic Operators

    OperatorAction
    +Addition
    -Subtraction
    *Multiplication
    /Division
    %Modulus


    You may not have come across the modulus operator before. It just calculates the remainder after dividing the value of the expression on the left of the operator by the value of the expression on the right. For this reason it’s sometimes referred to as the remainder operator. The expression 12%5 would produce 2, because 12 divided by 5 leaves a remainder of 2. You’ll look at this in more detail shortly. All these operators work as you’d expect with the exception of division, which has a slight aberration from the norm when applied to integers, as you’ll see. Let’s try some more arithmetic operations.


    Try It Out: Subtraction and Multiplication

    Let’s look at a food-based program that demonstrates subtraction and multiplication:

    /* Program 2.5 Calculations with cookies */
    #include <stdio.h>
    void main()
    {
      int cookies = 5;
      int cookie_calories = 125;    /* Calories per cookie */
      int total_eaten = 0;          /* Total cookies eaten */
      int eaten = 2;                /* Number to be eaten */
      cookies = cookies - eaten;    /* Subtract number eaten
         from cookies */
      total_eaten = total_eaten + eaten;
      printf("\nI have eaten %d cookies. There are %d cookies
         left",eaten, cookies);
      eaten = 3;                    /* New value for cookies 
         to be eaten  */
      cookies = cookies - eaten;    /* Subtract number eaten 
         from cookies */
      total_eaten = total_eaten + eaten;
      printf("\nI have eaten %d more. Now there are %d cookies
         left\n", eaten, cookies);
      printf("\nTotal energy consumed is %d calories.\n",
         total_eaten*cookie_calories);
    }

    This program produces the following output:

    ======================================================= I have eaten 2 cookies. There are 3 cookies left
    I have eaten three more. Now there are 0 cookies left

    Total energy consumed is 625 calories
    =====================================================

    HOW IT WORKS

    You first declare and initialize three variables of type int:

     int cookies = 5;
     int cookie_calories = 125;      /* Calories per cookie */
     int total_eaten = 0;            /* Total cookies eaten */

    You’ll use the total_eaten variable to accumulate the total number of cookies eaten as execution of the program progresses, so you initialize it to 0.

    The next variable that you declare and initialize holds the number of cookies to be eaten next:

     int eaten = 2;                  /* Number to be eaten */

    You use the subtraction operator to subtract eaten from the value of cookies:

     cookies = cookies - eaten;      /* Subtract number eaten
         from cookies */

    The result of the subtraction is stored back in the variable cookies, so the value of cookies will now be 5 – 2, which is 3.

    Because you’ve eaten some cookies, you increment the count of the total eaten by the value of eaten:

     total_eaten = total_eaten + eaten;

    You add the current value of eaten, which is 2, to the current value of total_eaten, which is 0. The result, 2, is stored back in the variable total_eaten.

    The printf() statement displays the number of cookies that are left:

     printf("\nI have eaten %d cookies. There are %d cookies
         left", eaten, cookies);

    I couldn’t fit the statement in the space available, so after the comma following the first argument to printf(), I put the rest of the statement on a new line. You can spread statements out like this to make them easier to read or fit within a given width on the screen.

    Note that you could not split the string that is the first argument in this way. An explicit newline character isn’t allowed in the middle of a string. When you need to split a string over two or more lines, each segment of the string on a line must have its own pair of double quotes delimiting it. For example, you could write the previous statement as follows:

     printf("\nI have eaten %d cookies. "
                  There are %d cookies left",
                                               eaten, cookies);

    Where there are two or more strings immediately following one another like this, the compiler will join them together to form a single string.

    You display the values stored in eaten and cookies using the conversion specifier,%d, for integer values. The value of eaten will replace the first %d in the output string, and the value of cookies will replace the second. The string will be displayed starting on a new line because of the \n at the beginning.

    The next statement sets the variable eaten to a new value:

     eaten = 3;         /* New value for cookies to be eaten */

    The new value, 3, replaces the previous value stored in eaten, which was 2. You then go through the same sequence of operations as you did before:

     cookies = cookies - eaten;    /* Subtract number eaten  
         from cookies */
     total_eaten = total_eaten + eaten;
     printf("\nI have eaten %d more.  Now there are %d
         cookies left\n",

    Finally, you calculate and output the number of calories corresponding to the number of cookies eaten:

     printf("\nTotal energy consumed is %d calories.\n", 
                                  total_eaten*cookie_calories);

    Here the second argument to the printf() function is an arithmetic expression rather than just a variable. The compiler will arrange for the result of the expression total_eaten*cookie_calories to be stored in a temporary variable, and that value will be passed as the second argument to the printf() function. You can always use an expression for an argument to a function as long as it evaluates to a result of the required type.

    Easy, isn’t it? Let’s take a look at division and the modulus operator.



    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
    Stay green...Green IT