Home arrow C++ arrow Page 5 - First Steps in (C) Programming, introduction
C++

First Steps in (C) Programming, introduction


If you're a beginning programmer and want to get more deeply into programming with variables, you've come to the right place. This article, the first of three parts, is excerpted from chapter two of the book Beginning C, written by Ivor Horton (Apress, 2004; ISBN: 1590592530).

Author Info:
By: Apress Publishing
Rating: 3 stars3 stars3 stars3 stars3 stars / 10
November 17, 2005
TABLE OF CONTENTS:
  1. · First Steps in (C) Programming, introduction
  2. · What Is a Variable?
  3. · Variables That Store Numbers
  4. · Try It Out: Using More Variables
  5. · Naming Variables
  6. · Initializing Variables
  7. · Basic Arithmetic Operations
  8. · Try It Out: Division and the Modulus Operator

print this article
SEARCH DEVARTICLES

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.

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


blog comments powered by Disqus
C++ ARTICLES

- Intel Threading Building Blocks
- Threading Building Blocks with C++
- Video Memory Programming in Text Mode
- More Tricks to Gain Speed in Programming Con...
- Easy and Efficient Programming for Contests
- Preparing For Programming Contests
- Programming Contests: Why Bother?
- Polymorphism in C++
- Overview of Virtual Functions
- Inheritance in C++
- Extending the Basic Streams in C++
- Using Stringstreams in C++
- Custom Stream Manipulation in C++
- General Stream Manipulation in C++
- Serialize Your Class into Streams in C++

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 
Support 

Developer Shed Affiliates

 




© 2003-2017 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials