C++ 13 Review Questions

profilegina123
c_basics.pdf

C++ BASCIS

Please note that the material on this website is not intended to be exhaustive. This is intended as a summary and supplementary material to required textbook.

INTRODUCTION

As all languages have a grammar, a description of what counts as a "well-formed" sentence, so does C++. This module explains some of the basic syntax, or grammar, of C++. A compiler is a tool that translates C++ code into instructions the computer hardware understands.

COMMENTS

Comments are entirely ignored by the compiler, so you can put anything you want in them. One way to add a comment is to use // which indicates that the rest of the line is a comment:

EXAMPLE: ... // the rest of this line is a comment

Alternatively, multiple lines can be comments using the /* ... */ notation:

EXAMPLE: /* . . . all of this text is a comment and is entirely ignored by the compiler . . . */

In addition, the compiler ignores blank lines. For the most part, the compiler also ignores spaces and indentations (tabs).

A very simple C++ program will look something like the following:

EXAMPLE: // The purpose of this program is to illustrate how a C++ program is constructed

#include <iostream>; using namespace std;

// the main () routine is where the program begins // execution

int main () { cout << "Hello World!" << endl; return 0; }

This program begins with a comment; indeed, every program should begin with a comment explaining its basic

purpose. Good software design principles require comments liberally placed throughout the code. This example also has a comment before the main routine. The entire main ( ) routine is contained within curly braces, { and }, which delimit the body of the main routine in a block.

INCLUDE DIRECTIVES

The purpose of include directives is to allow the programmer to take advantage of the many facilities that have already been coded, compiled, and tested. The definitions of cout and endl are in the <iostream> include file (often called a header file). If you leave out the include <iostream> statement, this simple program will not compile.

The include files do not contain compiled code; rather, they contain the C++ definitions of various terms. The compiled code for the items defined in a header file is in libraries.

The using namespace std; is also necessary. For now, we will think of a namespace as akin to a dictionary, with the definition of various terms listed in the namespace (called std).

When a program is compiled, before the compiler begins its work, a preprocessor reads into the file all of the contents of the files named in the include statements. Most compilers are two-pass compilers; that is, after the preprocessor has run the compiler makes two passes through the code: once to check the syntax, and if the syntax passes, the second pass produces the object code.

The linker is responsible for combining the object code with the libraries of routines defined in the include files to produce a program that is executable. An executable program still has to be loaded into memory to be run, and the loader is responsible for this.

MAIN ROUTINE

The main ( ) routine is where the program begins execution, once the executable is loaded into memory. A simple main routine may only be responsible for obtaining input to the program, processing the input, and producing the output. More complicated main routines are more like traffic directors, defining the route the program must traverse in order to accomplish its objective. The main routine is defined within a block of code contained within curly braces.

The int main ( ) part is the header of the main routine, and it merely says that main is a function (i.e., the ( ) part), and it returns an integer value when it exits. The main routine in the example above returns 0 when it exits (i.e., the return 0; part).

Within a block of code every line is a statement or a comment. A statement is a syntactically correct sentence of C++. All statements are terminated with a semicolon (;). Normally, only one statement is written on a single line, but you may put multiple statements on a single line. You may also have statements that require several lines in a file. An essential characteristic of a statement is that it ends with a semicolon. In the example above there are two statements: one beginning with cout and ending with a semicolon, and one beginning with return and ending with a semicolon. Note especially that blocks of code do not end with a semicolon; they end with a close curly brace.

INPUT AND OUTPUT>

Most programs require input and most programs produce output. Sometimes the only output from a program

indicates that an error occurred (this is called error output).

For now all input will be done using the cin facility (see below), and all output will be done by using the cout facility. Both of these facilities are defined in the <iostream> header file.

In the example above, the program outputs the text contained between the double quotes, i.e., the string Hello World!. The endl causes the end of the line to be a newline, which moves the cursor in the output window to a new line. Both of these items are separated with an operator: <<.

