SlideShare ist ein Scribd-Unternehmen logo
1 von 52
Lecture 3
            C++ Basics
              Part I




Computer Programming I   1
Outline
   Variables and Assignments
   Identifiers
   Keywords
   Input and Output
   Data Types and Expressions
   Arithmetic



    Computer Programming I       2
Variables and Assignments
 Variables are like small blackboards
   We can write a number on them
   We can change the number
   We can erase the number
 C++ variables are names for memory
  locations
   We can write a value in them
   We can change the value stored there
   We cannot erase the memory location
      Some value is always there (old content)

    Computer Programming I                        3
Identifiers
 Variables names are called identifiers
 Each piece of data in the computer is
  stored at a unique memory address
 Identifier names allow us to symbolically
  deal with the memory locations so that we
  don’t have to deal directly with these
  addresses
   e.g. total instead of 1001110001110001


  Computer Programming I                      4
Identifiers
                                                      Memory   Address
                                                                0000
                                                                0001
x is an integer variable                    4 bytes
                                                                0002
          int    x;                                             0003
c1 and c2 are character variable                                0005

         char         c1,                                       0007
                            char = 1 byte
                      c2;                                       0008
                                                                0009
                                                                0010
                                                                0011
f1 is a float variable
                                                                0012
       float    f1;          4 bytes
                                                                0013
                                                                0014




        Computer Programming I                                           5
Identifiers
Choosing variable names
   Use meaningful names that represent data to
    be stored
   First character must be
      a letter (a-z, A-Z)
      the underscore character (_)
   Remaining characters must be
      letters
      Numbers (letter (0-9)
      underscore character




   Computer Programming I                         6
Keywords
 Keywords (also called reserved words)
   Are used by the C++ language
   Must be used as they are defined in
    the programming language
   Cannot be used as identifiers




 Computer Programming I                   7
Keywords (example)




Computer Programming I     8
Declaring Variables
 Before use,,, variables must be declared

   Tells the compiler the type of data to store

    Examples: int       number_of_boxes;
                 double one_weight, total_weight;
   int is an abbreviation for integer.
      could store 3, 102, 3211, -456, etc.
      number_of_boxes is of type integer
   double represents numbers with a fractional
    component
      could store 1.34, 4.0, -345.6, etc.
      one_weight and total_weight are both of type double


   Computer Programming I                                    9
Declaring Variables
 Declaration syntax:
   Type_name    Variable_1 ,   Variable_2, . . . ;


 Declaration Examples:
     double average, m_score, total_score;
     double moon_distance;
     int age, num_students;
     int cars_waiting;




      Computer Programming I                          10
Assignment Statements
 An assignment statement changes the value of a
  variable
   total_weight = one_weight + number_of_bars;
      total_weight is set to the sum one_weight + number_of_bars

   Assignment statements end with a semi-colon

   The single variable to be changed is always on the left
    of the assignment operator ‘=‘

   On the right of the assignment operator can be
      Constants – age = 21;
      Variables -- my_cost = your_cost;
      Expressions – circumference = diameter * 3.14159;

   Computer Programming I                                      11
Initializing Variables
 Declaring a variable does not give it a value
    Giving a variable its first value is initializing the
     variable
 Variables are initialized in assignment statements

           double mpg;         // declare the variable
           mpg = 26.3;         // initialize the variable
 Declaration and initialization can be combined
  using two methods
    Method 1
            double mpg = 26.3, area = 0.0 , volume;
    Method 2
            double mpg(26.3), area(0.0), volume;

   Computer Programming I                                    12
Input and Output
 A data stream is a sequence of data
   Typically in the form of characters or numbers

 An input stream is data for the program to use
   Typically originates
      at the keyboard
      at a file

 An output stream is the program’s output
   Destination is typically
      the monitor
      a file

   Computer Programming I                            13
Output using cout
 cout is an output stream sending data to the
  monitor
 The insertion operator "<<" inserts data into cout
 Example:
         cout << number_of_box << " candy barsn";
   This line sends two items to the monitor
      The value of number_of_box
      The quoted string of characters " candy barsn"
          Notice the space before the ‘c’ in candy
          The ‘n’ causes a new line to be started following the ‘s’ in bars

      A new insertion operator is used for each item of output


   Computer Programming I                                                   14
Examples Using cout
 This produces the same result as the previous sample
            cout << number_of_bars ;
            cout << " candy barsn";

 Here arithmetic is performed in the cout statement
             cout << "Total cost is $" << (price + tax);

 Quoted strings are enclosed in double quotes ("Walter")
    Don’t use two single quotes (')
 A blank space can also be inserted with

              cout << " " ;
  if there are no strings in which a space is desired as
  in " candy barsn"
    Computer Programming I                                 15
Escape Sequences
 Escape sequences tell the compiler to treat
  characters in a special way
 '' is the escape character
     To create a newline in output use
               n – cout << "n";
           or the newer alternative
                     cout << endl;

     Other escape sequences:
              t  -- a tab
                -- a backslash character
              "  -- a quote character


   Computer Programming I                       16
Escape Sequences
            ASCII char     Symbolic Name
          Null character        ‘0’
          Alert (bell)          ‘a’
          Backspace             ‘b’
          Horizontal tab         ‘t’
          New line              ‘n’
          Vertical tab          ‘v’
          Form feed              ‘f’
          Carriage               ‘r’
          return                 ‘’’
          Single quote           ‘”’
          Double quote           ‘’
          Backslash


Computer Programming I                     17
Formatting Real Numbers
 Real numbers (type double) produce a variety of
  outputs

     double price = 78.5;
     cout << "The price is $" << price << endl;

   The output could be any of these:
                  The price is $78.5
                  The price is $78.500000
                  The price is $7.850000e01
   The most unlikely output is:
                  The price is $78.50

   Computer Programming I                         18
Showing Decimal Places
 cout includes tools to specify the output of type double

 To specify fixed point notation
    setf(ios::fixed)
 To specify that the decimal point will always be shown
    setf(ios::showpoint)
 To specify that two decimal places will always be shown
    precision(2)

 Example:      cout.setf (ios::fixed);
                cout.setf (ios::showpoint);
                cout.precision (2);
                cout << "The price is " << 1.234 << endl;


    Computer Programming I                                   19
Input Using cin
 cin is an input stream bringing data from the keyboard
 The extraction operator (>>) removes data to be used
 Example:
       cout << "Enter the number of bars in a packagen";
       cout << " and the weight in ounces of one bar.n";
       cin >> number_of_box;
       cin >> one_weight;
 This code prompts the user to enter data then
  reads two data items from cin
    The first value read is stored in number_of_bars
    The second value read is stored in one_weight
    Data is separated by spaces when entered



   Computer Programming I                                   20
Reading Data From cin
 Multiple data items are separated by spaces
 Data is not read until the enter key is pressed
   Allows user to make corrections

 Example:
             cin >> v1 >> v2 >> v3;

   Requires three space separated values
   User might type
            34 45 12 <enter key>


   Computer Programming I                           21
Designing Input and Output
 Prompt the user for input that is desired
   cout statements provide instructions

           cout << "Enter your age: ";
           cin >> age;
      Notice the absence of a new line before using cin
 Echo the input by displaying what was read
   Gives the user a chance to verify data

    cout << age << " was entered." << endl;
   Computer Programming I                                  22
Data Types and Expressions
 2 and 2.0 are not the same number
   A whole number such as 2 is of type int
   A real number such as 2.0 is of type double

 Numbers of type int are stored as exact values
 Numbers of type double may be stored as
  approximate
  values due to limitations on number of significant
  digits that can be represented


   Computer Programming I                         23
Writing Integer constants
 Type int does not contain decimal points
      Examples:    34 45 1 89




  Computer Programming I                     24
Writing Double Constants
 Type double can be written in two ways
   Simple form must include a decimal point
      Examples:   34.1 23.0034    1.0 89.9

   Floating Point Notation (Scientific Notation)
      Examples: 3.41e1    means         34.1
                 3.67e17   means         367000000000000000.0
                 5.89e-6   means         0.00000589
   Number left of e does not require a decimal point
   Exponent cannot contain a decimal point



   Computer Programming I                                 25
Other Number Types
 Various number types have different
  memory requirements
   More precision requires more bytes of memory
   Very large numbers require more bytes of
    memory
   Very small numbers require more bytes of
    memory




  Computer Programming I                      26
Some number types
Type Name         Memory Used    Size Range          Precision

short             2 bytes        -32,767 to          NA
                                 32,767
int               4 bytes        -2,147,483,647   NA
                                 to 2,147,483,647
long              4 bytes        -2,147,483,647   NA
                                 to 2,147,483,647
float             4 bytes        Approximately       7 digits
                                 10-38 to 1038
double            8 bytes        Approximately       15 digits
                                 10-308 to 10308
long double       10 bytes       Approximately       19 digits
                                 10-4932 to 104932

        Computer Programming I                                   27
Integer types
 long or long int (often 4 bytes)
   Equivalent forms to declare very large integers

                 long big_total;
                 long int big_total;

 short or short int (often 2 bytes)
   Equivalent forms to declare smaller integers

                 short small_total;
                 short int small_total;

   Computer Programming I                          28
Floating point types
 long double (often 10 bytes)
   Declares floating point numbers with up to
    19 significant digits

           long double big_number;

 float (often 4 bytes)
   Declares floating point numbers with up to
    7 significant digits

           float not_so_big_number;

   Computer Programming I                        29
Type char
 Computers process character data too
 char
   Short for character
   Can be any single character from the keyboard

 To declare a variable of type char:

                 char letter;

   Computer Programming I                      30
char constants
 Character constants are enclosed in single quotes

                   char letter = 'a';

 Strings of characters, even if only one character
  is enclosed in double quotes
   "a" is a string of characters containing one character
   'a' is a value of type character




   Computer Programming I                                    31
Reading Character Data
 cin skips blanks and line breaks looking for data
 The following reads two characters but skips
  any space that might be between
           char symbol1, symbol2;
           cin >> symbol1 >> symbol2;

 User normally separate data items by spaces
                      J D
 Results are the same if the data is not separated
  by spaces
                      JD

   Computer Programming I                         32
Type bool
 bool is a new addition to C++
   Short for boolean
   Boolean values are either true or false

 To declare a variable of type bool:

                 bool old_enough;



   Computer Programming I                     33
Type Compatibilities
 In general store values in variables of the
  same type
   This is a type mismatch:

            int int_variable;
            int_variable = 2.99;

   If your compiler allows this, int_variable will
    most likely contain the value 2, not 2.99


   Computer Programming I                             34
int  double
 Variables of type double should not be
  assigned to variables of type int

           int       int_variable;
           double double_variable;
           double_variable = 2.00;
           int_variable = double_variable;

   If allowed, int_variable contains 2, not 2.00

  Computer Programming I                            35
int  double
 Integer values can normally be stored in
  variables of type double

          double double_variable;
          double_variable = 2;

   double_variable will contain 2.0




  Computer Programming I                     36
char   int
 The following actions are possible but
  generally not recommended!
 It is possible to store char values in integer
  variables
                 int value = 'A';
  value will contain an integer representing 'A'

 It is possible to store int values in char
  variables
                 char letter = 65;
   Computer Programming I                      37
The ASCII
Character
Set




   Computer Programming I   38
bool   int
 The following actions are possible but generally
   not recommended!
 Values of type bool can be assigned to int
  variables
   True is stored as 1
   False is stored as 0
 Values of type int can be assigned to bool
  variables
   Any non-zero integer is stored as true
   Zero is stored as false

   Computer Programming I                            39
Arithmetic
 Arithmetic is performed with operators
     +    for addition
     -    for subtraction
     *   for multiplication
     /    for division

 Example: storing a product in the variable
            total_weight

  total_weight = one_weight * number_of_bars;

   Computer Programming I                       40
Results of Operators
 Arithmetic operators can be used with any
  numeric type
 An operand is a number or variable
  used by the operator
 Result of an operator depends on the types

 of operands
   If both operands are int, the result is int
   If one or both operands are double, the result is
    double
  Computer Programming I                          41
Division of Doubles
 Division with at least one operator of type double
  produces the expected results.

               double divisor, dividend, quotient;
               divisor = 3;
               dividend = 5;
               quotient = dividend / divisor;

   quotient = 1.6666…
   Result is the same if either dividend or divisor is
    of type int

   Computer Programming I                                 42
Division of Integers
 Be careful with the division operator!
    int / int produces an integer result
       (true for variables or numeric constants)

             int dividend, divisor, quotient;
             dividend = 5;
             divisor = 3;
             quotient = dividend / divisor;

    The value of quotient is 1, not 1.666…
    Integer division does not round the result, the
     fractional part is discarded!

   Computer Programming I                              43
Computer Programming I   44
Integer Remainders
 %(mod) operator gives the remainder from
  integer division

          int dividend, divisor, remainder;
          dividend = 5;
          divisor = 3;
          remainder = dividend % divisor;

   The value of remainder is 2
  Computer Programming I                      45
Arithmetic Expressions
 Use spacing to make expressions readable
   Which is easier to read?

               x+y*z        or   x+y*z
 Precedence rules for operators are the
  same as used in your algebra classes
 Use parentheses to alter the order of
  operations
    x+y*z      ( y is multiplied by z first)
   (x + y) * z ( x and y are added first)
   Computer Programming I                      46
Operator Shorthand
 Some expressions occur so often that C++
  contains to shorthand operators for them
 All arithmetic operators can be used this way
   += count = count + 2; becomes
        count += 2;
   *= bonus = bonus * 2; becomes
       bonus *= 2;
   /= time = time / rush_factor; becomes
        time /= rush_factor;
   %= remainder = remainder % (cnt1+ cnt2); becomes
        remainder %= (cnt1 + cnt2);

   Computer Programming I                          47
Increment/Decrement
 Unary operators require only one operand
    + in front of a number such as +5
    - in front of a number such as -5
 ++    increment operator
    Adds 1 to the value of a variable
                        x ++;
     is equivalent to   x = x + 1;
 --   decrement operator
    Subtracts 1 from the value of a variable
                        x --;
     is equivalent to   x = x – 1;

   Computer Programming I                       48
Exercises
1)    X += 1                  1)   X=X+1
2)    X *= Y                  2)   X=X*Y
3)    X += X – Y * Z          3)   X=X+(X–Y*Z)
4)    X++                     4)   X =X + 1
5)    X *= 2                  5)   X=X*2
6)    X *= Y * Z              6)   X=X*Y*Z
7)    X %= X / Y              7)   X=X % ( X / Y )
8)    X--                     8)   X =X - 1


     Computer Programming I                      49
Precedenc
Precedence           Operators        Precedence
    e
Table                Postfix ++, --   Highest
                     Prefix ++, --
Parentheses ( )      Unary +,-
                     *, /, %
                     Binary +, -
                     <, <=, >=, >
                     = =, !=
                     &&
                     ||
                     =                Lowest

    Computer Programming I                         50
Comparison Operators
Math Symbol   English                 C++        C++ Sample
                                      Notation
    =         equal to                   ==      x + 7 = = 2*y

    ≠         not equal to                !=     Abc != ’n’

    <         less than                   <      count < m +
                                                 3
    ≤         less than or equal to       <=     time <= limit

    >         greater than                 >     time > limit

    ≥         greater than or equal       >=     age >= 21
              to



    Computer Programming I                                    51
End




Computer Programming I    52

Weitere ähnliche Inhalte

Was ist angesagt?

Basics of c++ Programming Language
Basics of c++ Programming LanguageBasics of c++ Programming Language
Basics of c++ Programming LanguageAhmad Idrees
 
Intro To Programming Concepts
Intro To Programming ConceptsIntro To Programming Concepts
Intro To Programming ConceptsJussi Pohjolainen
 
Pseudocode algorithim flowchart
Pseudocode algorithim flowchartPseudocode algorithim flowchart
Pseudocode algorithim flowchartfika sweety
 
Chapter 1 - An Introduction to Programming
Chapter 1 - An Introduction to ProgrammingChapter 1 - An Introduction to Programming
Chapter 1 - An Introduction to Programmingmshellman
 
