Data types and calculation


Data inside the machine

Basic data types

Again, to declare a variable we specify its data type and its name, and the basic data types are:

Assigning values to variables

There are many ways to assign values to variables,

Observing Variable Values

There are two ways of observing the data stored in variables: We will return to both approaches in much greater detail later, for the moment we will just use the printf command to print out data values we are interested in.

Literal forms of data

Literal forms of data are exact values written into the source code of our program - if we wish to change these values we have to actually edit (and recompile) our source code.

(Because of this, use of literal values is sometimes called "hardcoding" data - the data is fixed within the program, and not open to user modification.)

Some examples are given below.

   char  SomeCharacter;
   int   AnInteger;
   float ARealNumber;
  
   // hardcoding values
   ARealNumber = 17.7;
   AnInteger = -300;
   SomeCharacter = 'L';

   printf("%f", ARealNumber);    // prints out the value 17.7
   printf("%d", AnInteger);      // prints out the value -300
   printf("%c", SomeCharacter);  // prints out the character L

Note that C++ syntax requires the use of single quotes around character literals.

Constants and constant values

When literal values are used within a program (as shown above), it is strongly advisable to declare them as constants at the start of a program (or program section).

This assigns a name to the value, and that value is then used throughout the program to refer to that specific value.

For instance, suppose we wrote a program that used the value of Pi for a variety of calculations. We could create a constant that holds the value of Pi as follows:

   // example declaration of a constant
   const float Pi = 3.14;

   // sample uses of the constant
   printf( "The value of Pi is %f\n", Pi);

   float circleDiameter = 1.5;
   float circleCircumference = circleDiameter * Pi;
   printf( "For a circle with a diameter of %f ",\n", circleDiameter);
   printf( "    the cirumference is %f\n", circleCircumference);
The two main advantages to the use of constants are

  1. Readability - in many cases, for someone reading source code, a descriptive name is much clearer than a hard-coded value.

  2. Maintainability - if a program may eventually use the constant value in more than one place, we simply have to change the constant definition rather than having to search through the code for all the places where the value is used.

    For example, if we wanted to use 3.1415 as the value of Pi, we would only need to change the single line to
    const float Pi = 3.1415; rather than needing to search the code (and risk missing one or more instances).

Strings

Doing things one character at a time is irritating for storing names, sentences, etc (imagine having to have a different variable declared for every single character in a name or sentence...)

To get around this, a string literal can be used for output, and is denoted by a pair of double-quotes

C++ comes with a string library that defines a string data type, but its storage format is a little special, so we use a conversion routine called .c_str() to help printf extract the right text from it, e.g.
   #include <cstdio>
   #include <string>
   
   int main()
   {
      std::string msg = "Hello world!";
      printf("%s\n", msg.c_str());
      return 0;
   }

Basic calculations (*, +, -, /, %)

As much of computing involves the manipulation of data, the ability to perform fundamental calculations is very important.

Below we give examples of some basic arithmetic using a set of variables we will declare:

   int   x, y, z; // creates data storage for 3 integers
   float A, B, C; // creates data storage for 3 floating point numbers
  • data types on both sides of = must be same
    (int to int, real to real, char to char, etc)
  • EXCEPTION: <float var> = <int expression>;
    is legal e.g. A = x;

    Operators

    Operators are the symbols representing the kind of arithmetic to be performed (e.g. +, -, /, etc) or the kind of data manipulation taking place.

    Operator precedence and brackets

    The computer must understand what order operations are to be performed in, for instance if we were given the expression 12 - 3 - 1 we need to know whether this means 12 - (3 - 1) or (12 - 3) - 1

    The set of rules used to determine the order of operations is called operator precedence, and in C++ operates as follows:

    Variable and expression types

    Initializing variables

    int, float limitations

    Example program

    This program will let you experiment with the effect of truncation errors
    #include <cstdio>
    
    const float Pi = 3.1415;
    
    int main()
    {
        float v, w, x, y, z, goodsum, badsum;
    
        printf( "Enter 5 real numbers, ");
        printf( "from smallest to largest\n");
    
        scanf("%f", &v); scanf("%f", &w); scanf("%f", &x);
        scanf("%f", &y); scanf("%f", &z);
    
        goodsum = v + w + x + y + z;
        badsum = z + y + x + w + v;
    
        printf( "Adding them from smallest to largest");
        printf( " gives %f\n", goodsum);
        printf( "Adding from largest to smallest gives ");
        printf( "%f\n", badsum);
    }
    

    Shorthand for common operations

    There are a few special operators for things we do frequently:

    System constants

    Want to find out the largest and smallest numbers you can use on the system? This varies from system to system, and is worth knowing
    #include <cstdio>
    #include <climits>
    #include <cfloat>
    
    int main()
    {
       printf("The largest positive integer is ");
       printf("%d\n", INT_MAX);
    
       printf( "The smallest negative integer is ");
       printf("%d\n", INT_MIN);
    
       printf( "The largest real number is ");
       printf("%f\n", FLT_MAX);
    
       printf( "The smallest negative float is ");
       printf("%f\n", FLT_MIN);
    
       printf( The maximum precision (digits) is ");
       printf("%d\n", FLT_DIG);
    }
    

    Debugging and programming errors

    There are actually three different kind of errors:

    Spotting errors

    For each of the following programs, spot the flaws:

    1. Program 1
      / this program will calculate the area of a square
      
      #include <cstdio>
      
      int main()
      {
         int area;   / store calculated area of square
         int side;   / input length of side of square
      
         printf( "How wide is the square?" << endl;
         scanf("%d", &side);
      
         area = side * side;
      
         printf( "The square has area %area"\n);
      }
      

    2. Program 2
       // this program prints information about the author
      
      int main()
      
      
      {
          printf( 'This program was written by Dave Wessels');
          printf( 'He didn't do a great job of it, \N');
          printf( 'It won't even compile');
      }
      
      
      // this program calculates user age
      
      #include <cstdio>
      
      int main()
         int currentyear;
         int birthyear;
      
         printf(Enter the year you were born\n");
         scanf("%d", &birthyear);
      
         printf("Enter the current year \n); 
         scanf("%d", ¤tyear);
      
         age = currentyear - birthyear;
      
         prinf("This year you will be %i ", age, \n);
      }
      

    3. Program 3
       // this program gets the user to enter three 
       // integers and prints them out lined up on 
       // three separate lines, e.g.
       //         17
       //       1024
       //        206
      
      #include <cstdio>
      
      int main()
      {
         // variables for the three integers
         int firstint;  int secondint;  int thirdint;
      
         print( "Please enter three integers ";
         scanf("%d", firstint);
         scanf("%f", &secondint);
         scanf("%d" &thirdint);
      
         printf( "The three integers are:);
         printf( "%5d", firstint);
         printf( "%4d", secondint);
         printf( "%3d", thirdint);
      
         return 0;
      }
      

    4. Program 4
      // given the radius of a circle,
      // this program prints its circumference,
      // and prints its area to three decimal places
      
      #include <cstdio>
      
      const int Pi = 3.1415
      
      void mian()
      (
         int radius;        // input circle radius
         int circumference; // calculated circumference
         float area;        // calculated area
      
         printf( "Enter the integer radius of the circle");
         printf('\n');
         scanf("%d", &radius);
      
         circumference = 2 * radius * Pi;
         area = Pi * raduis * radius;
      
         printf( "The circumference is "circumference"\n", circumference);
         printf( ", the area is ");
         printf( "%8.2f\n", area);
      
      )
      

    5. Program 5
      #include <cstdio>
      const int DaysInYear=365;
      const int HoursInDay=24;
      const int MinutesInHour=60;
      const int SecondsInMinute=60;
      int main(){ int x;
      x=DaysInYear*HoursInDay*MinutesInHour*SecondsInMinute;
      printf("%d seconds in a year \n", x); }
      

    Type compatability, conversions


    Type compatability and automatic conversions

    Deliberate conversions - ints and floats

    Deliberate conversions - ints and chars