C++ Language Fundamentals. 2 Contents 1. Introduction to C++ 2. Basic syntax rules 3. Declaring and using variables.

Slides:



Advertisements
Similar presentations
Introduction to C++ An object-oriented language Unit - 01.
Advertisements

C++ Introduction.
Chapter 8 Technicalities: Functions, etc. Bjarne Stroustrup
CPSC 441 TUTORIAL – JANUARY 16, 2012 TA: MARYAM ELAHI INTRODUCTION TO C.
Introduction to C++ Programming. Brief Facts About C++ Evolved from C Designed and implemented by Bjarne Stroustrup at the Bell Labs in the early 1980s.
Introduction to Programming in C++ John Galletly.
Your First C++ Program Aug 27, /27/08 CS 150 Introduction to Computer Science I C++  Based on the C programming language  One of today’s most.
Rossella Lau Lecture 1, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 1: Introduction What this course is about:
CS31: Introduction to Computer Science I Discussion 1A 4/2/2010 Sungwon Yang
1 8/30/06CS150 Introduction to Computer Science 1 Your First C++ Program.
General Computer Science for Engineers CISC 106 Lecture 26 Dr. John Cavazos Computer and Information Sciences 04/24/2009.
C++ fundamentals.
COMPUTER PROGRAMMING. Introduction to C++ History Merges notions from Smalltalk and notions from C The class concept was borrowed from Simular67 Developed.
JAVA v.s. C++ Programming Language Comparison By LI LU SAMMY CHU By LI LU SAMMY CHU.
Introduction to C++ - How C++ Evolved Most popular languages currently: COBOL, Fortran, C, C++, Java (script) C was developed in 1970s at AT&T (Richie)
Intro. to Game Programming Want to program a game?
Java and C++, The Difference An introduction Unit - 00.
C++ Programming. Table of Contents History What is C++? Development of C++ Standardized C++ What are the features of C++? What is Object Orientation?
11 Getting Started with C# Chapter Objectives You will be able to: 1. Say in general terms how C# differs from C. 2. Create, compile, and run a.
1Object-Oriented Program Development Using C++ Computer Science and Programming Languages Computers are ubiquitous Computer literacy is essential Computer.
C++
By – Tanvir Alam.  This tutorial offers several things.  You’ll see some neat features of the language.  You’ll learn the right things to google. 
By Noorez Kassam Welcome to JNI. Why use JNI ? 1. You already have significantly large and tricky code written in another language and you would rather.
Chapter 1 Introduction to Computers and C++ Programming Goals: To introduce the fundamental hardware and software components of a computer system To introduce.
Comp 245 Data Structures Linked Lists. An Array Based List Usually is statically allocated; may not use memory efficiently Direct access to data; faster.
1 Programs Composed of Several Functions Syntax Templates Legal C++ Identifiers Assigning Values to Variables Declaring Named Constants String Concatenation.
Game Programming in Java Dr. Jeyakesavan Veerasamy CS faculty, The University of Texas at Dallas Website:
Rossella Lau Lecture 1, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 1: Introduction What this course is about:
Applied Computing Technology Laboratory QuickStart C# Learning to Program in C# Amy Roberge & John Linehan November 7, 2005.
Course Title: Introduction to C++ Course Instructor: ADEEL ANJUM Chapter No: 01 1 BY ADEEL ANJUM (MCS, CCNA,WEB DEVELOPER)
COMPUTER PROGRAMMING. A Typical C++ Environment Phases of C++ Programs: 1- Edit 2- Preprocess 3- Compile 4- Link 5- Load 6- Execute Loader Primary Memory.
C++ History C++ was designed at AT&T Bell Labs by Bjarne Stroustrup in the early 80's Based on the ‘C’ programming language C++ language standardised in.
C++ Coding and Compiling. Why QT/C++ Over Java?  Java is easier than C++  Java has built in GUIs  Java is multi-platform  C/C++ is more used in industry.
N from what language did C++ originate? n what’s input, output device? n what’s main memory, memory location, memory address? n what’s a program, data?
Software Design 8.1 A Rose by any other name…C or Java? l Why do we use Java in our courses (royal we?)  Object oriented  Large collection of libraries.
C ++ Basics by Bindra Shrestha sce.uhcl.edu/shresthab CSCI 3333 Data Structures.
1 C++ Programming Basics Chapter 1 Lecture CSIS 10A.
C++ Programming Basic Learning Prepared By The Smartpath Information systems
Monday, Jan 6, 2003Kate Gregory with material from Deitel and Deitel CO 204 Object Oriented Programming 2003 Trent University Kate Gregory.
C++ Programming Part 2 Michael Griffiths Corporate Information and Computing Services The University of Sheffield
1 COMS 261 Computer Science I Title: C++ Fundamentals Date: September 05, 2005 Lecture Number: 4.
CS 11 C++ track: lecture 1 Administrivia Need a CS cluster account sysadmin/account_request.cgi Need to know UNIX (Linux)
More About Data Types & Functions. General Program Structure #include statements for I/O, etc. #include's for class headers – function prototype statements.
CSE 1341 Honors Note Set 2 1. Overview  Java vs. C++  Functions in C++  First Programming Packet  Development Environment 2.
Introducing C++ to Java Programmers by Kip Irvine updated 2/27/2003.
Learners Support Publications Introduction to C++
Introduction to C++.  Computers: CPU, Memory & Input / Output (IO)  Program: Sequence of instructions for the computer.  Operating system: Program.
CSE 332: C++ template examples Today: Using Class and Function Templates Two examples –Function template for printing different types –Class template for.
Java & C++ Comparisons How important are classes and objects?? What mechanisms exist for input and output?? Are references and pointers the same thing??
1 8/30/06CS150 Introduction to Computer Science 1 Your First C++ Program.
CSCE Introduction to Program Design and Concepts J. Michael Moore Spring 2015 Set 6: Miscellaneous 1 Based on slides created by Bjarne Stroustrup.
Software Engineering Algorithms, Compilers, & Lifecycle.
C++ Programming Michael Griffiths Corporate Information and Computing Services The University of Sheffield
Bill Tucker Austin Community College COSC 1315
Object Oriented Programming in
Introduction to Computers and C++ Programming
Eugene Hsu.
CISC/CMPE320 - Prof. McLeod
CSCI 161: Introduction to Programming
C++ History C++ was designed at AT&T Bell Labs by Bjarne Stroustrup in the early 80's Based on the ‘C’ programming language C++ language standardised in.
Computer science By/ Midhat Mohiey. Introduction to Programming using C ++ 2.
جامعة البحر الاحمر كلية العلوم التطبيقية قسم الفيزياء التطبيقية الفصل الداسي الثاني IIالمقرر: حاسوب د. خالد عثمان العالم.
Brought to you by C++ Tutorial Brought to you by
More About Data Types & Functions
جامعة البحر الاحمر كلية العلوم التطبيقية قسمي الحاسوب وتقنية المعلومات الفصل الداسي الثاني المقرر: اساليب برمجة 1 محاضرة رقم 1 د. خالد عثمان العالم.
Principles of object – oriented programming UNIT-1 Chapter-1.
CSE 303 Concepts and Tools for Software Development
Lecture 2 Fall 2011 September 13-15, 2011 Ghufran Ahmed
Computer Terms Review from what language did C++ originate?
SPL – PS1 Introduction to C++.
Presentation transcript:

