; Chapter 2 Introduction to C++ Programming_1_
Documents
Resources
Learning Center
Upload
Plans & pricing Sign in
Sign Out

Chapter 2 Introduction to C++ Programming_1_

VIEWS: 0 PAGES: 35

  • pg 1
									       Chapter 2
       Introduction to C++
       Programming
              C++, How to Program
              Deitel & Deitel




Spring 2010                     CS1600 Yanjun Li   1
Learn C++ by Examples

n    Five examples demonstrate
     q    How to display messages
     q    How to obtain information from the user
     q    How to perform arithmetic calculations




Spring 2010                 CS1600 Yanjun Li        2
Important Parts of a C++ program

n Comments: //, /* …. */
n Preprocessor directives : #include

n Function main
     q    Body of the function
     q    Return statement
     q    Other statements



Spring 2010                 CS1600 Yanjun Li   3
Comments

n    Explain programs to other programmers
     q    Improve program readability
n    Ignored by compiler
n    Single-line comment
     q    Begin with //
     q    Example
          n   //allows program to output data to the
              screen .
n    Multi-line comment
     q    Start with /*
     q    End with */
Spring 2010                    CS1600 Yanjun Li        4
Preprocessor Directives

n    Preprocessor directives
     q    Processed by preprocessor before compiling
     q    Begin with #
     q    Example
          n   #include < iostream >
              q   Tells preprocessor to include the input/output stream header file
                  <iostream >
n    White spaces
     q    Blank lines, space characters and tabs
     q    Delimiter, used to make programs easier to read
     q    Extra spaces are ignored by the compiler

Spring 2010                            CS1600 Yanjun Li                               5
Function main

n    A part of every C++ program
     q    Exactly one function in a program must be main
     q    main is a Keyword.
          n   Keyword : A word in code that is reserved by C++ for a
              specific use.
n    Header of function main : int main( )
n    Body is delimited by braces ({ })



Spring 2010                      CS1600 Yanjun Li                      6
Statements

n    Instruct the program to perform an action
n    All statements end with a semicolon (;)
n    Examples :
     q    return 0;
     q    std::cout << “Welcome to C++!\n ”;




Spring 2010            CS1600 Yanjun Li          7
return Statement

n    One of several means to exit a function
n    When used at the end of main
     q    The value 0 indicates the program terminated
          successfully
     q    Example
          n   return 0;




Spring 2010                 CS1600 Yanjun Li             8
Output Statement (1)

std::cout << “Welcome to
 C++!\n”;
     q    std::cout
          n   Standard output stream object.
          n   Defined in input/output stream header file <iostream >
          n   We are using a name (cout) that belongs to “namespace”
              std.
          n   Normally outputs to computer screen.
     q    Stream insertion operator <<
          n   Value to right (right operand) inserted into left operand.
          n   The string of characters contained between “ ” after the
              operator << shows on computer screen.
Spring 2010                        CS1600 Yanjun Li                        9
Output Statement (2)

n    Escape character : backslash : "\"
n    Escape sequence : A character preceded by
     backslash (\)
     q    Indicates “special” character output
     q    Examples :
          n   "\n"
              q   Newline. Cursor moves to beginning of next line on the
                  screen
          n   “\t”
              q   Horizontal tab. Move the screen cursor to the next tab stop.


Spring 2010                          CS1600 Yanjun Li                        10
Good Programming Practices

n    Add comments
     q    Every program should begin with a comment that
          describes the purpose of the program, author,
          date and time.
n    Use good indentation
     q    Indent the entire body of each function one level
          within the braces that delimit the body of the
          function. This makes a program’s functional
          structure stand out and helps make the program
          easier to read.

Spring 2010                  CS1600 Yanjun Li                 11
Run C++ Program

n    Save the program with the right extension
     q    programOne.cpp
n    Send the program in the right directory
n    Compiling the program:
     q    g++ programOne.cpp –o
          programOne.out
n    Run the executable file
     q    ./programOne.out


Spring 2010                CS1600 Yanjun Li      12
Modifying Our First C++ Program

n    Print text on one line using multiple
     statements
     q Each stream insertion resumes printing where the
       previous one stopped
     q Statements:

     Std::cout << “Welcome ”;
     Std::cout << “to C++!\n”;




Spring 2010              CS1600 Yanjun Li             13
Modifying Our First C++ Program

n    Print text on several lines using a single
     statement.
     q Each newline escape sequence positions the
       cursor to the beginning of the next line
     q Two newline characters back to back outputs a
       blank line
     q Example statement :

     Std::cout << “Welcome \nto\n\nC++!\n”;



Spring 2010             CS1600 Yanjun Li               14
Variable

n    Location in memory where value can be
     stored
n    Common data types (fundamental, primitive
     or built-in)
     q    int – integer numbers : 1, 2, 4,….
     q    char – characters : ‘a’, ‘c’, …
     q    float, double – floating point numbers: 2.5,
          4.96
n    The value of a variable could be changed
     while the program is running.
Spring 2010                CS1600 Yanjun Li              15
Declaration of Variables (1)

n    Declare variables with name and data type
     before they are used.
n    A variable name is any valid identifier that is
     not a keyword.
     q    Series of characters - letters, digits,
          underscores ( _ )
     q    Cannot begin with digit
     q    Case sensitive
     q    Choosing meaningful identifiers helps make a
          program self-documenting.
