CyberiaPC.com Main Page




Learning C++

Manipulating Integer/Double Variables

Integers/Doubles are two popular number data types that are mostly used for counting, summing, averaging and other mathematical calculations.  There are many things you can do with numbers, especially when using them in conjunction with loops.  You probably already know the basics, so this section will teach you some cool stuff that you can do with these data types.

The first thing to note is that, unlike strings, integers don't require a specific library for them to function.

To avoid repetition, here is an example that uses integers for counting:

     #include <iostream.h>
     
     void main()
     {
          int counter=0;
          int user_input=0;
          
          cout << "Enter Max Number" << endl;
          cin >> user_input;
          
          for (counter; counter <= user_input; counter++)
          {
               cout << counter << endl;
          }
     }

What this code does is that it inputs a number from the user.  The For loop then keeps on executing until counter (which is 0) is less than or equal to the user input.  Each number is then displayed on its own line going from 0 up until the value entered by the user.  You'll see this example a lot, even in your own coding.  Counters are very important when it comes to programming and using loops in general.

You'll find that it is easy and fun exploring the world of integers, doubles and counters.  Therefore, to help you out with your journey, here are some tips for formatting your output.  Note that these are part of the iostream library so you must state the library at the top of your code.

Function Description Example
width() sets a specific width for a variable cout << 1234567890 << endl;

cout.width(10);
cout << 123 << endl;

cout.width(5);
cout << 456 << endl;

Displays:

1234567890
            123
     456

precision() sets the number of decimal places for a number double answer=2.32*4.77;

cout.precision(2);
cout << answer << endl;

Displays:

11.07 instead of 11.0664

setf() determines alignment of output.  Used in conjunction with width() to align output in its field.  The function accepts the following constants: left, right (default).  Note that if you want to change alignment from left to right, you'll have to unset the default left alignment with this line: cout.unsetf(ios::left); cout.setf(ios::left);
cout << 1234567890 << endl;

cout.width(10);
cout << 123 << endl;

cout.width(5);
cout << 456 << endl;

Displays:

1234567890
123
456

instead of:

1234567890
            123
     456

Note that the functions width() and precision() have to be entered before each output that is to be formatted.  On the other hand, setf() needs to be set only once.

{Go Back To C++ Lessons Page}