Docstoc

basics - PowerPoint

Document Sample
basics - PowerPoint Powered By Docstoc
					Announcements
   HW1 will be assigned tomorrow or Wednesday
      Due Wednesday October 15, 19:30
      Homeworks will be assigned at SUCourse
      You will submit there too
   Homework will be explained in recitations
   Moreover, there will be important explanations about the
    homework submission procedure in recitations
      Submission is a tricky process, please do attend the
       recitations in order not to make a mistake
   SUCourse is ready
      You may reach the course web site
       http://people.sabanciuniv.edu/levi/cs201/ from SUCourse as
       well
      Lecture notes are at course web site.
   Assistant office hours are determined
      See details at course web site

    CS201 Introduction to Computing @ Sabancı University       1
Chapter 2
Writing and Understanding C++
    Writing programs in any language requires understanding
     the syntax and semantics of the programming language
       Syntax is similar to rules of spelling and grammar:
              • After main() you should put {
       Semantics is what a program means
    Approaches of learning programming languages
       Template based
              • Examine example programs and make analogies
              • Like a child learns how to speak
          First learn syntax and semantics, then start by writing
           small programs, ...
              • Like learning a foreign language
          Which one do you prefer?
          We will follow the second method


CS201 Introduction to Computing @ Sabancı University                 2
Towards Understanding of C++
    “Hello World” program. No biggie!
       #include <iostream>
       using namespace std;

       // traditional first program

      int main()
      {
          cout << "Hello world" << endl; /* display */
          return 0;
      }
    This program must be
       typed
       compiled (hello.cpp => hello.obj)
       linked (Build) (hello.obj and any other object modules linked
        together => project.exe)
       executed


CS201 Introduction to Computing @ Sabancı University                    3
Anatomy of a C++ Program
   Not all functions are defined in the core C++ language; some
    statements are in libraries
      In order to use them, you have to explicitly say so
   #include statements make libraries of functions accessible to
    the program
      Utility functions and tools that make the programmer’s life
       easier are defined in libraries
      Helps programmers develop code independently in a
       standard way
      Compiler needs access to interface, what the functions
       look like, but not to implementation of those functions
             • This is in the #included file
             • e.g.           #include <iostream>
               for input/output functions
   All programs that use standard C++ libraries should have
                       using namespace std;

    CS201 Introduction to Computing @ Sabancı University        4
        Anatomy of a C++ Program
   Comments make programs readable by humans (and by assistants!)
      Easier maintenance
      Try to use natural language, do not repeat the code!
         • Bad example
               area = pi*r*r; /* area is pi*r*r */
         • Better example
            area = pi*r*r; /* calculate area */
       Two ways of commenting
         • Using //     make the line comment line
         • Between /* and */
       Compiler disregards
        comments
       Comments in your homework
        affect your grades
       In VC++, comments are in green


         CS201 Introduction to Computing @ Sabancı University   5
Anatomy of a C++ Program
     Execution of the program begins with main
     Each program must have a main function
     Execution of C++ programs is organized as a sequence of
      statements
        Unless otherwise stated, statements execute
         sequentially one after another
               • Branching, repetition are possible (we will see them later)
           The main function returns a value to the operating
            system or the environment in which it is executed
               • return 0
               • Why 0? Because 0 means no problems encountered!




 CS201 Introduction to Computing @ Sabancı University                      6
Rules Rules Rules
     Now some syntax rules and definitions
     ABC of C++

     What is an “identifier”?
     Reserved words
     Symbols and compound symbols
     What is a “literal”?
        Types of literals
     Variables and basic types
     Where to use blanks, line breaks?
     Where to use semicolon?
     Basic Input/Output


 CS201 Introduction to Computing @ Sabancı University   7
    Identifiers
   Names of elements in a program
      Names of variables, functions, classes, etc.
   Sequence of letters (a .. z, A ..Z), digits (0 ..9) underscore _
   Cannot start with a digit
            number1                      valid
            number_1                     valid
            Me_myself                    valid
            1number                      not valid
   Do not start with an underscore
   Case sensitive
     Number1 and number1 are not the same
   Pick meaningful names in the context of your program and improve the
    self-readability of the code (do not use your boy/girlfriend’s name!)
   First occurrence of an identifier must be its declaration
        Standard declarations are in #include files
        We will see how to declare user-defined variables, functions, etc. as
         time goes by


     CS201 Introduction to Computing @ Sabancı University                  8
    Reserved Words (Keywords)
   Special and fixed meanings
      built-in in C++ language
      no need to have libraries to use them.
   Cannot be changed by programmer
      int
      return

       Full list is Table 2.1 of the textbook
       Full list also in MSDN:
           http://msdn.microsoft.com/en-us/library/aa245310(VS.60).aspx


   You cannot use a reserved word as a user-defined identifier
   In MS VC++, reserved words are automatically blue


     CS201 Introduction to Computing @ Sabancı University            9
Symbols
    Non-digit and non-letter characters with special meanings
    Mostly used as operators (some examples are below, full list later)
      + addition, sign
      - subtraction, minus
      = assignment
      / division
      *    multiplication
      % modulus
    Compound symbols (two consecutive symbols – one meaning),
     examples below, full list later
      /*
      */
      <<
      >>
      ==           equality comparison


    CS201 Introduction to Computing @ Sabancı University                   10
Literals
     Meaning: Fixed values
     Different format and rules for different types
        Integer
               3        454            -43              +343
           Real
               3.1415                       +45.44             -54.6   1.2334e3
               Last one is 1.2334 times 10 to the power 3 (scientific notation)
           String
               • Sequences of characters
               • Within double quotes (quotes are not part of the string)
               • Almost any character is fine (letters, digits, symbols)
               "Hello my friend"
               "10 is bigger"
               "10 > 22 ?"

 CS201 Introduction to Computing @ Sabancı University                             11
Variables and types
     Variables are used to store data that can change during program
        Memory locations of certain sizes
        Data input must be stored in a variable
        Results are stored in variables
        generally defined at the beginning of functions (no strict rule
          on the place of definition except being before the first use)
     Basic types (more to follow)
        Integer
                                                                Memory
               int list of identifiers separated by comma ;      number1    age
               int number1, age, deniz, selin;
                                                                  deniz    selin
               int num2;
           Real                                                      num2
               float list of identifiers separated by comma ;
               float area, circumference;                           area
               • There is another real type called double
                 that we will see later                          circumference
           String
               string list of identifiers separated by comma ;      myname
               string myname;

    CS201 Introduction to Computing @ Sabancı University                          12
    Arithmetic Operations
   Operators:    *       -    +       /   %
   Operands: values that operator combines
      variables or literals
   Combination of operators and operands is called expression
   Syntax and semantics for arithmetic operations
      Addition, subtraction: + and –,                   4
      for int, real (float and double)
            23 + 4                x + y                     d – 14.0 + 23     5 - 3 + 2
                                                                                             -1
        Multiplication: *, for int, real (float and double)
           23 * 4                     y * 3.0                  d * 23.1 * 4      5 – 3 * 2
        Division: /, different for int and real number types (double,
         float)
           • for int operands result is the integer part of division
           21 / 4 is 5           21 / 4.0 is 5.25               x / y
        Modulus: %, remainder of division, only for int
           21 % 4            is 1                    18 % 2 is 0                  x % y

     CS201 Introduction to Computing @ Sabancı University                                    13
Assignment Operator
                                                                   Memory
                    variable         =       expresion;
     To store a new value in a variable
     The value of expression becomes                       name      a     b
      the value of variable
     Previous value of variable is lost                             45     99
                                                          value

        int       a, b;
        a =       45;
        b =       a+54;
        a*b       = 332;                  wrong syntax

     Be careful about the types of left and right hand sides
        they must match
        compiler may or may not warn you

 CS201 Introduction to Computing @ Sabancı University                            14
         Example Program
   Write a program to calculate the area of a circle
        program first input a name and print a greeting
        input the radius
        calculate and display area
   identify literals, identifiers, symbols, variables and expressions in this program

#include <iostream>
#include <string>
using namespace std;

// area calculation program

int main()
{
   int radius;
   float area;
   string myname;
   cout << "Please enter your name: ";
   cin >> myname;
   cout << "Hello " << myname << "! Welcome to my area calculation program" << endl;
   cout << "Please enter the radius of your circle: ";
   cin >> radius;
   area = 3.14*radius*radius;
   cout << "the area is: " << area << endl;
   return 0;
}


         CS201 Introduction to Computing @ Sabancı University                            15
Issues
     What happens if the user enters a real number for radius?
        wrong result
        solution: real radius
     Can we combine
 cout << "Hello " << myname << "! Welcome to my area calculation program" << endl;
 cout << "Please enter the radius of your circle: ";

        Yes
     Can we eliminate the variable area?
        Yes




 CS201 Introduction to Computing @ Sabancı University                           16
Where to use Blanks
   You must have at least one blank
      between two words (identifiers or keywords)
             int count;
          between a word and numeric literal
             return 0;
   You cannot have a blank
      within a word (e.g. float cannot be written as flo at)
      within a compound symbol
             • e.g. != cannot be written as ! =
          within a literal
             • e.g. 3.14 cannot be written as 3           .    14
             • except string literals, in string literals blanks are blanks
   At all other places
      blanks are optional. E.g. a    =   5       ; is the same as a=5;
   Several blanks are functionally same as single blank
      except within string literals


    CS201 Introduction to Computing @ Sabancı University                      17
Where to use Line Breaks and Semicolon
     As a general rule, line breaks are possible whenever blank is
      possible
        exception: a string literal must start and finish on the
         same line
     Where to use a semicolon?
        general rule: at the end of a statement
        but there are exceptions
               • variable declaration: variable declaration is not a statement
                 but you have to use semicolon at the end of each
                 declaration
            it may be hard to identify the statements
               • is #include <iostream> a statement?
            an ability that will be gained over time


    CS201 Introduction to Computing @ Sabancı University                     18
    Stream output
   Output is an essential part of our programs
   cout (read as “see-out”) is the standard output stream (monitor),
   Accessible via #include<iostream>
   Objects are inserted onto stream with insertion operator <<
    Objects are literals, variables or expressions
      expressions are evaluated before output
      whatever exists within a string literal between " " are displayed
   Different objects separated by insertion operator <<
cout << "What a wonderful" << endl << "world" << endl;
cout << "gross = "                             What a wonderful
     << 12*12 << endl;                         world
cout << 5 << " in. = ";                        gross = 144
cout << 5*2.54 << " cm. " << endl;             5 in. = 12.7 cm.
   endl means “end of line” (defined in iostream)
        it causes the next output displayed at the beginning of the next line
        Line breaks in the program do not finish the output line in the
         output screen
     CS201 Introduction to Computing @ Sabancı University                   19
Stream Input
     cin (read as “see-in”)
         standard input stream (from keyboard)
         you can input only into variables
         extraction operator >> is used between cin and variables
        cin >> variable1 >> variable2 >> variable3 .......... ;

        int a, b, anynum;

        cin >> b >> anynum >> a;

     Data entry must be in the same order of variables in cin statement
        first the value for b, then the value for anynum, then the value
         of a must be entered by the user using the keyboard



 CS201 Introduction to Computing @ Sabancı University                 20
Stream Input
   You have to have at least one blank between any two input
    entry
      Multiple blanks are OK
   You may input values at several lines for a single cin
    statement
   You cannot display something using cin statement

   Type match between variable and the corresponding input
    value
      If mismatch then the input entry fails for the rest of the
       program
      But the values read up to that point are kept in the
       variables

   Important note on terminology
      “reading a value” means such an input


    CS201 Introduction to Computing @ Sabancı University            21
Stream Input – Example showing the
operation




 CS201 Introduction to Computing @ Sabancı University   22
Another Example Program
     Conversion from hours to minutes and seconds
     We will see two programs for the same job
        time.cpp uses three variables (for hours, minutes and
         seconds)
        time2.cpp uses just one variable




 CS201 Introduction to Computing @ Sabancı University            23

				
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
views:58
posted:9/28/2011
language:English
pages:23