Home arrow Practices arrow Page 4 - Basic Data Types and Calculations

Try It Out: Fixing the Appearance of the Output - Practices

This article looks at some of the basic data types that are built into C++. If you're learning how to use C++, you will want to keep reading, since you'll be using these data types in all of your programs. It is taken from chapter two of the book Beginning ANSI C++: The Complete Language, by Ivor Horton (Apress, 2004; ISBN: 1590592271).

TABLE OF CONTENTS:
  1. Basic Data Types and Calculations
  2. Performing Simple Calculations
  3. Try It Out: Integer Arithmetic in Action
  4. Try It Out: Fixing the Appearance of the Output
  5. Try It Out: Using Integer Variables
  6. The Assignment Operator
  7. Incrementing and Decrementing Integers
  8. Numerical Functions for Integers
  9. Floating-Point Operations
  10. Try It Out: Floating-Point Arithmetic
  11. Try It Out: Yet More Output Manipulators
  12. Working with Characters
  13. Functional Notation for Initial Values
  14. Exercises
By: Apress Publishing
Rating: starstarstarstarstar / 14
September 08, 2005

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

Although it may not appear so, the output from the previous example is right justified. The ďragged rightĒ appearance is due to the fact that the output for each integer is in a field width thatís exactly the correct number of characters to accommodate the value. You can make the output look tidier by setting the field width for each data item to a value of your choice, as follows:

Although it may not appear so, the output from the previous example is right justified. The ďragged rightĒ appearance is due to the fact that the output for each integer is in a thatís exactly the correct number of characters to accommodate the value. You can make the output look tidier by setting the field width for each data item to a value of your choice, as follows:

// Program 2.1A - Producing neat output
#include// For output to the screen
#include// For manipulators
using std::cout;
using std::endl;
using std::setw;

int main()
{
cout << setw(10) << 10 + 20 << endl; // Output is  30
cout << setw(10) << 10 - 5  << endl; // Output is   5
cout << setw(10) << 10 - 20 << endl; // Output is -10

cout << setw(10) << 10 * 20 << endl; // Output is 200
cout << setw(10) << 10/3    << endl; // Output is   3
cout << setw(10) << 10 % 3  << endl; // Output is   1
cout << setw(10) << 10 % -3 << endl; // Output is   1
cout << setw(10) << -10 % 3 << endl; // Output is  -1
cout << setw(10) << -10 % -3<< endl; // Output is  -1
cout << setw(10) << 10 + 20/10 - 5     << endl; // Output is  7
cout << setw(10) << (10 + 20)/(10 - 5) << endl; // Output is  6

cout << setw(10) << 10 + 20/(10 - 5)   << endl; // Output is 14
cout << setw(10) << (10 + 20)/10 - 5   << endl; // Output is -2
cout << setw(10) << 4*5/3%4 + 7/3      << endl; // Output is  4
return 0;                               // End the program
}

Now the output looks like this:


 

       30 
        5
      -10
      200
        3
        1
        1
       -1
       -1
        7
        6
       14
       -2
        4
 

 


 

 

 

HOW IT WORKS

Thatís much nicer, isnít it? The tidy formatting is accomplished by the changes to the output statements. Each value to be displayed is preceded in the output bysetw(10), as in the first statement:

cout << setw(10) << 10 + 20     << endl; // Output is 30

setw()is called a manipulator because it enables you to manipulate, or control, the appearance of the output. A manipulator doesnít output anything; it just modifies the output process. Its effect is to set the field width for the next value to be output to the number of characters that you specify between the parentheses, which is 10 in this case. The field width that you set by usingsetw()only applies to the next value that is written tocout. Subsequent values will be presented in the default manner.

The additional#includestatement for the standard header <iomanip>is necessary to make thesetw()manipulator available in your program. Iíve also added ausingdeclaration so you can use thesetwname unqualified. There are other manipulators that youíll try out in other examples as you go along. Meanwhile, you can try out this example with different field widths to see their effect.

Using Variables

Calculating with integer constants is all very well, but you were undoubtedly expecting a bit more sophistication in your C++ programs than that. To do more, you need to be able to store data items in a program, and this facility is provided by variables. A variable is an area in memory thatís identified by a name that you supply and that you can use to store an item of data of a particular type. Specifying a variable therefore requires two things: you must give it a name, and you must identify what kind of data you propose to store in it. First of all, letís consider what options you have for defining variable names.

