COS120 Software Development Using C++ AUBG Fall semester 200506 by xpw14517

VIEWS: 0 PAGES: 75

									                 COS120
      Software Development Using C++
      AUBG Fall semester 2005/06 AY
Ref book: Problem Solving, Abstraction and Design using C++
Authors: Frank Friedman, Elliot Koffman, http://www.aw.com/cssupport
Course lecturer: Assoc. Prof. Stoyan Bonev, PhD
            Declaration of Ethics


   This Power Point presentation (including slides
    style, samples and partly contents) was created
    using .ppt file, publicly available for download
    from ftp server at address:
   http://www.aw-bc.com/cssupport/FriedmanKoffman.html
   ftp://ftp.aw.com/cseng/authors/friedman/cpp3e/


                                                          2
Lecture 5: Computer Languages.
  Programming environments
             (IDE)
          Lecture Contents:

   Programming environments. Integrated
    development environments (IDE)
   Microsoft Visual C++ IDE
   Introduction to project concept
    – Workspace
    – Solution
   Sample programs in C/C++

                                           4
      Previous lecture reminder

                   Title:
     A Tutorial Introduction to C/C++

  Source: Friedman/Koffman, Chapter 02

Have a quick look at next approx 60 slides to
 refresh your knowledge on previous lecture

                                                5
Overview of C++

   Chapter 2
         2.1 C++ Language Elements

   Comments make a program easier to
    understand
   // Used to signify a comment on a single
    line
   /* Text text */ use if comments on multi
    lines
   Don‟t embed comments within /* */
    comments

                                               7
          Compiler Directives

   #include
    – Compiler directive
    – Processed at compilation time
    – Instructs compiler on what you want in the program
   #include <iostream>
    – Adds library files to program
    – Used with < >
    – Also “ “ user defined



                                                           8
           Compiler Directives

   Stream data type
    –   Object that is a stream of characters
    –   Defined in iostream
    –   Entered on the keyboard (cin)
    –   Displayed on monitor        (cout)




                                                9
         Declarations

   Direct compiler on requirements
   Based on data needs (data identifiers)
   Each identifier needed must be declared
   Comma used to separate identifiers
   cin and cout are undeclared identifiers
    – Special elements called streams
    – cin - input stream , cout - output stream
    – Included with the iostream not declared

                                                  10
         Executable Statements

   cout get output
    – cout << “Enter the fabric size in square meters: ”;
   cin get input
    – cin >> sizeInSqmeters;
   Assignment
    – sizeInSqyards = metersToYards * sizeInSqmeters;



                                                      11
          2.2 Reserved Words and
          Identifiers
   Reserved words have special meanings
    – Can NOT be used for other purposes (const,
      float and void are some examples)
   Identifiers (variables)
    – Used to store data by the program (user
      defined)
    – Valid identifiers - letter, letter1, _letter
    – Invalid identifiers - 1letter, const, hell o

                                                     12
         Reserved Words and
         Identifiers
   Special symbols
    – C++ has rules for special symbols
    – = * ; { } ( ) // << >>
   Appendix B
    – Examples of reserved words
    – Special characters



                                          13
         Upper and Lower Case

   C++ case sensitive
    – Compiler differentiates upper & lower case
    – Identifiers can be either
    – Be careful though (cost != Cost)
   Blank spaces
    – Use space to make program readable
    – Use care in placing spaces


                                                   14
            2.3 Data Types and
            Declarations
   Predefined data types
    – int     (integers)
       • Positive or negative whole numbers
       • 1000         12     199 100000
       • INT_MAX - largest int allowed by compiler
    – float   (real numbers)
       • Positive or negative decimal numbers
       • 10.5         1.2    100.02      99.88


                                                     15
         Data Types and Declarations

   Predefined data types
    – bool       (boolean)
       • true
       • false
    – char       (Characters)
       • Represent characters




                                  16
         Data Types and Declarations

   The basic integer type is int
    – The size of an int depends on the machine and
      the compiler
       • On pc’s it is normally 16 or 32 bits
   Other integers types
    – short: typically uses less bits
    – long: typically uses more bits


                                                      17
         Data Types and Declarations

   Different types allow programmers to use
    resources more efficiently
   Standard arithmetic and relational
    operations are available for these types




                                               18
         Data Types and Declarations

   Floating-point types represent real numbers
    – Integer part
    – Fractional part
   The number 108.1517 breaks down into the
    following parts
    – 108 - integer part
    – 1517 - fractional part


                                              19
         Data Types and Declarations

   C++ provides three floating-point types
    – float
    – double
    – long double




                                              20
         Data Types and Declarations

   Predefined data types
    – char    (characters)
       • Individual character value (letter or number)
       • Character literal enclosed in single quotes ‘A’
    – bool    (true / false)
   Ordinal types
    – int    bool          char
    – Values can be listed

                                                           21
         Data Types and Declarations

   Character type char is related to the integer
    types
   Characters are encoded using a scheme
    where an integer represents a particular
    character




                                                22
           Data Types and Declarations

   ASCII is the dominant encoding scheme
    – Examples
       •   ' ' encoded as 32
       •   '+' encoded as 43
       •   'A' encoded as 65
       •   'Z' encoded as 90
       •   ’a' encoded as 97
       •   ’z' encoded as 122


                                            23
         string Class

   String object data type
    – A literal string constant is a sequence of zero or
      more characters enclosed in double quotes
    – "Are you aware?\n"
    – Individual characters of string are stored in
      consecutive memory locations
    – The null character ('\0') is appended to strings
      so that the compiler knows where in memory
      strings ends

                                                       24
          string Class

   String literal
    – “A”
    – “1234”
    – “Enter the distance”
   Additional data types included in library
    #include <string>
    – Various operations on strings


                                                25
         Declarations

   Identifiers should be
    – Short enough to be reasonable to type (single
      word is norm)
       • Standard abbreviations are fine (but only standard
         abbreviations)
    – Long enough to be understandable
       • When using multiple word identifiers capitalize the
         first letter of each word



                                                               26
           Declarations

   Examples
    –   char response;
    –   int minelement;
    –   float score;
    –   float temperature;
    –   int i;
    –   int n;
    –   char c;
    –   float x;

                             27
           Constant Declarations

   Types of constants
    –   integer
    –   float
    –   char
    –   bool
    –   string objects
   Associate meaningful terms
    – const float PAYRATE = 10.25;

                                     28
              Hello.cpp –full text of
              program