Principles of-programming-languages-lecture-notes-
Principles of-programming-languages-lecture-notes-Principles of-programming-languages-lecture-notes-
Principles of-programming-languages-lecture-notes-Krishna Sai
 
Programming Fundamentals lecture 2
Programming Fundamentals lecture 2Programming Fundamentals lecture 2
Programming Fundamentals lecture 2REHAN IJAZ
 
Computer Programming Overview
Computer Programming OverviewComputer Programming Overview
Computer Programming Overviewagorolabs
 
Programming Fundamental Presentation
Programming Fundamental PresentationProgramming Fundamental Presentation
Programming Fundamental Presentationfazli khaliq
 
Introduction to programming
Introduction to programmingIntroduction to programming
Introduction to programmingNeeru Mittal
 
Programming Fundamentals lecture 1
Programming Fundamentals lecture 1Programming Fundamentals lecture 1
Programming Fundamentals lecture 1REHAN IJAZ
 
pseudocode and Flowchart
pseudocode and Flowchartpseudocode and Flowchart
pseudocode and FlowchartALI RAZA
 
1. over view and history of c
1. over view and history of c1. over view and history of c
1. over view and history of cHarish Kumawat
 

Was ist angesagt? (20)

Basics of c++ Programming Language
Basics of c++ Programming LanguageBasics of c++ Programming Language
Basics of c++ Programming Language
 
Intro To Programming Concepts
Intro To Programming ConceptsIntro To Programming Concepts
Intro To Programming Concepts
 
Pseudocode algorithim flowchart
Pseudocode algorithim flowchartPseudocode algorithim flowchart
Pseudocode algorithim flowchart
 
Chapter 1 - An Introduction to Programming
Chapter 1 - An Introduction to ProgrammingChapter 1 - An Introduction to Programming
Chapter 1 - An Introduction to Programming
 
C++ How to program
C++ How to programC++ How to program
C++ How to program
 
C++ book
C++ bookC++ book
C++ book
 
Principles of-programming-languages-lecture-notes-
Principles of-programming-languages-lecture-notes-Principles of-programming-languages-lecture-notes-
Principles of-programming-languages-lecture-notes-
 
Programming Fundamentals lecture 2
Programming Fundamentals lecture 2Programming Fundamentals lecture 2
Programming Fundamentals lecture 2
 
Computer Programming Overview
Computer Programming OverviewComputer Programming Overview
Computer Programming Overview
 
Programming Fundamental Presentation
Programming Fundamental PresentationProgramming Fundamental Presentation
Programming Fundamental Presentation
 
Introduction to c++ ppt
Introduction to c++ pptIntroduction to c++ ppt
Introduction to c++ ppt
 
Pseudocode
PseudocodePseudocode
Pseudocode
 
Introduction to programming
Introduction to programmingIntroduction to programming
Introduction to programming
 
Programming Fundamentals lecture 1
Programming Fundamentals lecture 1Programming Fundamentals lecture 1
Programming Fundamentals lecture 1
 
C++ ppt
C++ pptC++ ppt
C++ ppt
 
Abc c program
Abc c programAbc c program
Abc c program
 
Fundamentals of Programming Chapter 2
Fundamentals of Programming Chapter 2Fundamentals of Programming Chapter 2
Fundamentals of Programming Chapter 2
 
pseudocode and Flowchart
pseudocode and Flowchartpseudocode and Flowchart
pseudocode and Flowchart
 
Introduction to c++ ppt 1
Introduction to c++ ppt 1Introduction to c++ ppt 1
Introduction to c++ ppt 1
 
1. over view and history of c
1. over view and history of c1. over view and history of c
1. over view and history of c
 

Andere mochten auch

Andere mochten auch (7)

Lecture 12: Classes and Files
Lecture 12: Classes and FilesLecture 12: Classes and Files
Lecture 12: Classes and Files
 
Computer Programming- Lecture 6
Computer Programming- Lecture 6Computer Programming- Lecture 6
Computer Programming- Lecture 6
 
Computer Programming- Lecture 8
Computer Programming- Lecture 8Computer Programming- Lecture 8
Computer Programming- Lecture 8
 
Computer Programming- Lecture 11
Computer Programming- Lecture 11Computer Programming- Lecture 11
Computer Programming- Lecture 11
 
Computer Programming- Lecture 7
Computer Programming- Lecture 7Computer Programming- Lecture 7
Computer Programming- Lecture 7
 
Computer Programming- Lecture 9
Computer Programming- Lecture 9Computer Programming- Lecture 9
Computer Programming- Lecture 9
 
Computer Programming- Lecture 10
Computer Programming- Lecture 10Computer Programming- Lecture 10
Computer Programming- Lecture 10
 

Ähnlich wie Computer Programming- Lecture 3

C++ Tutorial.docx
C++ Tutorial.docxC++ Tutorial.docx
C++ Tutorial.docxPinkiVats1
 
02a fundamental c++ types, arithmetic
02a   fundamental c++ types, arithmetic 02a   fundamental c++ types, arithmetic
02a fundamental c++ types, arithmetic Manzoor ALam
 
presentation_c_basics_1589366177_381682.pptx
presentation_c_basics_1589366177_381682.pptxpresentation_c_basics_1589366177_381682.pptx
presentation_c_basics_1589366177_381682.pptxKrishanPalSingh39
 
presentation_data_types_and_operators_1513499834_241350.pptx
presentation_data_types_and_operators_1513499834_241350.pptxpresentation_data_types_and_operators_1513499834_241350.pptx
presentation_data_types_and_operators_1513499834_241350.pptxKrishanPalSingh39
 