Calculating with integer constants is all very well, but you were undoubtedly expecting a bit more sophistication in your C++ programs than that. To do more, you need to be able to store data items in a program, and this facility is provided by variables. A is an area in memory thatís identified by a name that you supply and that you can use to store an item of data of a particular type. Specifying a variable therefore requires two things: you must give it a name, and you must identify what kind of data you propose to store in it. First of all, letís consider what options you have for defining variable names. Variable Names

As you saw in Chapter 1, the name that you give to a variable can consist of any combination of upper- or lowercase letters, underscores, and the digits 0 to 9, but it must begin with a letter or an underscore. As I said in Chapter 1, the ANSI standard says that a variable name can also include UCS characters, and although you could use this in defining your variable names, itís there to allow compilers to accommodate the use of national language characters that arenít in the basic set of upper- and lowercase letters ( A to Z).

Donít forget, you must not express any character from the basic source character set as a UCS character. All characters from the basic source character set must appear as their explicit character representation.

You saw some examples of valid variable names in Chapter 1, but here are a few more:

value   monthlySalary   eight_ball   FIXED_VALUE   JimBob

Just to remind you of what I said in Chapter 1, a variable name canít begin with a digit, so names such as8balland7Uparenít valid. Also, because C++ is a case-sensitive language,republicanandRepublicanare different names. You shouldnít use variable names that begin with an underscore followed by a capital letter or that contain two successive underscores, as names of these forms are reserved for use within the standard libraries.

Generally, the names that you invent for your variables should be indicative of the kind of data that they hold. For instance, a name such asshoe_sizeis going to mean a whole lot more thanssóalways assuming youíre dealing with shoe sizes, of course. Youíll find that you often want to use names that combine two or more words to make your program more understandable. One common approach for doing this uses the underscore character to link words in a single, for example:

line_count   pay_rise   current_debt

A convention thatís frequently adopted in C++ is to reserve names that begin with a capital letter for naming classes, which are user-defined types. Youíll learn how to define your own data types in Chapter 11. With this approach to names,Point,Person, andProgramare all immediately recognizable as user-defined types and not variables. Of course, youíre free to assign any names that you want (as long as they arenít keywords), but if you choose names that are meaningful and name your variables in a consistent manner, it will make your programs more readable and less error-prone. Appendix B contains a list of all the C++ keywords.

Integer Variables

Suppose you want to use a variable to record how many apples you have. You can create a variable with the name apples by means of a declaration statement for the variable, as shown in Figure 2-2.

by means of a for the variable, as shown in Figure 2-2.apples by means of a for the variable, as shown in Figure 2-2.Suppose you want to use a variable to record how many apples you have. You can create a variable with the name apples by means of a for the variable, as shown in Figure 2-2.

 
Figure 2-2.   A variable declaration

The statement in Figure 2-2 is described as a declaration because it declares the nameapples. Any statement that introduces a name into your program is a declaration for that name. The statement in the illustration is also called a definition, because it causes memory to be allocated for the variableapples. Later, youíll meet statements that are declarations but are not definitions. A variable is created by its definition, so you can only refer to it after the definition statement. If you attempt to refer to a variable prior to its definition, youíll get an error message from the compiler.

When you define a variable, you can also specify an initial value. For example,

int apples = 10; // Definition for the variable apples

defines the variable calledapplesand sets its initial value as10. The definition in the diagram had no initial value specified, so the memory assigned to the variable would contain whatever junk value was left over from previous use of the memory. Having junk values floating around in your program is a bad idea, and this leads to our first golden rule.

GOLDEN RULE Always initialize your variables when you define them. If you don't know what value a variable should have when you define it, initialize it to zero.

You can use variables as operands of the arithmetic operators youíve seen in exactly the same way as youíve used literals. The value of the variable will be the operand value. If you apply the unary minus operator to a variable, the result is a value that has the opposite sign of the value of the variable, but the same magnitude. This doesnít change the value stored in the variable, though. Youíll see how to do that very soon.

Letís try out some integer variables in a little program.



 
 
>>> More Practices Articles          >>> More By Apress Publishing
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PRACTICES ARTICLES

- Calculating Development Project Costs
- More Techniques for Finding Things
- Finding Things
- Finishing the System`s Outlines
- The System in So Many Words
- Basic Data Types and Calculations
- What`s the Address? Pointers
- Design with ArgoUML
- Pragmatic Guidelines: Diagrams That Work
- Five-Step UML: OOAD for Short Attention Span...
- Five-Step UML: OOAD for Short Attention Span...
- Introducing UML: Object-Oriented Analysis an...
- Class and Object Diagrams
- Class Relationships
- Classes

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: