C++
  Home arrow C++ arrow Page 5 - First Steps in (C) Programming, introducti...
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Moblin 
JMSL Numerical Library 
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? 
C++

First Steps in (C) Programming, introduction
By: Apress Publishing
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 3 stars3 stars3 stars3 stars3 stars / 5
    2005-11-17

    Table of Contents:
  • First Steps in (C) Programming, introduction
  • What Is a Variable?
  • Variables That Store Numbers
  • Try It Out: Using More Variables
  • Naming Variables
  • Initializing Variables
  • Basic Arithmetic Operations
  • Try It Out: Division and the Modulus Operator

  • 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 (C) Programming, introduction - Naming Variables


    (Page 5 of 8 )

    The name that you give to a variable, conveniently referred to as a variable name, can be defined with some flexibility. A variable name is a string of one or more letters, digits, and underscore characters (_) that begins with a letter (incidentally, the underscore character counts as a letter). Examples of good variable names are as follows:

    Radius
    diameter
    Auntie_May
    Knotted_Wool
    D666

    Because a name can’t begin with a digit,8_Balland6_packaren’t legal names. A variable name can’t include any other characters besides letters, underscores, and digits, soHash!andMary-Louaren’t allowed as names. This last example is a common mistake, butMary_Louwould be quite acceptable. Because spaces aren’t allowed in a name,Mary Louwould be interpreted as two variable names,MaryandLou. Variables starting with one or two underscore characters are often used in the header files, so don’t use the underscore as the first letter when naming your variables; otherwise, you run the risk of your name clashing with the name of a variable used in the standard library. For example, names such as_thisand_thatare best avoided.

    Although you can call variables whatever you want within the preceding constraints, it’s worth calling them something that gives you a clue to what they contain. Assigning the namexto a variable that stores a salary isn’t very helpful. It would be far better to call itsalaryand leave no one in any doubt as to what it is.


    CAUTION 
    The number of characters that you can have in a variable name will depend upon your compiler. Up to 31 characters are generally supported, so you can always use names up to this length without any problems. I suggest that you don’t make your variable names longer than this anyway, as they become cumbersome and make the code harder to follow. Some compilers will just truncate names that are too long.

    Another very important point to remember when naming your variables is that C is case sensitive, which means that the namesDemocratanddemocrat are completely different. You can demonstrate this by changing theprintf()statement so that one of the variable names starts with a capital letter, as follows:

    /* Program 2.3 Using more variables */ #include <stdio.h>
    void main()
    {
      int brothers;          /* Declare a variable called brothers */
     
    int brides;            /* and a variable called brides     */
     
    brothers = 7;          /* Store 7 in the variable brothers  */
      brides = 7;            /* Store 7 in the variable brides    */
     
    /* Display some output */
      printf("%d brides for %d brothers", Brides, brothers);
    }

    You’ll get an error message when you try to compile this version of the program. The compiler interprets the two variable namesbridesandBrides as different, so it doesn’t understand whatBridesrefers to. This is a common error. As I’ve said before, punctuation and spelling mistakes are one of the main causes of trivial errors.

    Using Variables

    You now know how to name and declare your variables, but so far this hasn’t been much more useful than anything you learned in Chapter 1. Let’s try another program in which you’ll use the values in the variables before you produce the output.

    ..........................................................................................

    Try It Out: Doing a Simple Calculation

    This program does a simple calculation using the values of the variables:

    /* Program 2.4 Simple calculations */
    #include <stdio.h>
    void main()
    {
       int Total_Pets;       /* The total number of pets        */
       int Cats;             /* The number of cats as pets   */
       int Dogs;             /* The number of dogs as pets   */
      
    int Ponies;           /* The number of ponies as pets */
       int Others;           /* The number of other pets     */
      
    /* Set the number of each kind of pet */ 
       Cats = 2;
       Dogs = 1;
       Ponies = 1;
       Others = 46;
      
    /* Calculate the total number of pets */ 
       Total_Pets = Cats + Dogs + Ponies + Others;
      
    printf("We have %d pets in total", Total_Pets); /* Output the result */
    }

    This example produces the output

    --------------------------------------------
    We have 50 pets in total
    --------------------------------------------

    HOW IT WORKS

    As in the previous examples, all the statements between the braces are indented by the same amount. This makes it clear that all these statements belong together. You should always organize your programs the way you see here: indent a group of statements that lie between an opening and closing brace by the same amount. It makes your programs much easier to read.

    You first define five variables of typeint:

    int Total_Pets;         /* The total number of pets      */
    int Cats;               /* The number of cats as pets */
    int Dogs;               /* The number of dogs as pets */
    int Ponies;             /* The number of ponies as pets */
    int Others;             /* The number of other pets   */

    Because each of these variables will be used to store a count of a number of animals, it’s definitely going to be a whole number. As you can see, they’re all declared as typeint.

    Note that you could have declared all five variables in a single statement and included the comments, as follows:

    int Total_Pets,          /* The total number of pets        */
        Cats,                /* The number of cats as pets   */
        Dogs,                /* The number of dogs as pets   */
        Ponies,              /* The number of ponies as pets */
        Others;              /* The number of other pets     */

    The statement is spread over several lines so that you can add the comments in an orderly fashion. Notice that there are commas separating each of the variable names. Because the comments are ignored by the compiler, this is exactly the same as the following statement:

    int Total_Pets, Cats, Dogs, Ponies, Others;

    You can spread C statements over as many lines as you want. The semicolon determines the end of the statement, not the end of the line.

    Now back to the program. The variables are given specific values in these four assignment statements:

    Cats = 2;
    Dogs = 1;
    Ponies = 1;
    Others = 46;

    At this point the variableTotal_Petsdoesn’t have an explicit value set. It will get its value as a result of the calculation using the other variables:

    Total_Pets = Cats + Dogs + Ponies + Others;

    In this arithmetic statement, you calculate the sum of all your pets on the right of the assignment operator by adding the values of each of the variables together. This total value is then stored in the variableTotal_Petsthat appears on the left of the assignment operator. The new value replaces any old value that was stored in the variableTotal_Pets.

    Theprintf()statement shows the result of the calculation by displaying the value ofTotal_Pets:

    printf("We have %d pets in total", Total_Pets);

    Try changing the numbers of some of the types of animals, or maybe add some more of your own. Remember to declare them, initialize their value, and include them in theTotal_Petsstatement.

    ..........................................................................................

    More C++ Articles
    More By Apress Publishing


       · This article is an excerpt from the book "Beginning C," published by Apress. We hope...
       · Worthwhile reading for the beginner. BUT... I'm torn between praising the publishing...
       · Lol! Yes, I understand your ambivalence about it being a marketing ploy. On the...
       · That's a good idea. We tend to forget that C is still very capable and popular....
       · Thank you Pantaz! I'm glad you liked the article, and we'll keep your suggestion in...
     

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

    C++ ARTICLES

    - Multiplying Large Numbers with Karatsuba`s A...
    - Large Numbers
    - Dijkstra`s Shunting Algorithm with STL and C...
    - Brief Introduction to the STL Containers
    - The Standard Template Library
    - Templates in C++
    - C++ Programmer Alerts
    - C++ Programming Tips
    - First Steps in (C) Programming, conclusion
    - First Steps in (C) Programming, continued
    - First Steps in (C) Programming, introduction
    - C++ Preprocessor: Always Assert Your Code Is...
    - C++ Preprocessor: The Code in the Middle
    - Programming in C
    - Temporary Variables: Runtime rvalue Detection






    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 5 hosted by Hostway
    Stay green...Green IT