Last updated: Friday 24th March 2006, 15:10 PT, AHD

 

An Introduction to Programming using C++

 

C++ Basics

 

Chapter 2

 

2.1    Variables and Assignments

2.2    Input and Output

2.3    Data Types and Expressions

2.4    Simple Flow of Control

2.5    Program Style

 

 

2.1  Variables and Assignments

 

      Variables

      Identifiers

      Variable Declarations

      Assignment statements

  

Variables and Assignments

 

http://www.annedawson.com/02-01.cpp

 

 

 

2.2.       Input and Output

 

      Output using cout

      Escape sequences

      Formatting for numbers with a decimal point

      Input using cin

      Designing Input and Output

 

Output using cout

 

There are several ways C++ can get input and perform output.

 

Input and output occur in ‘streams’.

An input stream is a flow of data into the computer for the program to use. 

 

 An output stream is a flow of data out of the program. 

 

So far we have seen the keyboard used for the input stream,

and the screen used for the output stream.

 

In chapter 5, you will see how files can be used for input and output.

 

The following line

is a single statement in C++

 

cout << number_of_bars << "candy bars\n";

 

It outputs two items to the screen.

 

Firstly it outputs the value of number_of_bars...

 

cout << number_of_bars << "candy bars\n";

 

Then it outputs (on the same line) the text “candy bars” followed by a new line.

The \n represents a new line to the compiler.

 

cout << number_of_bars << "candy bars\n";

 

 

      Escape sequences

 

The character combination  \n  represents a SINGLE character to the compiler.

It is a special kind of character known as an escape character. 

'\n'

Single characters are contained within single quote marks (‘’) - so the \n character is written as ‘\n’ in C++ unless it is contained within a string - in which case it is contained within the double quotes ( “ ”) of the string..

 

Here is the '\n' contained within a string. 

It generates a new line at the end of the line of text which is output to the screen.

 

cout << number_of_bars << "candy bars\n";

 

 

Other kinds of escape characters

 

\n    generates a new line

\t    generates a horizontal tab (a few spaces)

\a    generates an alert (a bell sound)

 

\\  allows a backslash (\) to be included within a string.

(A single backslash within a string is interpreted as the start of an escape character –

 so would not be printed as a backslash character.)

 

\"    allows a ” to be printed within a string.  It would normally mark the end of a string.

 

 

 

http://www.annedawson.com/escape.cpp

http://www.annedawson.com/escape_borland.cpp

 

 

You can include expressions within a cout statement:

 

cout << "Total cost is $" << (price + tax);

 

 

 

The   <<   is known as the “insertion operator”

 

Here is the '\n' contained within a string.

It generates a new line at the end of the line of text which is output to the screen.

 

cout << number_of_bars <<  "candy bars\n";

 

cout << number_of_bars << "candy bars\n";

 

cout << number_of_bars << "candy bars" << endl;

 

The above 2 statements do exactly the same thing.

endl is known as an output manipulator.

It forces a new line.

Note endl is not contained within the  " " quotes marks.

 

\

 

Formatting for numbers with a decimal point

Data of type ‘double’ can contain a fractional part, e.g.  10.45678

 

If you want to control the output of a double so that only 2 decimal places are output to the screen, you must provide additional instructions to the compiler….

 

 

What is the output after running this code?

 

#include <iostream>

using namespace std;

int main()

{

  double num;

  num = 10.56789; 

  cout << "The value of num is :" << num;

  system("PAUSE");

 }

 

 

What is the output after running this code?

 

 

#include <iostream>

using namespace std;

int main()

{

  double num;

  num = 10.56789;

  cout.setf(ios::fixed);

  cout.setf(ios::showpoint);

  cout.precision(2);

  cout << "The value of num is : " << num;

  system("PAUSE");

}

 

 

Input using cin

 

http://www.annedawson.com/02-01.cpp

 

 

 

cin >> number_of_bars;

cin >> one_weight;

 

can be written on one line:

 

cin >> number_of_bars >> one_weight;

 

 

When a program reaches a cin statement...

  . . . it waits for input to be entered at the keyboard. 

It sets the first variable equal to the first value typed in,

and the second variable equal to the second value typed in:

 

cin >> number_of_bars >> one_weight;

 

 

When you type in input...

 

You should separate the data entered by either at least one space, or press the return key

(i.e. the Enter key) after each entry.

 

 

 

 

Designing Input and Output

 

When you write your programs, make sure that you prompt the user correctly when they should type in data entry. 

 

 

When a program reaches a cin statement, it will wait for data to be typed in at the keyboard.

 

Make sure that the statement before the cin statement is a cout statement,

explaining to the user what they should do next….

 

Input using cin

 

http://www.annedawson.com/02-01.cpp

this program gives a good example of  how cout statements