C++ Language Fundamentals

2 Contents 1. Introduction to C++ 2. Basic syntax rules 3. Declaring and using variables

3 1. Introduction to C++ Setting the scene Differences between C++ and Java The Standard C++ library Hello world! Compiling and linking a C++ program Getting input Making decisions

4 Setting the Scene C++ is an object-oriented evolution of C C dates back to 1972 C++ was introduced in 1985, by Bjarne Stroustrup C++ is now an ANSI standard Characteristics of C++ Object-oriented, i.e. supports classes, inheritance, polymorphism Strongly typed at compile-time Supports generic programming via templates, e.g. list Uses of C++ are extremely widespread E.g. middle-tier business rules in a distributed application E.g. low-level process control

5 Differences between C++ and Java C++ is compiled directly to machine code No concept of "byte codes" (like you have in Java) So you must re-compile for each target platform C++ applications run directly on the O/S No virtual machine between C++ and the O/S No garbage collection - you must de-allocate objects yourself No dynamic class loading - you must link all object files into a.exe Direct access to memory via pointers - powerful but dangerous The C++ Standard Template Library (STL) is extremely limited compared to the Java SE library STL has string, IO, and collection classes But STL doesn't have GUI / database / network / multithreading!

6 The Standard C++ Library The standard C++ lib incorporates the standard C lib You include header files such as,, etc. Declarations are nested in the std namespace, so you can use a using namespace statement to bring into scope The standard C++ lib also defines standard C++ classes You include header files such as,, etc. Declarations are nested in the std namespace, so you can use a using namespace statement to bring into scope #include // #include is a pre-processor directive to include a header file. #include using namespace std; // Allows unqualified access to standard C++ functions and classes. #include // #include is a pre-processor directive to include a header file. #include using namespace std; // Allows unqualified access to standard C++ functions and classes. #include using namespace std; #include using namespace std;

7 Hello World! Here's a traditional "Hello World" program in C++ main() is a global function, the entry-point in a C++ application cout outputs a message to the console (there's also cin, cerr ) endl means "new line" You can also declare main() as follows Provides access to command-line arguments // Include the standard header file that declares cout and endl. #include // Allow easy access to cout and endl, in the std namespace. using namespace std; int main() { cout << "Hello world!" << endl; return 0; } // Include the standard header file that declares cout and endl. #include // Allow easy access to cout and endl, in the std namespace. using namespace std; int main() { cout << "Hello world!" << endl; return 0; } HelloWorld.cpp int main(int argc, char *argv[]) …

8 Compiling/Linking a C++ Program (1 of 2) C++ is a compiled language Comprises source-code files (e.g. Account.cpp - you can name files anything you like!) Source-code files are compiled to object files (e.g. Account.obj ) Object files are linked together, along with library files perhaps, to create executable files (e.g. MyApp.exe ) Account.cpp Bank.cpp Customer.cpp Account.obj Bank.obj Customer.obj compilation MyApp.exe linking SomeLibrary.lib C/C++ standard library

9 Compiling/Linking a C++ Program (2 of 2) For example, to compile/link a C++ program in Linux: You can use the g++ command-line compiler/linker Use the -o option to specify the name of the executable output file Here's an example... Compiles HelloWorld.cpp to an object file Links the object file with the standard C++ library, to create an executable output file named Hello If you want more info about g++ command options: g++ HelloWorld.cpp -oHello man g++

Here's an example of how to get input from the console string is a standard C++ class, defined in the header cin inputs a value (e.g. a string or an int ) from the console Getting Input 10 #include using namespace std; int main() { string name; int age; cout << "Hi, what's your name? "; cin >> name; cout << "How old are you? "; cin >> age; cout << name << ", on your next birthday you'll be " << age + 1 << endl; return 0; } #include using namespace std; int main() { string name; int age; cout << "Hi, what's your name? "; cin >> name; cout << "How old are you? "; cin >> age; cout << name << ", on your next birthday you'll be " << age + 1 << endl; return 0; } PersonDetails.cpp

