SlideShare ist ein Scribd-Unternehmen logo
1 von 22
Downloaden Sie, um offline zu lesen
The C++ Language




                                     Language Overview




    Brief History of C++

    !   Derives from the C programming language by
        Kernighan and Ritchie
    !   Created and developed by Bjarne Stroustrup in
        the 1980s
    !   Standardized in 1998
    !   Added object-oriented features, additional
        safety, new standard library features, and
        many other features to C

2                   Language Basics - Struble




                                                         1
The C++ Compiler


        Preprocessor                                Compiler


    • The preprocessor …
        • Incorporates standard C++ features into your
        computer program.
        • Interprets directives given by the C++ programmer


3                       Language Basics - Struble




    C++ Program Structure

          Source File (.cpp)
           Directives

           main program (or function)




4                       Language Basics - Struble




                                                               2
A C++ Program: Miles to Kilometers
            // This program converts miles to kilometers.
            // From Problem Solving, Abstraction, & Design Using C++
            // by Frank L. Friedman and Elliot B. Koffman
            #include <iostream>
            using namespace std;

            int main() {
                const float KM_PER_MILE = 1.609; // 1.609 km in a mile
                float miles,        // input: distance in miles
                      kms;          // output: distance in kilometers
                // Get the distance in miles
                cout << "Enter the distance in miles: ";
                cin >> miles;
                // Convert the distance to kilometers and display it.
                kms = KM_PER_MILE * miles;
                cout << "The distance in kilometers is " << kms << endl;

                  return 0;
            }
5                             Language Basics - Struble




    C++ Directives (Comments)

    !   Comments
        –       Used by humans to document programs with natural
                language.
        –       Removed by preprocessor before source file is sent
                to the compiler.
    Single line comment.                                  Multiple line comment.
    // A comment                                          /*
                                                          Another comment
                                                          that is bigger.
                                                          */
6                             Language Basics - Struble




                                                                                   3
C++ Directives (#include)

    !   The #include directive is used to incorporate
        standard C++ features into your computer
        program.
    !   Examples
        Directive                 Meaning
        #include <iostream>       Include basic input and output
                                  features.
        #include <fstream>        Include input and output features for
                                  files.
        #include <cmath>          Include standard math functions.
7                   Language Basics - Struble




    C++ Directives (using namespace)

    !   Namespaces are used to identify related
        subprograms and data.
    !   They are accessed by the using namespace
        directive.
    !   In this class, only the std namespace is used
        to access standard C++ features. All of our
        programs contain the line
                   using namespace std;

8                   Language Basics - Struble




                                                                          4
C++ Directives (Example)

     // This program converts miles to …
     // From Problem Solving, Abstraction, …
     // by Frank L. Friedman and Elliot …
     #include <iostream>
     using namespace std;




9                     Language Basics - Struble




     C++ Identifiers

     !   Identifiers are used to name functions
         (subprograms) and data.
     !   Starts with a letter or underscore (_), followed
         by zero or more letters, digits, or underscores
     !   Syntax template
                                        Letter

                               {        _
                                                  {   Letter
                                                      _
                                                      Digit
                                                               …



10                    Language Basics - Struble




                                                                   5
C++ Identifiers

     !   Exercise: Determine whether or not the
         following are identifiers.
          Text          Valid/Invalid Reason Invalid
          miles
          3blindmice
          root_of_2
          hokie bird
          MoveData
          _
11                   Language Basics - Struble




     C++ Identifiers

     !   Identifiers are case sensitive
     !   The following name different functions or data
                      PRINTTOPPORTION
                      Printtopportion
                      pRiNtToPpOrTiOn
                      PrintTopPortion
                                                    Which of
                                                 these is easiest
                                                    to read?
12                   Language Basics - Struble




                                                                    6
C++ Identifiers (Good Programming
     Style)

     !   Always choose meaningful identifier names
         –   Use amount, amt, or totalCost, instead of x,
             xyzzy, or tc.
     !   Be consistent in spelling and capitalization.




13                     Language Basics - Struble




     C++ Identifiers (Keywords)

     !   A keyword or reserved word is an identifier
         reserved for use in the C++ language.
     !   The vocabulary of the C++ language.
     !   Cannot use for your own identifiers.
     !   Some examples (see book for entire list)
          int          while                 char      double
          for          using                 namespace const


14                     Language Basics - Struble




                                                                7
Main Program

     !   Starting point for C++ programs
     !   A collection of sequential statements
     !   Syntax template
                           int main() {
                                Statement
                                …
                           }


15                         Language Basics - Struble




     Main Program (Example)

     int main() {
         const float KM_PER_MILE = 1.609; // 1.609 km in a mile
         float miles,        // input: distance in miles
               kms;          // output: distance in kilometers
         // Get the distance in miles
         cout << "Enter the distance in miles: ";
         cin >> miles;
         // Convert the distance to kilometers and display it.
         kms = KM_PER_MILE * miles;
         cout << "The distance in kilometers is " << kms << endl;


         return 0;
     }
16                         Language Basics - Struble




                                                                    8
Data Types

     !   C++ is a typed language
         –   Data is categorized
     !   Everything is made up of data in four basic or
         simple categories
         –   Integers
         –   Floating point values (real numbers)
         –   Character
         –   Boolean

17                      Language Basics - Struble




     Simple Data Types (Integers)

     !   Positive or negative whole numbers
     !   Three kinds (determines range of values)
         –   short usually –32768 to 32767
         –   int usually –2147483648 to 2147483647
         –   long often the same as int or more
     !   Examples
         0           1000              -2179        +809754


18                      Language Basics - Struble




                                                              9
Simple Data Types (Floating Point)

     !   Positive or negative decimal values
         –   Some decimals values cannot be stored exactly
     !   Three kinds (determines range and precision of values)
         –   float approx 1.2e-38 to 3.4e+38, 6 digits
         –   double approx 2.2e-308 to 1.8e+308, 15 digits
         –   long double approx 3.4e-4932 to 1.2e+4932, 18 digits
     !   Examples
         98.6         3.1419             -3.4561E-12 3.           .4




19                        Language Basics - Struble




     Simple Data Types (Character)

     !   Stores a single character value
         –   Alphabetic characters, digits, etc.
         –   Surround character by single quotes
     !   Only one kind stores 256 different values
         –   char
     !   Examples
         'A'          '0'      '%'       '?'          '/'   '}'
     !   Note: 0 is not the same as '0'

20                        Language Basics - Struble




                                                                       10
Simple Data Types (Boolean)

     !   Stores logical values
         –   true
         –   false
     !   Only one kind, stores one of two values above
         –   bool




21                      Language Basics - Struble




     Other Data Types

     !   C++ provides several other data types
         –   Streams (input and output)
         –   Strings (sequences of characters)
         –   User-defined types
     !   Built up from simple types
     !   Used like other simple types



22                      Language Basics - Struble




                                                         11
Other Data Types (Strings)

     !   Stores sequences of characters
     !   One kind
          –   string
     !   Surrounded by double quotes (")
     !   Must include string support
          #include <string>
     !   Examples
          "Hello World"    "Craig Struble"
          "CS1044"         "2001"


23                     Language Basics - Struble




     Variables

     !   A variable is a location in memory, identified
         by a name, that contains information that can
         change.

                   Name            Address         Memory
                   change          1004                 7
                   dollars         1008                 2
                   quarters        1012                 3
                   dimes           1016                 1

24                     Language Basics - Struble




                                                            12
Variable Declarations

     !   A variable declaration instructs the compiler to
         set aside space for a variable.
         –   States the type of data stored in memory
         –   States the name used to refer to data
         –   Must appear before variable name can be used
     !   Syntax template

                     DataType Identifier , Identifier … ;


25                      Language Basics - Struble




     Variable Declarations (Examples)
     int change;      // change in cents

     // coin types
     int dollars, quarters, dimes, nickels, pennies;

     float miles, // distance in miles
           kms;   // distance in kilometers

     string firstName; // Student's first name



26                      Language Basics - Struble




                                                            13
Literal Constants

     !   Literal constants are data typed directly into a
         program
         123         "Craig Struble"                 0.567
         'A'         true




27                       Language Basics - Struble




     Named Constants

     !   A named constant is a memory location
         containing data that does not change.
         –   Typed information like variables
         –   Must also be declared before referencing
     !   Syntax template
               const DataType Identifier = LiteralConstant ;



28                       Language Basics - Struble




                                                               14
Named Constants (Examples)
     // Instructor's name
     const string INSTRUCTOR = "Dr. Craig Struble";

     const char BLANK = ' ';                     // a single space

     // value of a dollar in cents
     const int ONE_DOLLAR = 100;

     // An approximation of PI
     const double PI = 3.1415926;


29                          Language Basics - Struble




     Variables and Named Constants
     (Good Programming Style)
     !   Variable and constant names should be meaningful
     !   Always use named constants instead of literal values
         –   Easier to maintain
         –   Easier to read
         –   Constant identifiers should be all capital letters
     !   Requirement: A comment describing the use of the
         variable and constant must be included.
     !   Requirement: Named constants must be used at all
         times, except for the value 0, and for strings that are
         used to print out information.

30                          Language Basics - Struble




                                                                     15
Exercise

     !   Declare an appropriate variable or named
         constant for each of the following
         –   The number of days in a week
         –   The grade on a test
         –   Using IntegerList.data as the only name of an
             input file
         –   The name of a book
         –   The cost of a toy in dollars and cents
         –   Using the vertical bar | as a delimiter for input data

31                       Language Basics - Struble




     Executable Statements

     !   Variable and named constant declarations do
         not change the state of the computer
         –   Only set up memory in the computer
     !   Executable statements change the computer
         state
         –   Assignment statements
         –   Input and Output statements



32                       Language Basics - Struble




                                                                      16
Assignment Statements

     !   Stores values into a variable
         –   Changes the state of a variable
     !   An expression defines the value to store
         –   Expression is combination of identifiers, literal
             constants, and operators that is evaluated
     !   Syntax template
                         Variable = Expression ;


33                       Language Basics - Struble




     Expressions

     !   The most basic expression is a literal constant
         Grade = 98;
         President = "George Bush";
     !   Another simple expression is an identifier for a
         variable or named constant.
         BestGrade = Grade;
         Price = ONE_DOLLAR;                              Grade and
                                                     BestGrade contain
         Grade = 75;                                 different values now.


34                       Language Basics - Struble




                                                                             17
Simple Mathematical Expressions

     !   C++ understands basic mathematical
         operators
         Grade = 88 + 10; // 98 is stored in Grade
         Payment = 1.58;
         Cost = 0.97;
         Change = Payment - Cost; // 0.61 is stored
         kms = KM_PER_MILE * miles;
         mpg = miles / gallons;




35                       Language Basics - Struble




     Updating Variables

     !   The same variable name can be used on the
         left hand side of the equals sign and in the
         expression on the right.
         –   This is used to update the value in the variable.
     !   Examples
         // add one to the number of dollars and
         // update remaining change.
         dollars = dollars + 1;
         change = change - ONE_DOLLAR;



36                       Language Basics - Struble




                                                                 18
Integer Expressions

     !   Division works differently for expressions with
         only integers
         –   Remainders are truncated (removed)
         –   Only the integral quotient is stored
     !   Examples (all variables are int typed)
         ratio = 3 / 4; // 0 is stored
         ratio2 = 5 / 2; // 2 is stored



37                      Language Basics - Struble




     Integer Expressions

     !   C++ uses the percent sign % to calculate
         remainders.
     !   Examples
         // Use division to calculate dollars
         // and remaining change.
         dollars = dollars / ONE_DOLLAR;
         change = change % ONE_DOLLAR;




38                      Language Basics - Struble




                                                           19
Mixing Floating Point and Integers

     !   Simple expressions that mix floating point
         values and integers convert the integer to a
         floating point value before evaluating.
     !   Examples (variables are double)
         ratio = 5 / 2.0; // 5 becomes 5.0, 2.5 is stored
         Percent = 0.50 * 100; // 50.0 is stored
         Total = 50 + 7.5;     // 57.5 is stored




39                   Language Basics - Struble




     Assignment Statements (Types)

     !   The type of the expression should conform to
         ____________________.

                  // This is an error!
                  int id;
                  id = "012-345-6789";




40                   Language Basics - Struble




                                                            20
Assignment Statements (Types)

     !   Mixing floating point and integers is allowed,
         but
         –   Storing floating point value in an integer variable
             truncates the value
         –   Storing integer values in floating point variables
             widen the value
         –   Expression is evaluated by its type rules before
             truncating or widening.


41                       Language Basics - Struble




     Assignment Statements (Type
     Examples)
     int Grade;
     Grade = 91.9;              // 91 is stored

     float price;
     price = 2;                 // 2.0 is stored
                                                     Why?
     double ratio;
     ratio = 5 / 2;             // 2.0 is stored


42                       Language Basics - Struble




                                                                   21
Assignment Statement (Exercises)

     !   What value is each expression?
     !   What value is stored in each variable?
     // Note that the declarations precede references
     // value of dollar in dollars
     const float ONE_DOLLAR = 1.00;

     float change;    // change in dollars
     int dollars;     // number of dollars

     change = 2.59;
     dollars = change / ONE_DOLLAR;
     change = change - dollars;

43                   Language Basics - Struble




                                                        22

Weitere ähnliche Inhalte

Was ist angesagt? (19)

CProgrammingTutorial
CProgrammingTutorialCProgrammingTutorial
CProgrammingTutorial
 
Learning the C Language
Learning the C LanguageLearning the C Language
Learning the C Language
 
Learning c - An extensive guide to learn the C Language
Learning c - An extensive guide to learn the C LanguageLearning c - An extensive guide to learn the C Language
Learning c - An extensive guide to learn the C Language
 
Introduction to C Unit 1
Introduction to C Unit 1Introduction to C Unit 1
Introduction to C Unit 1
 
C tutorial
C tutorialC tutorial
C tutorial
 
Top C Language Interview Questions and Answer
Top C Language Interview Questions and AnswerTop C Language Interview Questions and Answer
Top C Language Interview Questions and Answer
 
Chapter 2
Chapter 2Chapter 2
Chapter 2
 
The smartpath information systems c pro
The smartpath information systems c proThe smartpath information systems c pro
The smartpath information systems c pro
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
 
Structures
StructuresStructures
Structures
 
Introduction to c programming
Introduction to c programmingIntroduction to c programming
Introduction to c programming
 
Structures-2
Structures-2Structures-2
Structures-2
 
Features of c language 1
Features of c language 1Features of c language 1
Features of c language 1
 
Features of c
Features of cFeatures of c
Features of c
 
Javascript by Yahoo
Javascript by YahooJavascript by Yahoo
Javascript by Yahoo
 
Introduction to C Programming
Introduction to C ProgrammingIntroduction to C Programming
Introduction to C Programming
 
cmp104 lec 8
cmp104 lec 8cmp104 lec 8
cmp104 lec 8
 
C by balaguruswami - e.balagurusamy
C   by balaguruswami - e.balagurusamyC   by balaguruswami - e.balagurusamy
C by balaguruswami - e.balagurusamy
 
Unit1 cd
Unit1 cdUnit1 cd
Unit1 cd
 

Andere mochten auch

Tech Ed 2011 Preso
Tech Ed 2011 PresoTech Ed 2011 Preso
Tech Ed 2011 PresoPAUL CONROY
 
Fusion Bpo Services- Corporate profile
Fusion Bpo  Services- Corporate profileFusion Bpo  Services- Corporate profile
Fusion Bpo Services- Corporate profileSurmit De
 
Thompson msue talk 8 15-2013
Thompson msue talk 8 15-2013Thompson msue talk 8 15-2013
Thompson msue talk 8 15-2013Jessica Thompson
 
Management of male impotency
Management of male impotency   Management of male impotency
Management of male impotency Krishna Lodha
 
Citizens for the_new_zoo revised
Citizens for the_new_zoo revisedCitizens for the_new_zoo revised
Citizens for the_new_zoo revisedahawari
 
Ecommerce Monetiser Son Site Philippefloch Technofutur
Ecommerce Monetiser Son Site Philippefloch TechnofuturEcommerce Monetiser Son Site Philippefloch Technofutur
Ecommerce Monetiser Son Site Philippefloch TechnofuturTechnofutur TIC
 
Intelligence collective et réseaux sociaux : comment le web 2.0 modifie la tr...
Intelligence collective et réseaux sociaux : comment le web 2.0 modifie la tr...Intelligence collective et réseaux sociaux : comment le web 2.0 modifie la tr...
Intelligence collective et réseaux sociaux : comment le web 2.0 modifie la tr...Fred Colantonio
 
Лекция № 5. Важнейшие элементы периодической системы Д.И. Менделеева, определ...
Лекция № 5. Важнейшие элементы периодической системы Д.И. Менделеева, определ...Лекция № 5. Важнейшие элементы периодической системы Д.И. Менделеева, определ...
Лекция № 5. Важнейшие элементы периодической системы Д.И. Менделеева, определ...Петрова Елена Александровна
 
Approche paysagiste
Approche paysagisteApproche paysagiste
Approche paysagisteHania Zazoua
 
Commission electorale
Commission electoraleCommission electorale
Commission electoraleJuanico
 
Baromètre EurObserv’ER 2014 - Etat des énergies renouvelables en Europe
Baromètre EurObserv’ER 2014 - Etat des énergies renouvelables en EuropeBaromètre EurObserv’ER 2014 - Etat des énergies renouvelables en Europe
Baromètre EurObserv’ER 2014 - Etat des énergies renouvelables en EuropePôle Réseaux de Chaleur - Cerema
 

Andere mochten auch (20)

Tech Ed 2011 Preso
Tech Ed 2011 PresoTech Ed 2011 Preso
Tech Ed 2011 Preso
 
Fusion Bpo Services- Corporate profile
Fusion Bpo  Services- Corporate profileFusion Bpo  Services- Corporate profile
Fusion Bpo Services- Corporate profile
 
Thompson msue talk 8 15-2013
Thompson msue talk 8 15-2013Thompson msue talk 8 15-2013
Thompson msue talk 8 15-2013
 
Management of male impotency
Management of male impotency   Management of male impotency
Management of male impotency
 
Budget 2014
Budget 2014Budget 2014
Budget 2014
 
 
Citizens for the_new_zoo revised
Citizens for the_new_zoo revisedCitizens for the_new_zoo revised
Citizens for the_new_zoo revised
 
Life
LifeLife
Life
 
Inco Terms
Inco TermsInco Terms
Inco Terms
 
Java I/O Part 1
Java I/O Part 1Java I/O Part 1
Java I/O Part 1
 
Java I/O Part 2
Java I/O Part 2Java I/O Part 2
Java I/O Part 2
 
JSP : Creating Custom Tag
JSP : Creating Custom Tag JSP : Creating Custom Tag
JSP : Creating Custom Tag
 
Dom Basics
Dom BasicsDom Basics
Dom Basics
 
Network analysis
Network analysisNetwork analysis
Network analysis
 
Ecommerce Monetiser Son Site Philippefloch Technofutur
Ecommerce Monetiser Son Site Philippefloch TechnofuturEcommerce Monetiser Son Site Philippefloch Technofutur
Ecommerce Monetiser Son Site Philippefloch Technofutur
 
Intelligence collective et réseaux sociaux : comment le web 2.0 modifie la tr...
Intelligence collective et réseaux sociaux : comment le web 2.0 modifie la tr...Intelligence collective et réseaux sociaux : comment le web 2.0 modifie la tr...
Intelligence collective et réseaux sociaux : comment le web 2.0 modifie la tr...
 
Лекция № 5. Важнейшие элементы периодической системы Д.И. Менделеева, определ...
Лекция № 5. Важнейшие элементы периодической системы Д.И. Менделеева, определ...Лекция № 5. Важнейшие элементы периодической системы Д.И. Менделеева, определ...
Лекция № 5. Важнейшие элементы периодической системы Д.И. Менделеева, определ...
 
Approche paysagiste
Approche paysagisteApproche paysagiste
Approche paysagiste
 
Commission electorale
Commission electoraleCommission electorale
Commission electorale
 
Baromètre EurObserv’ER 2014 - Etat des énergies renouvelables en Europe
Baromètre EurObserv’ER 2014 - Etat des énergies renouvelables en EuropeBaromètre EurObserv’ER 2014 - Etat des énergies renouvelables en Europe
Baromètre EurObserv’ER 2014 - Etat des énergies renouvelables en Europe
 

Ähnlich wie 4.languagebasics

Report on c and c++
Report on c and c++Report on c and c++
Report on c and c++oggyrao
 
C Programming- Harsh Sharma
C Programming- Harsh SharmaC Programming- Harsh Sharma
C Programming- Harsh SharmaHarsh Sharma
 
C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...
C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...
C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...ANUSUYA S
 
introduction to c programming language
introduction to c programming languageintroduction to c programming language
introduction to c programming languagesanjay joshi
 
490450755-Chapter-2.ppt
490450755-Chapter-2.ppt490450755-Chapter-2.ppt
490450755-Chapter-2.pptManiMala75
 
490450755-Chapter-2.ppt
490450755-Chapter-2.ppt490450755-Chapter-2.ppt
490450755-Chapter-2.pptManiMala75
 
Msc prev updated
Msc prev updatedMsc prev updated
Msc prev updatedmshoaib15
 
Msc prev completed
Msc prev completedMsc prev completed
Msc prev completedmshoaib15
 
C LANGUAGE UNIT-1 PREPARED BY MVB REDDY
C LANGUAGE UNIT-1 PREPARED BY MVB REDDYC LANGUAGE UNIT-1 PREPARED BY MVB REDDY
C LANGUAGE UNIT-1 PREPARED BY MVB REDDYRajeshkumar Reddy
 
Introduction to c programming language
Introduction to c programming languageIntroduction to c programming language
Introduction to c programming languagesanjay joshi
 
Chapter-2 edited on Programming in Can refer this ppt
Chapter-2 edited on Programming in Can refer this pptChapter-2 edited on Programming in Can refer this ppt
Chapter-2 edited on Programming in Can refer this pptANISHYAPIT
 
C++ programming language basic to advance level
C++ programming language basic to advance levelC++ programming language basic to advance level
C++ programming language basic to advance levelsajjad ali khan
 

Ähnlich wie 4.languagebasics (20)

Report on c and c++
Report on c and c++Report on c and c++
Report on c and c++
 
Presentation c++
Presentation c++Presentation c++
Presentation c++
 
Presentation 2.ppt
Presentation 2.pptPresentation 2.ppt
Presentation 2.ppt
 
Introduction Of C++
Introduction Of C++Introduction Of C++
Introduction Of C++
 
Prog1-L1.pdf
Prog1-L1.pdfProg1-L1.pdf
Prog1-L1.pdf
 
C Programming- Harsh Sharma
C Programming- Harsh SharmaC Programming- Harsh Sharma
C Programming- Harsh Sharma
 
C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...
C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...
C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...
 
C language
C languageC language
C language
 
introduction to c programming language
introduction to c programming languageintroduction to c programming language
introduction to c programming language
 
490450755-Chapter-2.ppt
490450755-Chapter-2.ppt490450755-Chapter-2.ppt
490450755-Chapter-2.ppt
 
490450755-Chapter-2.ppt
490450755-Chapter-2.ppt490450755-Chapter-2.ppt
490450755-Chapter-2.ppt
 
Msc prev updated
Msc prev updatedMsc prev updated
Msc prev updated
 
Basic c
Basic cBasic c
Basic c
 
Msc prev completed
Msc prev completedMsc prev completed
Msc prev completed
 
Chap 2 c++
Chap 2 c++Chap 2 c++
Chap 2 c++
 
C LANGUAGE UNIT-1 PREPARED BY MVB REDDY
C LANGUAGE UNIT-1 PREPARED BY MVB REDDYC LANGUAGE UNIT-1 PREPARED BY MVB REDDY
C LANGUAGE UNIT-1 PREPARED BY MVB REDDY
 
Introduction to c programming language
Introduction to c programming languageIntroduction to c programming language
Introduction to c programming language
 
Chapter-2 edited on Programming in Can refer this ppt
Chapter-2 edited on Programming in Can refer this pptChapter-2 edited on Programming in Can refer this ppt
Chapter-2 edited on Programming in Can refer this ppt
 
C++ programming language basic to advance level
C++ programming language basic to advance levelC++ programming language basic to advance level
C++ programming language basic to advance level
 
C notes
C notesC notes
C notes
 

Kürzlich hochgeladen

TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 

Kürzlich hochgeladen (20)

TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 

4.languagebasics

  • 1. The C++ Language Language Overview Brief History of C++ ! Derives from the C programming language by Kernighan and Ritchie ! Created and developed by Bjarne Stroustrup in the 1980s ! Standardized in 1998 ! Added object-oriented features, additional safety, new standard library features, and many other features to C 2 Language Basics - Struble 1
  • 2. The C++ Compiler Preprocessor Compiler • The preprocessor … • Incorporates standard C++ features into your computer program. • Interprets directives given by the C++ programmer 3 Language Basics - Struble C++ Program Structure Source File (.cpp) Directives main program (or function) 4 Language Basics - Struble 2
  • 3. A C++ Program: Miles to Kilometers // This program converts miles to kilometers. // From Problem Solving, Abstraction, & Design Using C++ // by Frank L. Friedman and Elliot B. Koffman #include <iostream> using namespace std; int main() { const float KM_PER_MILE = 1.609; // 1.609 km in a mile float miles, // input: distance in miles kms; // output: distance in kilometers // Get the distance in miles cout << "Enter the distance in miles: "; cin >> miles; // Convert the distance to kilometers and display it. kms = KM_PER_MILE * miles; cout << "The distance in kilometers is " << kms << endl; return 0; } 5 Language Basics - Struble C++ Directives (Comments) ! Comments – Used by humans to document programs with natural language. – Removed by preprocessor before source file is sent to the compiler. Single line comment. Multiple line comment. // A comment /* Another comment that is bigger. */ 6 Language Basics - Struble 3
  • 4. C++ Directives (#include) ! The #include directive is used to incorporate standard C++ features into your computer program. ! Examples Directive Meaning #include <iostream> Include basic input and output features. #include <fstream> Include input and output features for files. #include <cmath> Include standard math functions. 7 Language Basics - Struble C++ Directives (using namespace) ! Namespaces are used to identify related subprograms and data. ! They are accessed by the using namespace directive. ! In this class, only the std namespace is used to access standard C++ features. All of our programs contain the line using namespace std; 8 Language Basics - Struble 4
  • 5. C++ Directives (Example) // This program converts miles to … // From Problem Solving, Abstraction, … // by Frank L. Friedman and Elliot … #include <iostream> using namespace std; 9 Language Basics - Struble C++ Identifiers ! Identifiers are used to name functions (subprograms) and data. ! Starts with a letter or underscore (_), followed by zero or more letters, digits, or underscores ! Syntax template Letter { _ { Letter _ Digit … 10 Language Basics - Struble 5
  • 6. C++ Identifiers ! Exercise: Determine whether or not the following are identifiers. Text Valid/Invalid Reason Invalid miles 3blindmice root_of_2 hokie bird MoveData _ 11 Language Basics - Struble C++ Identifiers ! Identifiers are case sensitive ! The following name different functions or data PRINTTOPPORTION Printtopportion pRiNtToPpOrTiOn PrintTopPortion Which of these is easiest to read? 12 Language Basics - Struble 6
  • 7. C++ Identifiers (Good Programming Style) ! Always choose meaningful identifier names – Use amount, amt, or totalCost, instead of x, xyzzy, or tc. ! Be consistent in spelling and capitalization. 13 Language Basics - Struble C++ Identifiers (Keywords) ! A keyword or reserved word is an identifier reserved for use in the C++ language. ! The vocabulary of the C++ language. ! Cannot use for your own identifiers. ! Some examples (see book for entire list) int while char double for using namespace const 14 Language Basics - Struble 7
  • 8. Main Program ! Starting point for C++ programs ! A collection of sequential statements ! Syntax template int main() { Statement … } 15 Language Basics - Struble Main Program (Example) int main() { const float KM_PER_MILE = 1.609; // 1.609 km in a mile float miles, // input: distance in miles kms; // output: distance in kilometers // Get the distance in miles cout << "Enter the distance in miles: "; cin >> miles; // Convert the distance to kilometers and display it. kms = KM_PER_MILE * miles; cout << "The distance in kilometers is " << kms << endl; return 0; } 16 Language Basics - Struble 8
  • 9. Data Types ! C++ is a typed language – Data is categorized ! Everything is made up of data in four basic or simple categories – Integers – Floating point values (real numbers) – Character – Boolean 17 Language Basics - Struble Simple Data Types (Integers) ! Positive or negative whole numbers ! Three kinds (determines range of values) – short usually –32768 to 32767 – int usually –2147483648 to 2147483647 – long often the same as int or more ! Examples 0 1000 -2179 +809754 18 Language Basics - Struble 9
  • 10. Simple Data Types (Floating Point) ! Positive or negative decimal values – Some decimals values cannot be stored exactly ! Three kinds (determines range and precision of values) – float approx 1.2e-38 to 3.4e+38, 6 digits – double approx 2.2e-308 to 1.8e+308, 15 digits – long double approx 3.4e-4932 to 1.2e+4932, 18 digits ! Examples 98.6 3.1419 -3.4561E-12 3. .4 19 Language Basics - Struble Simple Data Types (Character) ! Stores a single character value – Alphabetic characters, digits, etc. – Surround character by single quotes ! Only one kind stores 256 different values – char ! Examples 'A' '0' '%' '?' '/' '}' ! Note: 0 is not the same as '0' 20 Language Basics - Struble 10
  • 11. Simple Data Types (Boolean) ! Stores logical values – true – false ! Only one kind, stores one of two values above – bool 21 Language Basics - Struble Other Data Types ! C++ provides several other data types – Streams (input and output) – Strings (sequences of characters) – User-defined types ! Built up from simple types ! Used like other simple types 22 Language Basics - Struble 11
  • 12. Other Data Types (Strings) ! Stores sequences of characters ! One kind – string ! Surrounded by double quotes (") ! Must include string support #include <string> ! Examples "Hello World" "Craig Struble" "CS1044" "2001" 23 Language Basics - Struble Variables ! A variable is a location in memory, identified by a name, that contains information that can change. Name Address Memory change 1004 7 dollars 1008 2 quarters 1012 3 dimes 1016 1 24 Language Basics - Struble 12
  • 13. Variable Declarations ! A variable declaration instructs the compiler to set aside space for a variable. – States the type of data stored in memory – States the name used to refer to data – Must appear before variable name can be used ! Syntax template DataType Identifier , Identifier … ; 25 Language Basics - Struble Variable Declarations (Examples) int change; // change in cents // coin types int dollars, quarters, dimes, nickels, pennies; float miles, // distance in miles kms; // distance in kilometers string firstName; // Student's first name 26 Language Basics - Struble 13
  • 14. Literal Constants ! Literal constants are data typed directly into a program 123 "Craig Struble" 0.567 'A' true 27 Language Basics - Struble Named Constants ! A named constant is a memory location containing data that does not change. – Typed information like variables – Must also be declared before referencing ! Syntax template const DataType Identifier = LiteralConstant ; 28 Language Basics - Struble 14
  • 15. Named Constants (Examples) // Instructor's name const string INSTRUCTOR = "Dr. Craig Struble"; const char BLANK = ' '; // a single space // value of a dollar in cents const int ONE_DOLLAR = 100; // An approximation of PI const double PI = 3.1415926; 29 Language Basics - Struble Variables and Named Constants (Good Programming Style) ! Variable and constant names should be meaningful ! Always use named constants instead of literal values – Easier to maintain – Easier to read – Constant identifiers should be all capital letters ! Requirement: A comment describing the use of the variable and constant must be included. ! Requirement: Named constants must be used at all times, except for the value 0, and for strings that are used to print out information. 30 Language Basics - Struble 15
  • 16. Exercise ! Declare an appropriate variable or named constant for each of the following – The number of days in a week – The grade on a test – Using IntegerList.data as the only name of an input file – The name of a book – The cost of a toy in dollars and cents – Using the vertical bar | as a delimiter for input data 31 Language Basics - Struble Executable Statements ! Variable and named constant declarations do not change the state of the computer – Only set up memory in the computer ! Executable statements change the computer state – Assignment statements – Input and Output statements 32 Language Basics - Struble 16
  • 17. Assignment Statements ! Stores values into a variable – Changes the state of a variable ! An expression defines the value to store – Expression is combination of identifiers, literal constants, and operators that is evaluated ! Syntax template Variable = Expression ; 33 Language Basics - Struble Expressions ! The most basic expression is a literal constant Grade = 98; President = "George Bush"; ! Another simple expression is an identifier for a variable or named constant. BestGrade = Grade; Price = ONE_DOLLAR; Grade and BestGrade contain Grade = 75; different values now. 34 Language Basics - Struble 17
  • 18. Simple Mathematical Expressions ! C++ understands basic mathematical operators Grade = 88 + 10; // 98 is stored in Grade Payment = 1.58; Cost = 0.97; Change = Payment - Cost; // 0.61 is stored kms = KM_PER_MILE * miles; mpg = miles / gallons; 35 Language Basics - Struble Updating Variables ! The same variable name can be used on the left hand side of the equals sign and in the expression on the right. – This is used to update the value in the variable. ! Examples // add one to the number of dollars and // update remaining change. dollars = dollars + 1; change = change - ONE_DOLLAR; 36 Language Basics - Struble 18
  • 19. Integer Expressions ! Division works differently for expressions with only integers – Remainders are truncated (removed) – Only the integral quotient is stored ! Examples (all variables are int typed) ratio = 3 / 4; // 0 is stored ratio2 = 5 / 2; // 2 is stored 37 Language Basics - Struble Integer Expressions ! C++ uses the percent sign % to calculate remainders. ! Examples // Use division to calculate dollars // and remaining change. dollars = dollars / ONE_DOLLAR; change = change % ONE_DOLLAR; 38 Language Basics - Struble 19
  • 20. Mixing Floating Point and Integers ! Simple expressions that mix floating point values and integers convert the integer to a floating point value before evaluating. ! Examples (variables are double) ratio = 5 / 2.0; // 5 becomes 5.0, 2.5 is stored Percent = 0.50 * 100; // 50.0 is stored Total = 50 + 7.5; // 57.5 is stored 39 Language Basics - Struble Assignment Statements (Types) ! The type of the expression should conform to ____________________. // This is an error! int id; id = "012-345-6789"; 40 Language Basics - Struble 20
  • 21. Assignment Statements (Types) ! Mixing floating point and integers is allowed, but – Storing floating point value in an integer variable truncates the value – Storing integer values in floating point variables widen the value – Expression is evaluated by its type rules before truncating or widening. 41 Language Basics - Struble Assignment Statements (Type Examples) int Grade; Grade = 91.9; // 91 is stored float price; price = 2; // 2.0 is stored Why? double ratio; ratio = 5 / 2; // 2.0 is stored 42 Language Basics - Struble 21
  • 22. Assignment Statement (Exercises) ! What value is each expression? ! What value is stored in each variable? // Note that the declarations precede references // value of dollar in dollars const float ONE_DOLLAR = 1.00; float change; // change in dollars int dollars; // number of dollars change = 2.59; dollars = change / ONE_DOLLAR; change = change - dollars; 43 Language Basics - Struble 22