Courses/CS 2114/Lab Manual/Programming Errors, Variables and User Input

From A-State Computer Science Wiki
Jump to: navigation, search

Programming Errors, Variables and User Input

Introduction

This tutorial will introduce common programming errors, variable definitions, data types, assignment statements and user input.

Topics Covered in this Lab:

  • Generating common programming errors
  • Creating, storing, accessing variables
  • User input

Questions Answered in this Lab:

  • What does a compiler do with a program?
  • What are some of the common programming errors?
  • How does a computer program store and retrieve values?
  • How does a computer program get input from a user?

Demonstrable Skills Acquired in this Lab:

  • Ability to recognize common compiler errors
  • Familiarity with console input, specifically C++'s cin

Programming Errors

In computer programming there are three types of errors: syntax, logical, and run-time. Syntax errors are illegal uses of key words, operators, punctuation, and other programming constructs. These types of errors are found during compilation by the compiler. Typically, these errors are easy to identify and are generally just typos. Logical Errors, on the other hand, can be much harder to identify. These mistakes cause the program to produce erroneous results and are not caught by the compiler. The last type of error, run-time errors, are not evident until the program is run. These are usually logical errors, however, instead of just producing erroneous output they cause the program to crash. Like logical errors, run-time errors can be difficult to track down.

Common C++ Errors:

Error Type Error
Syntax Forgetting to quote strings
Syntax Forgetting to place a semicolon at the end of a statement
Syntax Using a variable before it has been declared
Semantic Using the assignment (=) operator instead of the equality (==) operator
Semantic Forgetting to place curly braces around the body of a control statement when the body contains more than one statement
Runtime Indexing an array "out-of-bounds"
Runtime Division by Zero

Compiler Errors

In this section, several different kinds of syntax errors will be introduced into the working program of the preceding sections. It is better to become familiar with errors in this manner than to encounter them for the first time when they have occurred by accident; at the close of this section, you may wish to experiment with other potential mistakes.

Important: The actual error messages that you see when you perform each step are likely to differ slightly from what is shown here. Different compilers (even different versions of the same compiler) will show error reports that are similar, but not exactly the same. Warning messages vary even more!

  1. Create a folder sp02 and copy the hello.cpp file from the sp01 folder.
  2. Edit the file hello.cpp (in the sp02 folder) and remove the semicolon from the end of the line beginning with cout.
  3. Save the file and compile it again.
  4. Consider the error messages that appear:
    hello.cpp: In function `int main()': 
    hello.cpp:32: error: expected `;' before "return" 
    

    Note that the compiler reports an error at the start of the line following the cout line. This is simply the first place that the compiler knew something was amiss. Since C++ is very flexible on formatting program code, the line (with correct code)

    cout << "Hello, World!\n";
    

    could have been entered as

            cout
    <<
                "Hello, World!\n"
        ;
    

    Try this to verify that the program behaves the same.

    The function main could also have been written

    int main () { cout << "Hello, World!\n"; return 0; }
    

    Try this as well. Now remove the semicolon following the cout statement. It is easy to see in this version why the compiler complains about the missing semicolon at the start of the word return. It is important to understand that the compiler sees the original version and the two succeeding variations above in exactly the same way: any number of carriage returns and blank spaces may be replaced by a single blank space. (An exception to the rule is spacing inside quotation marks, as the compiler wants to print exactly what it finds there.) Indentation and spacing help to make programs more readable for humans; a good first rule to follow is to indent three spaces inside each pair of curly braces.

  5. Correct the semicolon error above and then comment out the line beginning with using and examine the messages generated.
    hello.cpp: In function ‘int main()’:
    hello.cpp:30: error: ‘cout’ was not declared in this scope
    
  6. Correct the above error and then change the spelling of cout to cour and examine the messages generated.
    hello.cpp: In function `int main()': 
    hello.cpp:30: error: `cour' undeclared (first use this function) 
    hello.cpp:30: error: (Each undeclared identifier is reported only once for each function it appears in.)
    
  7. Correct the spelling error above and then remove the second " from the cout line and examine the messages generated.
    hello.cpp: In function `int main()': 
    hello.cpp:30: error: missing terminating " character 
    hello.cpp:32: error: expected primary-expression before "return" 
    hello.cpp:32: error: expected `;' before "return" 
    
  8. Correct the " error above and then remove the zero from the return line and examine the messages generated.
    hello.cpp: In function `int main()': 
    hello.cpp:32: error: return-statement with no value, in function returning 'int' 
    
  9. Correct the error above and then remove the ending } from the main function and examine the messages generated.
    hello.cpp: In function ‘int main()’:
    hello.cpp:32: error: expected `}' at end of input
    
  10. Correct the error above and then remove the parentheses following the word main and examine the messages generated.
    hello.cpp:28: error: function definition does not declare parameters
    


Using Computer Memory for Variables

Rules for Creating Legal Identifiers

Data can be stored in the computer's memory; variables are used to reference specific storage locations in memory. In C++, a variable must be defined before it can be used. When defining a variable, you should choose an identifier, or variable name, that describes the value it references. The rules for creating identifiers are:

  • The characters of an identifier must be alphanumeric (a-z, A-Z, 0-9) or the underscore (_).
  • The first character must not be a digit.
    • While the first character of an identifier can be an underscore (_), such identifiers often have special meaning in libraries; therefore, avoid beginning an identifier with an underscore.
  • An identifier cannot be a keyword.

In addition to the three rules above, it is worth noting that C++ is case-sensitive in all contexts; this means that the identifier studentcount is different than studentCount, for example.