warn the user what they are supposed to do next

 

2.3.       Data Types and Expressions

 

      The types int and double

      Other number types

      The type char

      The type bool

      Type compatibilities

      Arithmetic operators and expressions

      More assignment statements

  

  

The types int and double

 

We will be using mainly the types int and double to hold numbers.

 

The int type of variable can hold a whole number such as 1, 2, 3 or 4

 

The double type of variable can hold a number with a fractional part, such as 1.23 

 

The keyword  int  means integer

 

Data types which can hold a number with a decimal point are called floating point types

 

 

 

  

 

 

Integer Data Types

 

Type Name      Memory      Size range

 

short (int)         2 bytes        -32,767 - 32,767

int                     4 bytes       -2,147,483,647   to

                                             2,147,483,647

long (int)          4 bytes       -2,147,483,647   to

                                             2,147,483,647

 

 

 

 

 

 

 

 

 

 

Floating point Data Types

 

Type Name      Memory      Size range

 

float                 4 bytes        approx. 10-38

                                            to 1038

double              8 bytes        approx. 10-308

                                            to  10308

long double     10 bytes       approx. 10-4932

                                             to 104932

 

 

Precision with floating point numbers

 

Precision refers to the number of meaningful digits

- this includes those before and after the decimal point:

 

   float                  7 digits

   double              15 digits

   long double     19 digits

 

 

 

 

 

Numeric accuracy

 

Integers are held in the computer with absolute accuracy.

 

Floating point calculations may result in a number that cannot be held accurately

by the computer because of the lack of precision. 

 

 

The char data type

 

 

The char type can hold a single character, e.g. ‘a’, ‘b’, or ‘1’, ‘2’, ‘3’

 

characters are contained within single quote  marks ( ‘ ’)

 

a string of characters is contained within double quote marks  ( “ ”)

 

 

 

 

 

Characters and Strings

 

‘a’ is a character

 

and

 

“a” is a string

 

They are different!!! (more on strings later)

 

 

 

A character….

 

…occupies a single byte, and its byte value is the decimal value given by its ASCII code:

 

‘A’  is decimal 65  or binary   01000001

 

 

 

 

The bool type

 

Some compilers offer a bool (Boolean) type

 

A bool variable can take a value of true or false

The Borland C++ Version 5.02 compiler does have the bool data type.

 

 

 

 

Type Compatibilities

Make sure that you assign only integers to integer types, and doubles to double type:

 

   int inum;

 double dnum;

 inum = 10;

 dnum = 10.234;

 

 

Do not mix your types!

 

Assigning a double value to an integer variable results in loss of data. 

The compiler will give you a warning of this…

  

  int inum;

 double dnum;

 dnum = 2.99;

 inum = dnum; //inum gets a value of 2

 

 

 

 

 

Arithmetic Operators and Expressions

  

In C++ you can combine variables and/or numbers using the arithmetic operators:

 

                   +  for addition

                   - for subtraction

                   * for multiplication

                   / for division

 

 

          sum = num1 + num2;

    product = num1 * num2;

    result = sum / 5;

    result = sum / 5.0;

 

why are the last two statements different?

 

 

5.0 / 2.0  results in a value of 2.5

because the two operands are doubles, the result is a double.

 

However:

5/2  results in a value of 2 because the two operands are integers, the calculation will be an integer division and the result will be an integer.

 

When you perform any calculations in C++,

you should always check the result at each stage

 so that you can confirm that you get the result you are expecting.

 

HINT, during calculations in a program - use a cout statement to send the result to the screen,

so you can check it is correct.

 

 

 

 

The % (modulus) operator

 

The % operator is used with two integer values, e.g. 

 

   answer  =   6  %  4;

 

This does an integer division and the result is what is left after dividing 6 by 4.

Therefore ‘answer’ receives a value of 2.

 

 

More on %

 

answer  =  6  %  4 ;  // answer is 2

answer  =  6  %  3 ;  // answer is 0

answer  =  6  %  1 ;  // answer is 0

answer  =  6  %  2 ;  // answer is 0

answer  =  6  %  5 ;  // answer is 1

answer  =  6  %  6 ;  // answer is 0

 

 

Operator Precedence

 

    *     and    /       done first

    +    and    -       done later

 

e.g.    3 + 2  *  4   (results in 11)  BUT

        (3 + 2)  * 4   (results in 20)

 

 

 

 

More Assignment Statements

count += 2;  is the same as:  count = count + 2;

count -= 2;  is the same as:  count = count - 2;

bonus *= 2;  is the same as:  bonus = bonus * 2;

 

see textbook for more examples,

but be aware that some programmers

avoid using these shortcuts as they

find them confusing!

 

 

 

 

 

2.4           Simple Flow of Control

 

