Home arrow C++ arrow Page 7 - 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 - Basic Arithmetic Operations
(Page 7 of 8 )

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_Petscontains the value 50. Then, in the second line, you add 2 to that value and store the result back in the variableTotal_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

Operator +

Action 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 typeint:

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

Youíll use thetotal_eatenvariable 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 subtracteatenfrom the value ofcookies:

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

The result of the subtraction is stored back in the variablecookies, 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 ofeaten:

total_eaten = total_eaten + eaten;

You add the current value ofeaten, which is 2, to the current value oftotal_eaten, which is 0. The result, 2, is stored back in the variabletotal_eaten.

Theprintf()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 toprintf(), 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 ineaten andcookies using the conversion specifier,%d, for integer values. The value ofeatenwill replace the first%din the output string, and the value ofcookieswill replace the second. The string will be displayed starting on a new line because of the\nat the beginning.

The next statement sets the variableeatento a new value:

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

The new value, 3, replaces the previous value stored ineaten, 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",
              eaten, cookies);

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 theprintf()function is an arithmetic expression rather than just a variable. The compiler will arrange for the result of the       expressiontotal_eaten*cookie_caloriesto be stored in a temporary variable, and that value will be passed as the second argument to theprintf()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.

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

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


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