// FILE: Hello.cpp
// DISPLAYS A USER'S NAME
#include <iostream>
#include <string>
using namespace std;
int main ()
{
char letter1, letter2;
   string lastName;
   // Enter letters and print message.
   cout << "Enter 2 initials and last name: ";
   cin >> letter1 >> letter2 >> lastName;
    cout << "Hello " << letter1 << ". " << letter2 << ". " << lastName << "!   ";
    cout << "We hope you enjoy studying C++." << endl;
    return 0;
}




                                                                                    29
        Hello.cpp

// FILE: Hello.cpp
// DISPLAYS A USER'S NAME

#include <iostream>
#include <string>

using namespace std;

int main ()
{



                            30
         Hello.cpp
    char letter1, letter2;
    string lastName;

    // Enter letters and print message.
    cout << "Enter 2 initials and last name: ";
    cin >> letter1 >> letter2 >> lastName;
    cout << "Hello " << letter1 << ". " <<
       letter2 << ". " << lastName << "! ";
    cout << "We hope you enjoy studying C++." <<
                                      endl;
    return 0;
}


                                                   31
       Hello.cpp

               Program output

Enter first two initials and last name and press
                         return: EBKoffman

Hello E. B. Koffman! We hope you enjoy
                         studying C++.

                                               32
         2.4 Executable Statements

   Memory status
    – Before and after
   Assignments
    – Form: result = expression;
    – sizeInSqyards = metersToYards * sizeInMeters;
    – sum = sum + item;



                                                 33
        Arithmetic Operators

   +     Addition
   -     Subtraction
   *     Multiplication
   /     Division
   %     Modulus



                               34
            Input / Output Operations

   Input
    – #include <iostream> library
    – cin >> sizeInSqmeters;
   Extracted from cin (input stream)
   >> Directs input to variable
   cin associated with keyboard input (stdin)
   Used with int, float, char, bool and strings

                                                   35
         Data Types and cin

   Don‟t mix types with cin
    int x;
    cin >> x;

                    Keyboard input
    16.6
    Value placed in x would be 16


                                     36
         Other Characteristics of cin

   Leading blanks ignored (floats, int, char,
                           bool and strings)
   Char read 1 at a time (1 non blank)
   Case issues
   int or float will read until space
   Stings same as int and float


                                                 37
        General Form for cin


Form:      cin >> dataVariable;

cin >> age >> firstInitial;




                                  38
         Program Output

   Output stream cout
   << Output operator (insertion operator)
    – cout << “my height in inches is: “ << height;
   Blank lines
    – endl; or “\n”;