So far we have seen program statements executed one after the other,

starting with the first and ending with the last statement.

 

It is also possible to alter the order in which the statements are executed.

 

The order in which the statements are executed

is known as the flow of control.

 

In this section we look at two different ways to change

the order in which statements are executed. . . 

 

A branching mechanism: the if-else statement

 

       if (hours > 40)

       pay = (hourly_rate * hours) + BONUS;

    else

       pay = (hourly_rate * hours) ; 

 

The expression:

  

(hours > 40)

 

 is known as a Boolean expression

 

 

 

Boolean Expression

  

A Boolean expression has a value which can either be "true" or "false"

  

  

   (hours > 40)

 

    has a value which can either be "true" or "false"

 

 

The   >   symbol

The  >  symbol is known as a comparison operator and is used to compare one value with another.

 

       >   means "greater than"

 

       e.g.           (hours > 40)

 

 

 

 

Comparison Operators

 

= =          equal to

!=            not equal to

>             greater than

<             less than

>=           greater than or equal to

<=           less than or equal to

 

 

 

The if-else statement

http://www.annedawson.com/02-06.cpp

 

 

 

Combining Boolean expressions

 

You can combine Boolean expressions.

For example, if you need to know if a person's age is greater than 21,

AND they have a salary greater than 50 thousand dollars…..

 

     

  (age > 21) && (salary > 50000)

 

The &&  is known as a logical operator. 

&&  is the  'AND'  logical operator.

 

 

 

Logical Operators

 

&&         AND

||              OR

!          NOT

 

 

 

 

 

Truth Table of Boolean && (AND) Operator

 

 value of A   value of B      resulting value of

                                                 A  &&  B 

 

    false                 false                     false

    false                 true                      false

    true                  false                     false

    true                  true                      true

 

 

 

 

 

Truth Table of Boolean || (OR) Operator

 

 value of A   value of B      resulting value of

                                                 A  ||  B 

 

    false                 false                     false

    false                 true                      true

    true                  false                     true

    true                  true                      true

 

 

 

 

 

Truth Table of Boolean  ! (NOT) Operator

 

 value of A      resulting value of

                                 !A

   

      false                      true

 true                       false

 

When writing boolean expressions or arithmetic expressions,

 it is usually best to indicate the order of operations by using parentheses (brackets).

 

 

 

  

However, if parentheses are not used,

the computer will perform the operations in an order determined by the…

precedence rules. . .

 

unary operators: +, -, ++,--, and !

binary arithmetic operators: *, /, %

binary arithmetic operators: +,-

boolean operators: <, >, <=, >=

boolean operators: ==, !=

boolean operator: &

boolean operator:  |

boolean operator: &&

boolean operator: ||

 

 

Logical Operators

http://www.annedawson.com/logical.cpp

 

{

   int num1 = 10;

   int num2 = 20;

   cout << "Note: num1 = 10 and num2 = 20" << endl << endl;

   if ((num1 > 5) && (num2 > 5)) // the AND operator &&

   {

       cout << "both num1 and num2 are greater than 5" << endl;

   }

   else

   {

       cout << "num1 and num2 are not both greater than 5" << endl;

   }

 

}

the if-else statement
using a single statement for each branch

 

       if (hours > 40)

       pay = (hourly_rate * hours) + BONUS;

    else

       pay = (hourly_rate * hours); 

 

 

 

Using a compound statement for each branch

 

       if  (hours   >   40)

       {

            pay  =  (hourly_rate * hours) + BONUS;

            cout  <<  "You get a bonus";

       }

      else

       {

             pay  =  (hourly_rate * hours) ; 

             cout  <<  "No bonus for you, sorry";

       }

 

Simple Flow of Control

 

a branching mechanism (if-else) and

a looping mechanism . . .

 

 

A Looping Mechanism

A looping mechanism is one which causes a section of code to be repeated.

 

Each repeat is known as an iteration.

 

 

A looping mechanism:
the while statement

count = 4;

while (count > 0)

{

    cout << "Hello";

    count = count - 1;

}   // Prints out Hello four times

   

 

 

The while statement

 

http://www.annedawson.com/02-10.cpp

 

 

 

 

 

The do-while loop

 

 

 

count = 1;

do

{

   cout << "Hello";

   count = count + 1;

}  while (count < 5);

// prints out Hello four times

 

 

 

The do-while statement

 

http://www.annedawson.com/02-13.cpp

 

 

 

Program Style

 

The style of a program refers to the layout of the text in the code.

 

In particular, program style is improved by correctly indenting the code,

appropriate use of comments,

correct use of constants

and by using meaningful variable names.

 

The code shown in example program

 http://www.annedawson.com/02-15.cpp

is an example of good program style. 

 

 

Your own code should follow this style.