Here's an example of making simple decisions Making Decisions 11 #include using namespace std; int main() { int a, b, c; cout << "Enter the coefficient of x-squared, x, and units: "; cin >> a >> b >> c; double disc = (b * b) - (4 * a * c); if (disc < 0) { cerr << "Roots are imaginary " << endl; } else { double root1 = (-a + sqrt(disc)) / 2 * a; double root2 = (-a - sqrt(disc)) / 2 * a; cout << "Roots are " << root1 << " and " << root2 << endl; } return 0; } #include using namespace std; int main() { int a, b, c; cout << "Enter the coefficient of x-squared, x, and units: "; cin >> a >> b >> c; double disc = (b * b) - (4 * a * c); if (disc < 0) { cerr << "Roots are imaginary " << endl; } else { double root1 = (-a + sqrt(disc)) / 2 * a; double root2 = (-a - sqrt(disc)) / 2 * a; cout << "Roots are " << root1 << " and " << root2 << endl; } return 0; } MakingDecisions.cpp

12 2. Basic Syntax Rules Statements and expressions Comments Legal identifiers Classes Functions and methods

13 Statements and Expressions C++ code comprises statements C++ statements end with a semi-colon You can group related statements into a block, by using {} C++ code is free-format But you should use indentation to indicate logical structure An expression is part of a statement. For example: a+b a == b

14 Comments Single-line comment Use // Remainder of line is a comment Block comment Use /* … … */ Useful for larger comments, e.g. at the start of an algorithm Note: No concept of JavaDoc-style comments So you can't use /** … … */

15 Legal Identifiers Identifiers (names for classes, methods, variables, etc.): Must start with a letter or _ Thereafter, can contain letters, numbers, and _ Are case sensitive Keywords:

16 Classes You can define classes (nouns) in any source file You don't have to define classes in a file with the same name … although many developers do like to do this Standard C++ classes are all lowercase E.g. string E.g. list E.g. file Some developers like to use capitalization (like in Java) E.g. BankAccount E.g. Bank E.g. Customer

17 Functions and Methods C++ is based on C (this is an important pragmatic point) So C++ supports global functions i.e. you don't have to define everything in a class! C++ offers many global functions from its C heritage, and are all lowercase E.g. sqrt() E.g. max() E.g. printf() Some developers like to use capitalization E.g. CalcInterest() E.g. TransferFunds()

18 3. Declaring and Using Variables Variables Constants #define directives C++ built-in types Using integers Using floating point variables Using characters Using booleans Quiz

19 Variables All applications use variables A variable has a name, a type, and a value Note, all variables in C++ are "garbage" until you assign a value!!! General syntax: Example: A variable also has a scope: Block scope Method scope Object scope Class scope type variableName = optionalInitialValue; int yearsToRetirement = 20;

20 Constants A constant is a fixed "variable" Use the const keyword (similar to final variables in Java) Make sure the constant has a known initial value The compiler will ensure you don't modify the constant thereafter General syntax: Example: const type CONSTANT_NAME = initialValue; const long SPEED_OF_LIGHT = ; const int SECONDS_IN_MIN = 60; const int SECONDS_IN_HOUR = SECONDS_IN_MINUTE * 60; const string BEST_TEAM_IN_WALES = "Swansea City"; // const long SPEED_OF_LIGHT = ; const int SECONDS_IN_MIN = 60; const int SECONDS_IN_HOUR = SECONDS_IN_MINUTE * 60; const string BEST_TEAM_IN_WALES = "Swansea City"; //

21 #define Directives C++ code can use #define directives (originated in C) Anything that starts with # is a pre-processor directive Expanded (prior to compilation) by the pre-processor Examples in the standard C++ header file: #define directives can take parameters These are known as macros… good or bad? #define INT_MIN #define INT_MAX #define UINT_MAX … #define INT_MIN #define INT_MAX #define UINT_MAX … #define MAX(a, b) (((a) > (b)) ? (a) : (b))

C++ Built-in Types Here is the full set of built-in types in C++: Note: the size/range details vary, based on compiler and platform 22