Keywords

Keywords are words that have a predefined meaning to a programming language. The following is a list of C++ keywords as defined by the C++11 standard issued by ISO/IEC. Keywords marked with (1) were added in the C++11 standard, and those marked with (2) had their usage or meaning changed slightly between the C++98 and C++11 standards.

alignas (1)  catch         default (2)  float      noexcept (1) reinterpret_cast  this              virtual
alignof (1)  char          delete (2)   for        not          return            thread_local (1)  void        
and          char16_t (1)  do           friend     not_eq       short             throw             volatile
and_eq       char32_t (1)  double       goto       nullptr (1)  signed            true              wchar_t   
asm          class         dynamic_cast if         operator     sizeof            try               while 
auto (2)     compl         else         inline     or           static            typedef           xor     
bitand       const         enum         int        or_eq        static_assert (1) typeid            xor_eq     
bitor        const_cast    explicit     long       private      static_cast       typename                      
bool         constexpr (1) export (2)   mutable    protected    struct            union         
break        continue      extern       namespace  public       switch            unsigned               
case         decltype (1)  false        new        register     template          using (2)      


Data Types

Most data is either numerical or textual, but within the numerical category are numerous sub-categories. The basic data types of C++ are whole numbers (or integers), real numbers (or numbers containing decimals; also called floating-point numbers), the character (char) and boolean (bool). In the integer category reside the short, unsigned short, int, unsigned int, long and unsigned long. In the floating-point numbers, there are float, double, and long double. Refer to your text for the size of memory that will be reserved as well as the range of values that can be held for each of these types. Of the integers, we will use int most frequently; of the floating-point numbers, we will use the double most frequently. The character, or char, in C++ represents a single character, such as the letter A. A boolean value is either true or false.

Defining and Using a Variable

The C++ language requires the definition of a variable prior to its use. The syntax for defining a variable is

data_type_keyword identifier;

This requests that a location in memory which can hold a value the size of the specified data type be set aside and labeled as indicated; further, a value can be stored in this location using the assignment operator (=).

  1. Create a new file, named sp02t.cpp, in the sp02 folder and add the basic components of a program (as discussed in the last lab): comment block, #include and using, int main(),and return 0;. Do not forget the curly braces for the main function. Refer to the hello.cpp program, if necessary.
  2. Add the following line to the program in file sp02t.cpp to set aside an integer location, name it number1 and store the value 5 in this location; this line (and all additions to follow) should immediately precede the return 0 statement.
    Verbatimcode.pngCode Illustration

    CS2114VariableDeclarationWithAssignment.png

  3. This value can be displayed by adding the following cout statements to the program.
    Verbatimcode.pngCode Illustration

    CS2114Multple cout stmts.png

    Note that both literal character strings following cout are surrounded by quotation marks while the variable name is not. While the literal character strings display to the screen exactly as shown, the cout << number1; statement instructs the computer to retrieve the value stored in the memory location number1 and then display that value to the screen. (The multiple cout statements are used to demonstrate one way to write the code.)

  4. Compile and execute the program to see the value displayed.
  5. Add the following pair of lines to create a second variable and display its value; note that the redundant semicolons and couts are removed when displaying this second value. (The multiple cout statements can be combined into a single statement as shown here.)
    Verbatimcode.pngCode Illustration

    CS2114Single cout stmt.png

  6. Execute the program again.


Performing Computer Arithmetic

The C++ language contains arithmetic operators to calculate the following:

sum of an addition +
difference of a subtraction -
product of a multiplication *
quotient of an integer division /
remainder of an integer division     %
  1. Add the following to the program to perform an addition and display its result.
    Verbatimcode.pngCode Illustration

    CS2114Addition.png

    Note the use of two operators in the first line; addition has higher precedence than assignment, so number1 and number2 are added, after which their sum is assigned to sum1.

  2. Execute the program and verify that the result is correct.
  3. The result can be made even more meaningful if the operands are included in the display. Make the following changes to the program.
    Verbatimcode.pngCode Illustration

    CS2114MoreMeaningfulOutput.png

  4. Execute the program again.
  5. Add additional statements to examine the quotient of the two numbers.
    • Let quotient1 store the result when number1 is divided by number2.
    • Let quotient2 store the result when number2 is divided by number1.
    • Execute the program again and examine the results.


Reading from the Keyboard

As has been demonstrated, 'results' are written to the screen in C++ with cout ( console output). Information may be read from the keyboard with cin (console input).

  1. Begin by adding a second using statement for cin following that already in place for cout.
    Verbatimcode.pngCode Illustration

    CS2114 using cin.png

  2. Add the following sequence to the program to read an integer value from the keyboard.
    Verbatimcode.pngCode Illustration

    CS2114PromptAnd cin.png

    The stream extraction operator (>>) grabs the data from the stream on the left and stores it in the variable on the right.

    Whenever you need the user to provide data, be sure to include a cout statement to guide the user. Avoid writing code that will attempt to read data from the user without first identifying what the program requires.

  3. Execute the program.
  4. Add another sequence to read another value from the keyboard into a variable number4 and execute the program again.
  5. Add statements to the program to perform addition on the two values read from the keyboard and display the values along with the sum as demonstrated above.
  6. Add an additional sequence to the program to perform subtraction and multiplication on the same two values.

We have now seen the stream insertion operator (<<) as well as the stream extraction operator (>>). Notice that the stream insertion operator "points" toward the cout stream while the stream extraction operator "points" away from the cin stream and toward the variable that will hold the contents being extracted. The direction of the stream operator indicates the flow of the data.