Spring 2010                CS1600 Yanjun Li              16
Declaration of Variables (2)

n    Can Declare each variable on a separate
     line.
     q    int integer1;
     q    int integer2;
     q    int sum;
n    Can declare several variables of same type
     in one declaration.
     q    Comma-separated list
     q    int integer1, integer2, sum;

Spring 2010               CS1600 Yanjun Li        17
Assign Value to Variables

n    Assignment operator =
     q Assigns value on right to variable on left

     q Binary operator (two operands)

n    Assign a value after declaration
     q    int integer1;      //declaration
     q    integer1 = 10;     //assignment
n    Declare and assign a value at the same time.
     q    int integer2 =      20;

Spring 2010             CS1600 Yanjun Li            18
Input stream object

n    std::cin from <iostream >
     q    Usually connected to keyboard
     q    Stream extraction operator >>
          n   Waits for user to input value, press Enter (Return) key
          n   Stores value in variable to right of operator
              q   Converts value to variable data type
     q    Example
          n   int number1;
          n   std::cin >> number1;
              q   Reads an integer typed at the keyboard
              q   Stores the integer in variable number1


Spring 2010                         CS1600 Yanjun Li                    19
Constant variables

n Declared  using the const qualifier
n Also called named constants or read-only
  variables
n Must be initialized with a constant expression
  when they are declared and cannot be
  modified thereafter
n Example: const int size = 5;




Spring 2010          CS1600 Yanjun Li              20
Arithmetic (1)

n    Arithmetic operators
     q    +:      Addition
     q    - :     Subtraction
     q    *:      Multiplication
     q    /:      Division
          n   Integer division truncates remainder
              q   7 / 5 evaluates to 1
     q    % : Modulus operator returns remainder
          n   7 % 5 evaluates to 2
          n   Attempting to use the modulus operator (%) with
              non-integer operands is a compilation error.

Spring 2010                        CS1600 Yanjun Li             21
Arithmetic operators




Spring 2010     CS1600 Yanjun Li   22
Arithmetic (2)

n    Straight-line form
     q    Required for arithmetic expressions in C++
     q    All constants, variables and operators appear in a straight
          line
n    Grouping sub-expressions
     q    Parentheses are used in C++ expressions to group sub-
          expressions
          n   Same manner as in algebraic expressions
     q    Example
          n   a * ( b + c )
              q   Multiple a times the quantity b + c


Spring 2010                           CS1600 Yanjun Li                  23
Rules of operator precedence

n    Operators in parentheses evaluated first
     q    Nested/embedded parentheses
          n   Operators in innermost pair first
n    Multiplication, division, modulus applied next
     q    Operators applied from left to right
n    Addition, subtraction applied last
     q    Operators applied from left to right




Spring 2010                       CS1600 Yanjun Li    24
Precedence of Arithmetic Operators




Spring 2010    CS1600 Yanjun Li      25
Performing Arithmetic Calculation in C++
Program
n    Adding two integers
     q    int number1, number2, sum;
     q    std::cin >> number1;
     q    std::cin >> number2;
     q    sum = number 1 + number 2;
          n   Add the values of variable1 and variable2
          n   Store result in sum




Spring 2010                    CS1600 Yanjun Li           26
Question

n    Question :
    int integerOne = 1;
    double doubleOne = 2.5;

     int sumOne = integerOne + doubleOne; //A
     double sumTwo = integerOne + doubleOne; //B


     Which statement is correct , A or B ?




Spring 2010              CS1600 Yanjun Li          27
Output Statement With Expression

n    Variables or expressions could be inserted into
     output statement, its value is printed out.
n    Long output statement could be broken into
     multiple lines.
n    Example:
     std::cout <<   “sum is ” << sum
               <<   “. bye-bye! \n”;
     std::cout <<   “sum is ”
               <<   number1 + number2 ;


Spring 2010             CS1600 Yanjun Li           28
End of Line

n    Stream manipulator std::endl
     q    Outputs a newline
     q    Flushes the output buffer




Spring 2010                CS1600 Yanjun Li   29
Memory Concepts

n    Variable names
     q    Correspond to actual locations in computer's memory
          n   Every variable has name, type, size and value
     q    When new value placed into variable, overwrites old value
          n   Writing to memory is destructive
     q    Reading variables from memory nondestructive
     q    Example
          n   sum = number1 + number2;
              q   Value of sum is overwritten
              q   Values of number1 and number2 remain intact




Spring 2010                         CS1600 Yanjun Li                  30
   Fig. 2.6 | Memory location showing the name and value
   of variable number1.




Spring 2010               CS1600 Yanjun Li            31
   Fig. 2.7 | Memory locations after storing values for
   number1 and number2.


Spring 2010               CS1600 Yanjun Li                32
 Fig. 2.8 | Memory locations after calculating and storing
 the sum of number1 and number2.


Spring 2010              CS1600 Yanjun Li               33
Type Sizes and Ranges

n The size and range of any data type is
  compiler and architecture dependent.
n Many architectures implement data types
  of a standard size. ints and floats are
  often 32-bit, chars 8-bit, and doubles are
  usually 64-bit.


Spring 2010        CS1600 Yanjun Li        34
Reference

n    Reproduced from the Cyber Classroom for
     C++, How to Program, 5/e by Deitel &
     Deitel.
n    Reproduced by permission of Pearson
     Education, Inc.




Spring 2010          CS1600 Yanjun Li          35

								
To top