Home arrow C++ arrow Page 6 - First Steps in (C) Programming, continued
C++

First Steps in (C) Programming, continued


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 second 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: 4 stars4 stars4 stars4 stars4 stars / 22
November 23, 2005
TABLE OF CONTENTS:
  1. · First Steps in (C) Programming, continued
  2. · Variables and Memory
  3. · Integer Constants
  4. · Floating-Point Variables
  5. · More on Format Specifiers
  6. · More Complex Expressions
  7. · Defining Constants
  8. · Try It Out: The Right Types of Variables

print this article
SEARCH DEVARTICLES

First Steps in (C) Programming, continued - More Complex Expressions
(Page 6 of 8 )

You know that arithmetic can get a lot more complicated than just dividing a couple of numbers. In fact, if that was all you were trying to do, then you may as well use paper and pencil. Now that you have the tools of addition, subtraction, multiplication, and division at your disposal, you can start to do some really heavy calculations.

For these more complicated calculations, youíll need more control over the sequence of operations when an expression is evaluated. Parentheses provide you with this capability. They can also help to make expressions clearer when theyíre getting intricate.

Parentheses in Arithmetic Expressions

You can use parentheses in arithmetic expressions, and they work much as youíd expect. Subexpressions contained within parentheses are evaluated in sequence from the innermost pair of parentheses to the outermost, with the normal rules that youíre used to for operator precedence, where multiplication and division happen before addition or subtraction. Therefore, the expression 2 * (3 + 3 * (5 + 4)) evaluates to 60. You start with the expression 5 + 4, which produces 9. Then you multiply that by 3, which gives 27. Then you add 3 to that total (giving 30) and multiply the whole lot by 2.

You can also insert spaces to separate operands from operators to make your arithmetic statements more readable. If youíre not quite sure of how an expression will be evaluated according to the precedence rules, you can always put in some parentheses to make sure it produces the result you want.

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

Try It Out: Arithmetic in Action

This time youíll have a go at calculating the circumference and area of a circular table from an input value for its diameter radius. You may remember from elementary math the equations to calculate the area and circumference of a circle using π or pi (circumference = 2πr and area = πr2, where r  is the radius). If you donít, then donít worry. This isnít a math book, so just look at how the program works.

This time youíll have a go at calculating the circumference and area of a circular table from an input value for its diameter radius. You may remember from elementary math the equations to calculate the area and circumference of a circle using πor pi (circumference = 2πr and area = πr, whereis the radius). If you donít, then donít worry. This isnít a math book, so just look at how the program works.

/* Program 2.8 calculations on a table */ #include <stdio.h>
void main()
{
  float radius = 0.0f;        /* The radius of the table  */
  float diameter = 0.0f;      /* The diameter of the table  */
  float circumference = 0.0f; /* The circumference of the table */
  float area = 0.0f;          /* The area of a circle      */
  float Pi = 3.14159265f;
 
printf("Input the diameter of the table:");
  scanf("%f", &diameter);     /* Read the diameter from the keyboard */
  radius = diameter/2.0f;     /* Calculate the radius    */
  circumference = 2.0f*Pi*radius; /*
Calculate the circumference    */
  area = Pi*radius*radius;    /* Calculate the area      */
  printf("\nThe circumference is %.2f", circumference);
  printf("nThe area is %.2f\n", area);
}

Hereís some typical output from this example:

--------------------------------------------
Input the diameter of the table: 6
The circumference is 18.85
The area is 28.27
--------------------------------------------

HOW IT WORKS

Up to the firstprintf()the program looks much the same as those youíve seen before:

float radius = 0.0f;   /* The radius of the table   */
float diameter = 0.0f; /* The diameter of the table  */
float circumference = 0.0f;  /* The circumference of the table */
float area = 0.0f;     /* The area of a circle     */
float Pi = 3.14159265f;

You declare and initialize five variables, wherePihas its usual value. Note how all the initial values have anfat the end because youíre initializing values of typefloat. Without thefthe values would be of typedouble. They would still work here, but you would be introducing some unnecessary conversion that the compiler would have to arrange, from typedoubleto typefloat.

The following statement outputs a prompt for input from the keyboard:

printf("Input the diameter of the table:");

The next statement deals with reading the value for the diameter of the table. You use a new standard library function, thescanf()function, to do this:

scanf("%f", &diameter);      /* Read the diameter from the keyboard */

Thescanf()function is another function that requires thestdio.hheader file to be included. This function handles input from the keyboard. In effect it takes what you enter through the keyboard and interprets it as specified by the first argument, which is a control string between double quotes. In this case the control string is"%f"because youíre reading a value of typefloat. It stores the result in the variable specified by the second argument,diameterin this instance. The first argument is a control string similar to what youíve used with theprintf()function, except that here it controls input rather than output.

Youíve undoubtedly noticed something new here: the&preceding the variable namediameter. This is called the address of operator, and itís needed to allow thescanf()function to store the value that is read in your variable,diameter. The reason for this is bound up with the way argument values are passed to a function. For the moment, I wonít go into a more detailed explanation of this; youíll see more on this in Chapter 11. The only thing to remember is to use the address of operator (the&sign) before a variable when youíre using thescanf()function, and not to use it when you use theprintf()function.

Youíll see a lot more on howscanf()works later in the book, but for now the basic set of format specifiers you can use for reading data of various types are as follows:

To read a value of type short

%hd

To read a value of type int

%d

To read a value of type long

%ld

To read a value of type float

%f or %e

To read a value of type double

%lf or %le

In the%ldand%lfformat specifiers,lis a lowercaseL. Donít forget, you must always prefix the name of the variable thatís receiving the input value with&. Also, if you use the wrong format specifieróif you read a value into a variable of typefloatwith%d, for instanceóthe data value in your variable wonít be correct, but youíll get no indication that a junk value has been stored.

Next, you have three statements that calculate the results youíre interested in:

radius = diameter/2.0f;   /* Calculate the radius   */
circumference = 2.0f*Pi*radius; /* Calculate the circumference   */
area = Pi*radius*radius; /* Calculate the area   */

 The first statement calculates the radius as half of the value of the diameter that was entered. The second statement computes the circumference of the table, using the value that was calculated for the radius. The third statement calculates the area. Note that if you forget thefin2.0f, youíll probably get a warning message from your compiler. This is because without thef, the constant is of typedouble, and you would be mixing different types in the same expression. Youíll see more about this later.

The next two statements output the values youíve calculated:

printf("\nThe circumference is %.2f", circumference);
printf("\nThe area is %.2f\n", area);

These twoprintf()statements output the values of the variablescircumferenceandareausing the format specifier%.2f. As youíve already seen, in both statements the format control string contains text to be displayed, as well as a format specifier for the variable to be output. The format specification outputs the values with two decimal places after the point. The default field width will be sufficient in each case to accommodate the value that is to be displayed.

Of course, you can run this program and enter whatever values you want for the diameter. You could experiment with different forms of floating-point input here, and you could try entering something like1E1f, for example.

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


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