T02 a firstcprogram
T02 a firstcprogramT02 a firstcprogram
T02 a firstcprogramprincepavan
 
T02 a firstcprogram
T02 a firstcprogramT02 a firstcprogram
T02 a firstcprogramprincepavan
 
C++ lesson variables.pptx
C++ lesson variables.pptxC++ lesson variables.pptx
C++ lesson variables.pptxCynthia Agabin
 
C++ and OOPS Crash Course by ACM DBIT | Grejo Joby
C++ and OOPS Crash Course by ACM DBIT | Grejo JobyC++ and OOPS Crash Course by ACM DBIT | Grejo Joby
C++ and OOPS Crash Course by ACM DBIT | Grejo JobyGrejoJoby1
 
CHAPTER-2.ppt
CHAPTER-2.pptCHAPTER-2.ppt
CHAPTER-2.pptTekle12
 

Ähnlich wie Computer Programming- Lecture 3 (20)

C++ basics
C++ basicsC++ basics
C++ basics
 
keyword
keywordkeyword
keyword
 
keyword
keywordkeyword
keyword
 
C++ Tutorial.docx
C++ Tutorial.docxC++ Tutorial.docx
C++ Tutorial.docx
 
02a fundamental c++ types, arithmetic
02a   fundamental c++ types, arithmetic 02a   fundamental c++ types, arithmetic
02a fundamental c++ types, arithmetic
 
L03vars
L03varsL03vars
L03vars
 
Declaration of variables
Declaration of variablesDeclaration of variables
Declaration of variables
 
C++ programming
C++ programmingC++ programming
C++ programming
 
presentation_c_basics_1589366177_381682.pptx
presentation_c_basics_1589366177_381682.pptxpresentation_c_basics_1589366177_381682.pptx
presentation_c_basics_1589366177_381682.pptx
 
Chapter2
Chapter2Chapter2
Chapter2
 
Savitch Ch 02
Savitch Ch 02Savitch Ch 02
Savitch Ch 02
 
Savitch Ch 02
Savitch Ch 02Savitch Ch 02
Savitch Ch 02
 
presentation_data_types_and_operators_1513499834_241350.pptx
presentation_data_types_and_operators_1513499834_241350.pptxpresentation_data_types_and_operators_1513499834_241350.pptx
presentation_data_types_and_operators_1513499834_241350.pptx
 
Savitch ch 02
Savitch ch 02Savitch ch 02
Savitch ch 02
 
T02 a firstcprogram
T02 a firstcprogramT02 a firstcprogram
T02 a firstcprogram
 
T02 a firstcprogram
T02 a firstcprogramT02 a firstcprogram
T02 a firstcprogram
 
C++ lesson variables.pptx
C++ lesson variables.pptxC++ lesson variables.pptx
C++ lesson variables.pptx
 
C++ and OOPS Crash Course by ACM DBIT | Grejo Joby
C++ and OOPS Crash Course by ACM DBIT | Grejo JobyC++ and OOPS Crash Course by ACM DBIT | Grejo Joby
C++ and OOPS Crash Course by ACM DBIT | Grejo Joby
 
CHAPTER-2.ppt
CHAPTER-2.pptCHAPTER-2.ppt
CHAPTER-2.ppt
 
Introduction To C
Introduction To CIntroduction To C
Introduction To C
 

Kürzlich hochgeladen

ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfVanessa Camilleri
 
Sulphonamides, mechanisms and their uses
Sulphonamides, mechanisms and their usesSulphonamides, mechanisms and their uses
Sulphonamides, mechanisms and their usesVijayaLaxmi84
 
Mythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWMythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWQuiz Club NITW
 
How to Make a Duplicate of Your Odoo 17 Database
How to Make a Duplicate of Your Odoo 17 DatabaseHow to Make a Duplicate of Your Odoo 17 Database
How to Make a Duplicate of Your Odoo 17 DatabaseCeline George
 
4.9.24 School Desegregation in Boston.pptx
4.9.24 School Desegregation in Boston.pptx4.9.24 School Desegregation in Boston.pptx
4.9.24 School Desegregation in Boston.pptxmary850239
 
MS4 level being good citizen -imperative- (1) (1).pdf
MS4 level   being good citizen -imperative- (1) (1).pdfMS4 level   being good citizen -imperative- (1) (1).pdf
MS4 level being good citizen -imperative- (1) (1).pdfMr Bounab Samir
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptxmary850239
 
ARTERIAL BLOOD GAS ANALYSIS........pptx
ARTERIAL BLOOD  GAS ANALYSIS........pptxARTERIAL BLOOD  GAS ANALYSIS........pptx
ARTERIAL BLOOD GAS ANALYSIS........pptxAneriPatwari
 
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptx
Unraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptxUnraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptx
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptxDhatriParmar
 
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQ-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQuiz Club NITW
 
Congestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationCongestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationdeepaannamalai16
 
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...Nguyen Thanh Tu Collection
 
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxGrade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxkarenfajardo43
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxlancelewisportillo
 
Textual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSTextual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSMae Pangan
 
How to Fix XML SyntaxError in Odoo the 17
How to Fix XML SyntaxError in Odoo the 17How to Fix XML SyntaxError in Odoo the 17
How to Fix XML SyntaxError in Odoo the 17Celine George
 
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxBIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxSayali Powar
 
ICS 2208 Lecture Slide Notes for Topic 6
ICS 2208 Lecture Slide Notes for Topic 6ICS 2208 Lecture Slide Notes for Topic 6
ICS 2208 Lecture Slide Notes for Topic 6Vanessa Camilleri
 