Form:         cout << dataVariable;

                                                      39
         2.5 General Form of a C++
         Program
   General program form
    – Function basic unit (collection of related
      statements)
    – A C++ program must contain a main function
               void main ()
    – int - function returns integer value
    – main - lower case with ()
    – { } - Braces define the function body

                                                   40
         General Form of a C++
         Program
   General form of function body parts

    – Declaration statements
       • Variables and constants

    – Executable statements
       • C++ statements


                                          41
          General Form of a C++
          Program
   General form
    // File: filename
    // Program description:
    #include directives
    int main()
    {
                  Declarations section
                  Executable statements section
    }

                                                  42
       General Form

// Name: Mike Hudock
// Date: March 10, 2000
// Files: file1.cpp
          file2.cpp
// Changes :
// Program description:


                          43
         General Form

   Use comments throughout code to highlight
    points of interest
   Strange identifiers
   Function explanations
   Algorithm definitions




                                            44
         2.6 Arithmetic Expressions

   int data type
    – + - * /, Assignment, input and output on int
    –%         Only used with int
   Examples of integer division
                        15 / 3 = 5
                        15 / 2 = 7
                        0 / 15 = 0
                    15 / 0 undefined

                                                     45
         Modulus and Integer

   Used only with integer and yields remainder
   Examples of integer modulus
                     7%2=1
                  299 % 100 = 99
                    49 % 5 = 4
                 15 % 0 undefined



                                              46
          Mixed-type Assignments

   Expression evaluated
   Result stored in the variable on the left side
   C++ can mix types
    float a, b, x;
    int m, n;
    a=10;
    b=5;
    x = m / n;

                                                     47
         Expressions With Multiple
         Operators
   Operator precedence tells how to evaluate
    expressions
   Standard precedence order
    – ()     Evaluated first, if nested innermost
       done first
    – * / % Evaluated second. If there are several,
       then evaluate from left-to-right
    – +-     Evaluate third. If there are several,
       then evaluate from left-to-right

                                                      48
         Mathematical Formulas in
         C++
   a = bc not valid C++ syntax
    – * Operator   a = b * c;


   m=y-b
      x-a
    – ( ) And /    m = (y - b) / (x - a);



                                            49
         Coin Collection Case Study

   Problem statement
    – Saving nickels and pennies and want to
      exchange these coins at the bank so need to
      know the value of coins in dollars and cents.
   Analysis
    – Count of nickels and pennies in total
    – Determine total value
    – Use integer division to get dollar value
       • / 100

                                                      50
           Coin Collection Case Study

   Analysis (cont)
    – Use modulus % to get cents value
    – % 100
   Design
    –   Prompt for name
    –   Get count of nickels and pennies
    –   Compute total value
    –   Calculate dollars and cents
    –   Display results

                                           51
         Coin Collection Case Study

   Implementation
    – Write C++ code of design
    – Verify correct data types needed
    – Mixed mode types and promotion
   Testing
    – Test results using various input combinations



                                                      52
        Coins.cpp
// File: coins.cpp
// Determines the value of a coin collection

#include <iostream>
#include <string>

using namespace std;

int main()
{



                                               53
     Coins.cpp
// Local data ...
string name;
int pennies;
int nickels;
int dollars;
int change;
int totalCents;

// Prompt sister for name.
cout << "Enter your first name: ";
cin >> name;



                                     54
     Coins.cpp
// Read in the count of nickels and pennies.
cout << "Enter the number of nickels: ";
cin >> nickels;
cout << "Enter the number of pennies: ";
cin >> pennies;

// Compute the total value in cents.
totalCents = 5 * nickels + pennies;

// Find the value in dollars and change.
dollars = totalCents / 100;
change = totalCents % 100;


                                               55
           Coins.cpp

    // Display the value in dollars and change.
      cout << "Good work " << name << '!' << endl;
      cout << "Your collection is worth " <<
               dollars << " dollars and " <<
                      change << " cents." << endl;
      return 0;
}




                                                     56
        Coins.cpp

                   Program output
Enter your first name and press return: Sally
Enter number of nickels and press return: 30
Enter number of pennies and press return: 77

Good work sally!
Your collection is worth 2 dollars and 27 cents.


                                                   57
         2.7 Interactive Mode, Batch
         and Data Files
   Two modes interactive or batch
    – Keyboard input interactive
   Batch mode data provided prior to start
    – File as input
   Input / output redirection
    – Direct input to program use „<„ symbol
    – Direct output to a file use „>„ symbol


                                               58
         Input / Output Redirection

   Program name < datafile

               Metric < mydata




                                      59
         Input / Output Redirection

   Program name > outFile

                Metric > outFile

   Input and output redirection

             Metric < inFile > outFile

                                         60
        Milesbatch.cpp