23 Using Integers Integers store whole numbers C++ supports signed and unsigned ints (default is signed ) Absolute size of these types is platform-dependent! You can use decimal, hex, or octal notation Examples: int x, y, z; short age; long population; unsigned short goalsScored; int yearOfBirth = 1997; short goalDifference = -5; long favouriteColor = 0xFF000000; // Hexadecimal int bitMask = 0701; // Octal int x, y, z; short age; long population; unsigned short goalsScored; int yearOfBirth = 1997; short goalDifference = -5; long favouriteColor = 0xFF000000; // Hexadecimal int bitMask = 0701; // Octal

24 Using Floating Point Variables Floating point variables store fractional and large values float holds a single-precision floating point number double holds a double-precision floating point number Should you use float or double ? Use double in most cases (all the C++ APIs do) … unless memory is critical Examples: double pi = ; double c = 2.99E8; // 2.99 x 10 8 double e = E-19; // x float height = 1.58F; // The F (or f) suffix means "float", i.e. not "double". float weight = 58.5F; // Ditto. double pi = ; double c = 2.99E8; // 2.99 x 10 8 double e = E-19; // x float height = 1.58F; // The F (or f) suffix means "float", i.e. not "double". float weight = 58.5F; // Ditto.

25 Using Characters Characters are single-byte values (not Unicode!) Enclose character value in single quotes Examples: If you want to store Unicode characters, use wchar_t char myInitial = 'A'; char nl = '\n'; // Newline char cr = '\r'; // Carriage return char tab = '\t'; // Horizontal tab char nul = '\0'; // Null character (ASCII value 0) char bsl = '\\'; // Backslash char sqt = '\''; // Single quote char dqt = '\"'; // Double quote char aDec = 97; // Assign decimal value to char char aOct = '\141'; // Assign octal value to char char aHex = '\x97'; // Assign hexadecimal value to char char myInitial = 'A'; char nl = '\n'; // Newline char cr = '\r'; // Carriage return char tab = '\t'; // Horizontal tab char nul = '\0'; // Null character (ASCII value 0) char bsl = '\\'; // Backslash char sqt = '\''; // Single quote char dqt = '\"'; // Double quote char aDec = 97; // Assign decimal value to char char aOct = '\141'; // Assign octal value to char char aHex = '\x97'; // Assign hexadecimal value to char wchar_t unicodeChar = L'A';

26 Using Booleans bool variables are true/false values C++ supports automatic conversions to bool Any non-zero value implicitly means truth C++ allows non-booleans in test conditions Quite different than Java! bool isWelsh = true; bool canSing = false; bool isWelsh = true; bool canSing = false; int errorCount; … bool isBad = errorCount; // If errorCount is non-zero, isBad is true. cout << isBad; // Outputs true or false. int errorCount; … bool isBad = errorCount; // If errorCount is non-zero, isBad is true. cout << isBad; // Outputs true or false. int errorCount; … if (errorCount) { … } // If errorCount is non-zero, it means "true". int errorCount; … if (errorCount) { … } // If errorCount is non-zero, it means "true".

27 Quiz What does this code do? #include using namespace std; void main() { int swans, bloobs; cout << "Goals for Swans: "; cin >> swans; cout << "Goals for Cardiff: "; cin >> bloobs; cout << "Swansea " << swans << "-" << bloobs << " Cardiff" << endl; cout << "Press ENTER to continue dude..."; cin.ignore(256, '\n'); cin.peek(); cout << "I'm outta here!" << endl; } #include using namespace std; void main() { int swans, bloobs; cout << "Goals for Swans: "; cin >> swans; cout << "Goals for Cardiff: "; cin >> bloobs; cout << "Swansea " << swans << "-" << bloobs << " Cardiff" << endl; cout << "Press ENTER to continue dude..."; cin.ignore(256, '\n'); cin.peek(); cout << "I'm outta here!" << endl; }

28 Any Questions?