Kürzlich hochgeladen (20)

ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdf
 
Sulphonamides, mechanisms and their uses
Sulphonamides, mechanisms and their usesSulphonamides, mechanisms and their uses
Sulphonamides, mechanisms and their uses
 
Mythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWMythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITW
 
How to Make a Duplicate of Your Odoo 17 Database
How to Make a Duplicate of Your Odoo 17 DatabaseHow to Make a Duplicate of Your Odoo 17 Database
How to Make a Duplicate of Your Odoo 17 Database
 
4.9.24 School Desegregation in Boston.pptx
4.9.24 School Desegregation in Boston.pptx4.9.24 School Desegregation in Boston.pptx
4.9.24 School Desegregation in Boston.pptx
 
MS4 level being good citizen -imperative- (1) (1).pdf
MS4 level   being good citizen -imperative- (1) (1).pdfMS4 level   being good citizen -imperative- (1) (1).pdf
MS4 level being good citizen -imperative- (1) (1).pdf
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx
 
ARTERIAL BLOOD GAS ANALYSIS........pptx
ARTERIAL BLOOD  GAS ANALYSIS........pptxARTERIAL BLOOD  GAS ANALYSIS........pptx
ARTERIAL BLOOD GAS ANALYSIS........pptx
 
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptx
Unraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptxUnraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptx
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptx
 
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQ-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
 
Faculty Profile prashantha K EEE dept Sri Sairam college of Engineering
Faculty Profile prashantha K EEE dept Sri Sairam college of EngineeringFaculty Profile prashantha K EEE dept Sri Sairam college of Engineering
Faculty Profile prashantha K EEE dept Sri Sairam college of Engineering
 
Congestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationCongestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentation
 
Mattingly "AI & Prompt Design: Large Language Models"
Mattingly "AI & Prompt Design: Large Language Models"Mattingly "AI & Prompt Design: Large Language Models"
Mattingly "AI & Prompt Design: Large Language Models"
 
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
 
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxGrade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
 
Textual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSTextual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHS
 
How to Fix XML SyntaxError in Odoo the 17
How to Fix XML SyntaxError in Odoo the 17How to Fix XML SyntaxError in Odoo the 17
How to Fix XML SyntaxError in Odoo the 17
 
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxBIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
 
ICS 2208 Lecture Slide Notes for Topic 6
ICS 2208 Lecture Slide Notes for Topic 6ICS 2208 Lecture Slide Notes for Topic 6
ICS 2208 Lecture Slide Notes for Topic 6
 