// File: milesBatch.cpp
// Converts distance in miles to kilometers.

#include <iostream>
using namespace std;

int main()           // start of main function
{
      const float KM_PER_MILE = 1.609;
      float miles,
             kms;


                                                 61
      Milesbatch.cpp
    // Get the distance in miles.
    cin >> miles;
    cout << "The distance in miles is " <<
                      miles << endl;

    // Convert the distance to kilometers.
    kms = KM_PER_MILE * miles;

    // Display the distance in kilometers.
    cout << "The distance in kilometers is " <<
                                   kms << endl;
    return 0;
}

                                              62
       Milesbatch.cpp

              Program output



The distance in miles is 10
The distance in kilometers is 16.09



                                      63
         2.8 Common Programming
         Errors
   Syntax
    – Programs rarely compile
    – Something always goes wrong
    – Systematic solutions
   Compiler not descriptive
    – Look at line number before and after error
    – Watch missing ; and }


                                                   64
         Common Programming Errors

   Run-time errors
    – Illegal operation (divide by 0)
    – Test.cpp is example
   Logic errors
    – Program functions differently than you expect




                                                      65
                  Introduction to
                  MS Visual C++, version 6
    How to create and execute C/C++ console applications?
Start (run) MS Visual C++, version 6
Click File >> New >> Projects
Select Win32 Console Application, enter project name/location, click OK
Select Empty project, click Finish.
Click OK
Click File >> New >> Files
Select C++ Source File, enter name/location for the source file (usually same as project
   name), click OK
Enter the source text in the text window just opened
Click Build >> Compile <file>.cpp or press Ctrl+F7
Read messages displayed in output pane: in case of errors you should correct the source
   text. If you succeed, “<file>.obj - 0 error(s), 0 warning(s)” will display.
Click Build >> Execute <file>.exe
                                                                                66
                Introduction to
                MS Visual C++.NET
   How to create and execute C/C++ console applications?
Start (run) MS Visual C++.NET IDE
Click File >> New >> Project
Select Visual C++ Projects, Win32, Win32 Console project, enter project
      name/location, click OK
Click Application Settings (Application type: Console application, Additional
      Options: empty project), click Finish.
Click File >> Add New Item …
Select template C++ File (.cpp), enter name/location for the source file (usually same
      as project name), click Open
Enter the source text in the text window just opened
Click Build >> Build <project name>
Read messages displayed in output pane: in case of errors you should correct the text.
      If you succeed, “Build: 1 succeeded: 0 failed, 0 skipped” will display.
Click Debug >> Start without Debugging                                         67
                Intro to Borland C++

How to compile and execute C/C++ applications?
Click Start from Task bar, Select Run… and click on it
Enter cmd command and click OK or press Enter to open an MSDOS window
Change current device to Q: drive and call command H:\borlandc\bin\bc.exe
Press F10 >> Options >> Directories. Check Drive letter for Include and Library
   directories to be H, Drive letter for output and source directory to be Q
Press F10 >> File >> New, enter the source text of your program
Press F10 >> Save As… to name and save your program as a source file (.cpp).
Press F10 >> Compile >> Compile (or Alt+F9) and look at the compiler
   messages. In case of errors and/or warnings, you should edit and recompile
   your source text until “0 warnings, 0 errors, Success” is displayed
Press F10 >> Run >> Run (or Ctrl+F9) to run your program.

                                                                           68
      Exercise 5.1

Build and run a program: To compute and
 display the volume of a pool;




                                          69
      Exercise 5.2

Build and run a program: To convert meters
 to feet and inches




                                             70
       Exercise 5.3

Build and run a program: To add, subtract,
 multiply and divide two numeric values




                                             71
       Exercise 5.4

Build and run a program: To convert Celsius
 degrees to Fahrenheit degrees
           Fahr = 9./5.*Cel+32




                                              72
       Exercise 5.5

Build and run a program: To convert
 Fahrenheit degrees to Celsius degrees
           Cel = 5./9.*(Fahr-32)




                                         73
    Before lecture end

                Lecture:
 Integrated Development Environments
    A Tutorial Introduction toC/C++


        More to read:
Friedman/Koffman, Chapter 02

                                       74
 Thank You
     For
Your Attention

                 75

								
To top