Thus the cout line in the example first outputs the string Hello World!, followed by a newline.

A prompt is an output statement that solicits input from the user of the program. Typically these are strings that are not followed by an endl.

EXAMPLE: cout << "Enter the name of the file to open => "; cout << "Enter Y for yes or N for no => ";

WRITING YOUR FIRST C++ PROGRAM

Your first program will be the example shown above.

SYNTAX, SEMANTICS, and METALANGUAGE

In order to fully describe the C++ language, we must explain how to form syntactically correct statements using the facilities of the language. Next, we must describe what the different statements of the language mean, i.e., the semantics of the facility. Our description of the facilities of C++ is carried out in yet another language, English, which is our metalanguage, i.e., the language we use to describe another language: C++.

VARIABLES AND CONSTANTS; ASSIGNMENT

Variables and constants are specified in C++ by means of declarations. Each declaration names a variable or constant and indicates how it will be used, its type. The name of a variable or constant is called an identifier. Identifiers must be formed according to the following rules: all identifiers consist of the following letters and only the following letters (note that a space is not included):

A, B, C, D, ..., Z (upper case alphas)

a, b, c, d, ..., z (lower case alphas)

0, 1, 2, 3, ..., 9 (digits)

_ (the underscore)

An identifier may not begin with a digit. Further, no identifier can be the same as a keyword (a reserved word) in C++; keywords are listed below.

Thus the following are valid identifiers:

EXAMPLE: isAnAlpha _myVariable

PI word1 Word_1

The following are NOT valid identifiers:

EXAMPLE: 1Word a variable may not start with a number

word 1 a variable can't have a space

Word*1 * is an invalid character

word/1 / is an invalid character

continue reserved words are not valid identifiers

while reserved words are not valid identifiers

In addition, your instructor may require you to follow certain naming conventions, which are not required by the C++ language. For instance:

All constants will consist of upper case alphas, digits, and _. All variables will begin with a lower case alpha. When multiple words are used, subsequent words are capitalized.

Once a valid name is chosen for a variable or a constant, the next important task is to declare the type of the variable or constant. Some of the many simple types are listed in the table below, along with their usage (meaning), storage size in memory, and possible values.

(Recall that one byte is eight bits: 8 0s and 1s.)

In C++ all decimal numbers are represented in memory in a shorthand for scientific notation, which has two parts as in: 2.14 x 105. The first part (2.14 in the example) is called the coefficient (sometimes called the mantissa) and the second part is a power of 10. In C++ the 10 is assumed, and what is stored is the exponent (5 in the example). C++ displays decimal numbers in the form: 2.14e5. Even though all decimal numbers are stored in scientific notation, they also can be displayed in fixed point form: 214000.0.

Variable and Constant Types

Type Meaning StorageSize* Values

char character 1 - 4 bytes The keys on the keyboard (and more) enclosed in single quotes: '

short signed integer 2 bytes -32,767 to 32,767

int signed integer 4 bytes -2,146,483,647 to 2,146,483,647

long signed integer 4 bytes same as int (may be 8 bytes)

float signed decimal 4 bytes 10-37 to 1038 with 6 significant digits

double signed decimal 8 bytes 10-307 to 10308 with 15 significant digits

long signed decimal 16 bytes Used for very large and very small signed numbers

double 10-4931 to 104932 with 19 significant digits

string set of characters

varies** Any set of characters, enclosed in double quotes: "

* Different computer architectures may assign different storage sizes than those shown here. ** The string type is considered a complex type, not a simple type.

For the numeric types there is also an unsigned type, such as unsigned int (range of values: 0 to 4,294,967,295) and unsigned short (range of values: 0 to 65,535).

A declaration of a variable consists of its type, its name, and optionally an assignment of a value to the variable. A constant declaration consists of the keyword const followed by its type, its name, and a required assignment of a value to the constant. The assignments are made by use of the = operator. All declarations are statements, so a semicolon must terminate declarations. Some examples of valid variable and constant declarations are:

EXAMPLE: char userInput; int counter; double rate = 0.10; char response = 'Y'; string prompt = "Enter Y or N => "; const float PI = 3.14159; const string KG = "kilograms";

When initializing constants and variables, you may use the alternative syntax:

EXAMPLE: int counter (0); double rate (0.10);

C++ requires that all variables and constants must be declared before they are used. For now, this means the declaration must precede the uses of the variable. The most common use of a variable is make an assignment to it:

EXAMPLE: int counter; . . . counter = 1; . . .

Variable declarations and assignments are valid when they contain commas, as these examples show:

EXAMPLE: int num1, num2, num3; // declares 3 integers double rate1, rate2, rate3; // declares 3 decimals char YES = 'Y', NO = 'N'; // declarations with assignments

Other simple types include enum and bool (covered in other modules). Other complex types, in addition to string, are: struct, union, and class (also covered in other modules).

USING THE cin FACILITY

User input is stored in variables, already declared in your program, usually after the user is prompted for the input.

EXAMPLE: . . . char userResponse; cout << "Enter Y to continue or N to quit => "; cin >> userResponse; . . .

The cin facility uses the operator >>, and never contains a string or character literal, or an endl.

CHARACTER AND STRING VALUES

A literal string, such as "This is a string.", must be enclosed in double quotes; literal characters, such as 'a', must be enclosed in single quotes. Certain characters are special whitespace characters, such as the newline, the carriage return, the backspace, and the tab, which you may want to embed in your strings; you may also want to represent these special characters as literal characters or embed them within strings.

C++ provides an escape mechanism to represent these special characters; all escape characters begin with the backslash, \. A partial list would include:

\n the newline (on your keyboard, the Return or Enter key)

\r the carriage return (in C++ the newline includes the carriage return)

\b the backspace

\t the tab key

\\ the backslash character

\" the double quote

\' the single quote

Some examples of output strings and characters constructed with cout are:

EXAMPLE: cout << "This produces a string with " << '\'' << "single quotes << '\'' << " in it"; cout << "I said, \"No more!\"" << endl; cout << '\n'; // produces a blank line cout << "The path is C:\\temp\\misc" << endl;

KEYWORDS

iThe following keywords, or reserved words, can never be used as identifiers.

and double not this

and_eq dynamic_cast not_eq throw

asm else operator true

auto enum or try

bitand explicit or_eq typedef

bitor export private typeid

bool extern protected typename

break false public union

case float register unsigned

catch for reinterprete_cast using

char friend return virtual

class goto short void

compl if signed volatile

const inline sizeof wchar_t

const_cast int static while

continue long static_cast xor

default mutable struct xor_eq

delete namespace switch

do new template

REVIEW EXERCISES

1. * The main ( ) routine is set out in a block of code, and is where the program begins execution. T or F? 2. * All comments must begin with //. T or F? 3. * The library routines cout and endl are declared in the include file <iostream>. T or F? 4. ** Most simple data types can be signed as well as unsigned. T or F? 5. ** What do the following code snippets output?

cout << "Enter the name of the file to open\t=> "; cout << "The man said: \"Enough is enough!\"\n"; cout << "The path name of the file is " << "C:\\temp\\file.out" << endl;

Note that the last cout statement spans more than one line. How does the compiler determine that this is a

single statement?

6. * What is wrong with the following code snippet? int main ( ) { counter = 0; int counter; return 0; }

7. * Which of the following a valid identifiers? Why or why not? 0num speedOfLight user response if E QUART

8. * What type should the variable userResponse have to be to make the following code snippet syntactically correct? cout << "Enter your full name => "; cin >> userResponse;

9. ** Determine the size of the primitive data types on your machine. Write a program that prints out the sizes using lines like the following:

cout << "The size of an int is " << sizeof(int) << endl;

What is the size (i.e., the number of bits) of a char, a short, a float, a double, and the like?

© 2011 cad rcm cpsm