Computer Programming- Lecture 3

  • 1. Lecture 3 C++ Basics Part I Computer Programming I 1
  • 2. Outline  Variables and Assignments  Identifiers  Keywords  Input and Output  Data Types and Expressions  Arithmetic Computer Programming I 2
  • 3. Variables and Assignments  Variables are like small blackboards  We can write a number on them  We can change the number  We can erase the number  C++ variables are names for memory locations  We can write a value in them  We can change the value stored there  We cannot erase the memory location  Some value is always there (old content) Computer Programming I 3
  • 4. Identifiers  Variables names are called identifiers  Each piece of data in the computer is stored at a unique memory address  Identifier names allow us to symbolically deal with the memory locations so that we don’t have to deal directly with these addresses  e.g. total instead of 1001110001110001 Computer Programming I 4
  • 5. Identifiers Memory Address 0000 0001 x is an integer variable 4 bytes 0002 int x; 0003 c1 and c2 are character variable 0005 char c1, 0007 char = 1 byte c2; 0008 0009 0010 0011 f1 is a float variable 0012 float f1; 4 bytes 0013 0014 Computer Programming I 5
  • 6. Identifiers Choosing variable names  Use meaningful names that represent data to be stored  First character must be  a letter (a-z, A-Z)  the underscore character (_)  Remaining characters must be  letters  Numbers (letter (0-9)  underscore character Computer Programming I 6
  • 7. Keywords  Keywords (also called reserved words)  Are used by the C++ language  Must be used as they are defined in the programming language  Cannot be used as identifiers Computer Programming I 7
  • 9. Declaring Variables  Before use,,, variables must be declared  Tells the compiler the type of data to store Examples: int number_of_boxes; double one_weight, total_weight;  int is an abbreviation for integer.  could store 3, 102, 3211, -456, etc.  number_of_boxes is of type integer  double represents numbers with a fractional component  could store 1.34, 4.0, -345.6, etc.  one_weight and total_weight are both of type double Computer Programming I 9
  • 10. Declaring Variables  Declaration syntax:  Type_name Variable_1 , Variable_2, . . . ;  Declaration Examples:  double average, m_score, total_score;  double moon_distance;  int age, num_students;  int cars_waiting; Computer Programming I 10
  • 11. Assignment Statements  An assignment statement changes the value of a variable  total_weight = one_weight + number_of_bars;  total_weight is set to the sum one_weight + number_of_bars  Assignment statements end with a semi-colon  The single variable to be changed is always on the left of the assignment operator ‘=‘  On the right of the assignment operator can be  Constants – age = 21;  Variables -- my_cost = your_cost;  Expressions – circumference = diameter * 3.14159; Computer Programming I 11
  • 12. Initializing Variables  Declaring a variable does not give it a value  Giving a variable its first value is initializing the variable  Variables are initialized in assignment statements double mpg; // declare the variable mpg = 26.3; // initialize the variable  Declaration and initialization can be combined using two methods  Method 1 double mpg = 26.3, area = 0.0 , volume;  Method 2 double mpg(26.3), area(0.0), volume; Computer Programming I 12
  • 13. Input and Output  A data stream is a sequence of data  Typically in the form of characters or numbers  An input stream is data for the program to use  Typically originates  at the keyboard  at a file  An output stream is the program’s output  Destination is typically  the monitor  a file Computer Programming I 13
  • 14. Output using cout  cout is an output stream sending data to the monitor  The insertion operator "<<" inserts data into cout  Example: cout << number_of_box << " candy barsn";  This line sends two items to the monitor  The value of number_of_box  The quoted string of characters " candy barsn"  Notice the space before the ‘c’ in candy  The ‘n’ causes a new line to be started following the ‘s’ in bars  A new insertion operator is used for each item of output Computer Programming I 14
  • 15. Examples Using cout  This produces the same result as the previous sample cout << number_of_bars ; cout << " candy barsn";  Here arithmetic is performed in the cout statement cout << "Total cost is $" << (price + tax);  Quoted strings are enclosed in double quotes ("Walter")  Don’t use two single quotes (')  A blank space can also be inserted with cout << " " ; if there are no strings in which a space is desired as in " candy barsn" Computer Programming I 15
  • 16. Escape Sequences  Escape sequences tell the compiler to treat characters in a special way  '' is the escape character  To create a newline in output use n – cout << "n"; or the newer alternative cout << endl;  Other escape sequences: t -- a tab -- a backslash character " -- a quote character Computer Programming I 16
  • 17. Escape Sequences ASCII char Symbolic Name Null character ‘0’ Alert (bell) ‘a’ Backspace ‘b’ Horizontal tab ‘t’ New line ‘n’ Vertical tab ‘v’ Form feed ‘f’ Carriage ‘r’ return ‘’’ Single quote ‘”’ Double quote ‘’ Backslash Computer Programming I 17
  • 18. Formatting Real Numbers  Real numbers (type double) produce a variety of outputs double price = 78.5; cout << "The price is $" << price << endl;  The output could be any of these: The price is $78.5 The price is $78.500000 The price is $7.850000e01  The most unlikely output is: The price is $78.50 Computer Programming I 18
  • 19. Showing Decimal Places  cout includes tools to specify the output of type double  To specify fixed point notation  setf(ios::fixed)  To specify that the decimal point will always be shown  setf(ios::showpoint)  To specify that two decimal places will always be shown  precision(2)  Example: cout.setf (ios::fixed); cout.setf (ios::showpoint); cout.precision (2); cout << "The price is " << 1.234 << endl; Computer Programming I 19
  • 20. Input Using cin  cin is an input stream bringing data from the keyboard  The extraction operator (>>) removes data to be used  Example: cout << "Enter the number of bars in a packagen"; cout << " and the weight in ounces of one bar.n"; cin >> number_of_box; cin >> one_weight;  This code prompts the user to enter data then reads two data items from cin  The first value read is stored in number_of_bars  The second value read is stored in one_weight  Data is separated by spaces when entered Computer Programming I 20
  • 21. Reading Data From cin  Multiple data items are separated by spaces  Data is not read until the enter key is pressed  Allows user to make corrections  Example: cin >> v1 >> v2 >> v3;  Requires three space separated values  User might type 34 45 12 <enter key> Computer Programming I 21
  • 22. Designing Input and Output  Prompt the user for input that is desired  cout statements provide instructions cout << "Enter your age: "; cin >> age;  Notice the absence of a new line before using cin  Echo the input by displaying what was read  Gives the user a chance to verify data cout << age << " was entered." << endl; Computer Programming I 22
  • 23. Data Types and Expressions  2 and 2.0 are not the same number  A whole number such as 2 is of type int  A real number such as 2.0 is of type double  Numbers of type int are stored as exact values  Numbers of type double may be stored as approximate values due to limitations on number of significant digits that can be represented Computer Programming I 23
  • 24. Writing Integer constants  Type int does not contain decimal points  Examples: 34 45 1 89 Computer Programming I 24
  • 25. Writing Double Constants  Type double can be written in two ways  Simple form must include a decimal point  Examples: 34.1 23.0034 1.0 89.9  Floating Point Notation (Scientific Notation)  Examples: 3.41e1 means 34.1 3.67e17 means 367000000000000000.0 5.89e-6 means 0.00000589  Number left of e does not require a decimal point  Exponent cannot contain a decimal point Computer Programming I 25
  • 26. Other Number Types  Various number types have different memory requirements  More precision requires more bytes of memory  Very large numbers require more bytes of memory  Very small numbers require more bytes of memory Computer Programming I 26
  • 27. Some number types Type Name Memory Used Size Range Precision short 2 bytes -32,767 to NA 32,767 int 4 bytes -2,147,483,647 NA to 2,147,483,647 long 4 bytes -2,147,483,647 NA to 2,147,483,647 float 4 bytes Approximately 7 digits 10-38 to 1038 double 8 bytes Approximately 15 digits 10-308 to 10308 long double 10 bytes Approximately 19 digits 10-4932 to 104932 Computer Programming I 27
  • 28. Integer types  long or long int (often 4 bytes)  Equivalent forms to declare very large integers long big_total; long int big_total;  short or short int (often 2 bytes)  Equivalent forms to declare smaller integers short small_total; short int small_total; Computer Programming I 28
  • 29. Floating point types  long double (often 10 bytes)  Declares floating point numbers with up to 19 significant digits long double big_number;  float (often 4 bytes)  Declares floating point numbers with up to 7 significant digits float not_so_big_number; Computer Programming I 29
  • 30. Type char  Computers process character data too  char  Short for character  Can be any single character from the keyboard  To declare a variable of type char: char letter; Computer Programming I 30
  • 31. char constants  Character constants are enclosed in single quotes char letter = 'a';  Strings of characters, even if only one character is enclosed in double quotes  "a" is a string of characters containing one character  'a' is a value of type character Computer Programming I 31
  • 32. Reading Character Data  cin skips blanks and line breaks looking for data  The following reads two characters but skips any space that might be between char symbol1, symbol2; cin >> symbol1 >> symbol2;  User normally separate data items by spaces J D  Results are the same if the data is not separated by spaces JD Computer Programming I 32
  • 33. Type bool  bool is a new addition to C++  Short for boolean  Boolean values are either true or false  To declare a variable of type bool: bool old_enough; Computer Programming I 33
  • 34. Type Compatibilities  In general store values in variables of the same type  This is a type mismatch: int int_variable; int_variable = 2.99;  If your compiler allows this, int_variable will most likely contain the value 2, not 2.99 Computer Programming I 34
  • 35. int  double  Variables of type double should not be assigned to variables of type int int int_variable; double double_variable; double_variable = 2.00; int_variable = double_variable;  If allowed, int_variable contains 2, not 2.00 Computer Programming I 35
  • 36. int  double  Integer values can normally be stored in variables of type double double double_variable; double_variable = 2;  double_variable will contain 2.0 Computer Programming I 36
  • 37. char   int  The following actions are possible but generally not recommended!  It is possible to store char values in integer variables int value = 'A'; value will contain an integer representing 'A'  It is possible to store int values in char variables char letter = 65; Computer Programming I 37
  • 38. The ASCII Character Set Computer Programming I 38
  • 39. bool   int  The following actions are possible but generally not recommended!  Values of type bool can be assigned to int variables  True is stored as 1  False is stored as 0  Values of type int can be assigned to bool variables  Any non-zero integer is stored as true  Zero is stored as false Computer Programming I 39
  • 40. Arithmetic  Arithmetic is performed with operators  + for addition  - for subtraction  * for multiplication  / for division  Example: storing a product in the variable total_weight total_weight = one_weight * number_of_bars; Computer Programming I 40
  • 41. Results of Operators  Arithmetic operators can be used with any numeric type  An operand is a number or variable used by the operator  Result of an operator depends on the types of operands  If both operands are int, the result is int  If one or both operands are double, the result is double Computer Programming I 41
  • 42. Division of Doubles  Division with at least one operator of type double produces the expected results. double divisor, dividend, quotient; divisor = 3; dividend = 5; quotient = dividend / divisor;  quotient = 1.6666…  Result is the same if either dividend or divisor is of type int Computer Programming I 42
  • 43. Division of Integers  Be careful with the division operator!  int / int produces an integer result (true for variables or numeric constants) int dividend, divisor, quotient; dividend = 5; divisor = 3; quotient = dividend / divisor;  The value of quotient is 1, not 1.666…  Integer division does not round the result, the fractional part is discarded! Computer Programming I 43
  • 45. Integer Remainders  %(mod) operator gives the remainder from integer division int dividend, divisor, remainder; dividend = 5; divisor = 3; remainder = dividend % divisor; The value of remainder is 2 Computer Programming I 45
  • 46. Arithmetic Expressions  Use spacing to make expressions readable  Which is easier to read? x+y*z or x+y*z  Precedence rules for operators are the same as used in your algebra classes  Use parentheses to alter the order of operations x+y*z ( y is multiplied by z first) (x + y) * z ( x and y are added first) Computer Programming I 46
  • 47. Operator Shorthand  Some expressions occur so often that C++ contains to shorthand operators for them  All arithmetic operators can be used this way  += count = count + 2; becomes count += 2;  *= bonus = bonus * 2; becomes bonus *= 2;  /= time = time / rush_factor; becomes time /= rush_factor;  %= remainder = remainder % (cnt1+ cnt2); becomes remainder %= (cnt1 + cnt2); Computer Programming I 47
  • 48. Increment/Decrement  Unary operators require only one operand  + in front of a number such as +5  - in front of a number such as -5  ++ increment operator  Adds 1 to the value of a variable x ++; is equivalent to x = x + 1;  -- decrement operator  Subtracts 1 from the value of a variable x --; is equivalent to x = x – 1; Computer Programming I 48
  • 49. Exercises 1) X += 1 1) X=X+1 2) X *= Y 2) X=X*Y 3) X += X – Y * Z 3) X=X+(X–Y*Z) 4) X++ 4) X =X + 1 5) X *= 2 5) X=X*2 6) X *= Y * Z 6) X=X*Y*Z 7) X %= X / Y 7) X=X % ( X / Y ) 8) X-- 8) X =X - 1 Computer Programming I 49
  • 50. Precedenc Precedence Operators Precedence e Table Postfix ++, -- Highest Prefix ++, -- Parentheses ( ) Unary +,- *, /, % Binary +, - <, <=, >=, > = =, != && || = Lowest Computer Programming I 50
  • 51. Comparison Operators Math Symbol English C++ C++ Sample Notation = equal to == x + 7 = = 2*y ≠ not equal to != Abc != ’n’ < less than < count < m + 3 ≤ less than or equal to <= time <= limit > greater than > time > limit ≥ greater than or equal >= age >= 21 to Computer Programming I 51