Lec1. C++ Basics
Lec1. C++ Basics
C++ Basics
TA: TBA
2
Course Info
• Moodle:
– Links to Syllabus, Announcements, Calendar, details on course policies
• Textbooks:
– Data Structures and Algorithms in C++, Goodrich, Tamassia, Mount,
2nd Edition, Wiley. ISBN: 978-0-470-38327-8.
– Data Structures and Algorithm Analysis in C++, 4/E, Mark Weiss, ISBN-
10: 013284737X, Pearson
– Introduction to Algorithms, Cormen, Leiserson, Rivest, and Stein
(CLRS), 2nd Ed., MIT Press, 2001
– Absolute C++, Global Edition,5th or 6th edition, Savitch and Mock,
Pearson
1-4
CMPS 212
Grading Criteria
Category Percentage
Programming assignments 20%
Labs and attendance 10%
Quiz 1 (Mon. 9th March at 18:00) 15%
Quiz 2 (Wed. 22nd April at 18:00) 20%
Final Exam 35%
If these dates are not convenient for you, you have to let us
know before February 15th.
1-5
CMPS 212
Course Policies
• Attendance
– You are expected to attend lectures and labs and to be
on time
– Attendance during lab sessions and lectures may be
taken (sometimes in the form of a pop quiz)
• Collaboration
– You may have discussions, but you must submit your
own solution/code
• Extensions
– Late submissions are NOT allowed
What will you learn in this
course?
• Code in C++ using the STL and templates
• Define reusable components following OOP paradigm
• Explain abstract data types such as stacks, queues
• Select the appropriate data structures for specific
problems and implement them in different ways
• Use hashing for data access and retrieval
• Apply mathematical background of algorithm analysis
to determine their efficiency
• Describe various tree and graph algorithms
• Use algorithm design techniques such as greedy, divide-
and-conquer, and dynamic programming
Why C++?
• The greatest strength of C++ is its potential for
creating fast executables and robust libraries
• C and C++ provide great flexibility in controlling low-
level aspects of how data is stored, how information
is passed, and how memory is managed
• The compiler technology has been highly optimized
(loop unrolling example)
• The greatest weakness of C++ is its complexity
Python vs C++
• Interpreter versus Compiler
– Python
• Python code -> Python interpreter -> CPU (on the fly)
• Python is an example of an interpreted language
– C++
• C++ code -> Compiler -> Machine code (compile-time)
• Executable -> CPU (run-time)
• C++ is an example of a compiled language
• Faster execution / safer distribution
first.cpp
#include <cstdlib>
#include <iostream>
/* This program inputs two numbers x and y and
outputs their sum */
int main( ) {
int x, y;
std::cout << "Please enter two numbers: ";
std::cin >> x >> y; // input x and y
int sum = x + y; // compute their sum
std::cout << "Their sum is " << sum << std::endl;
return EXIT_SUCCESS; // terminate successfully
}
‘using’ statement
#include <iostream>
using namespace std; // makes std:: available
// ...
cout << "Please enter two numbers: "; // (std:: is not
needed)
cin >> x >> y;
Introduction to C++
• C++ Origins
– Low-level languages
• Machine, assembly (will be seen in CMPS 255)
– High-level languages
• C, C++, ADA, COBOL, FORTRAN
– Object-Oriented-Programming in C++
• C++ Terminology
– Programs and functions
– Basic Input/Output (I/O) with cin and cout
1-12
A Sample C++ Program
#include <iostream>
using namespace std;
int main(){
int number;
cout << "Hello reader.\n"
<< "Welcome to C++.\n";
cout << "How many programming languages have you used? ";
cin >> number;
if (number < 1)
cout << "Read the preface. You may prefer\n"
<< "a more elementary book by the same author.\n";
else
cout << "Enjoy the book.\n";
return 0;
} Hello reader.
Welcome to C++.
How many programming languages have you used? 0
Read the preface. You may prefer
a more elementary book by the same author.
Hello reader.
Welcome to C++.
How many programming languages have you used? 1 1-13
Enjoy the book
C++ Variables
• C++ Identifiers
– Keywords/reserved words vs. Identifiers
– Case-sensitivity and validity of identifiers
– Meaningful names!
– no limit to their length
• Variables : A memory location to store data for a program
– must be declared before it is used in program
– variable name : Any legal identifier, other than reserved word.
• int numberOfBeans;
• double oneWeight, totalWeight;
– Type such as int and double : tells the compiler what kind of
data you will be storing in the variable
• Some predefined words, such as cin and cout , are not keywords.
– they are defined in libraries required by the C++ language standard.
– Safest and easiest practice is to treat all predefined identifiers as keywords
1-14
Data Types: Simple Types
1-15
Assigning Data
• Assigning data during execution
– Lvalues (left-side) & Rvalues (right-side)
• Example 1: distance = rate * time;
• Lvalues must be variables: distance
• Rvalues can be any expression: rate * time
• Example 2: count = count + 2;
1-16
Assigning Data: Shorthand Notations
1-17
Data Assignment Rules
• Compatibility of Data Assignments
– Type mismatches: Cannot place value of one type into variable of another type
• Can cause problems because value must be changed to a value of appropriate type
int intVar;
intVar = 2.99; // 2 is assigned to intVar!
double doubleVar;
doubleVar = 2; // 2.0 is assigned to doubleVar
• Called "implicit" or "automatic type conversion"
1-18
Literal Data
• A literal is a name for one specific value. Literals are often called
constants
• Cannot change values during execution
• Called "literals" because you "literally typed“ them in your program!
2 // Literal constant int
5.75 // Literal constant double
‘Z’ // Literal constant char
"Hello World" // Literal constant string
3.67e17 // Literal constant int 3.67 *10^17
– exponent e means multiply by 10 to the power that follows
1-19
Escape Sequences
1-20
Constants
• Naming your constants
– Literal constants are "OK", but provide little meaning
• e.g., seeing 24 in a program, tells nothing about what it represents
1-21
Arithmetic Operators: Named Constant
#include <iostream>
using namespace std;
int main( ){
const double RATE = 6.9;
double deposit;
cout << "Enter the amount of your deposit $";
cin >> deposit;
double newBalance;
newBalance = deposit + deposit*(RATE/100);
cout << "In one year, that deposit will grow to\n"
<< "$" << newBalance << " an amount worth waiting for.\n";
return 0;
}
• Pre-Increment : ++intVar
– Increments variable first, THEN uses new value
1-25
Post/Pre-Increment in Action
int n = 2, valueProduced;
valueProduced = 2 * (n++);
cout << valueProduced << endl;
cout << n << endl;
1-29
String type
• C++ has a data type of “string” to store sequences of characters
– Not a primitive data type; distinction will be made later
– Must add #include <string> at the top of the program
string fruit1, fruit2 = "orange";
fruit1 = "apple";
string s= fruit1 + "," + fruit2;
– The “+” operator on strings concatenates two strings together
– cin >> str where str is a string only reads up to the first whitespace
character
1-34
Input Using cin
• cin for input, cout for output
• Differences:
– ">>" (extraction operator) points opposite
• Think of it as "pointing toward where the data goes"
– Object name "cin" used instead of "cout"
– No literals allowed for cin
• Must input "to a variable"
cin >> num;
– Waits on-screen for keyboard entry
– Value entered at keyboard is "assigned" to num
• Always "prompt" user for input
cout << "Enter number of dragons: ";
cin >> numOfDragons;
• Every cin should have cout prompt
– Maximizes user-friendly input/output
1-35
Program Style
• Bottom-line: Make programs easy to read and modify
• Comments, two methods:
– // Two slashes indicate entire line is to be ignored
– /*Delimiters indicates everything between is ignored*/
– Both methods commonly used
• Identifier naming
– ALL_CAPS for constants
– lowerToUpper for variables
– Most important: MEANINGFUL NAMES!
1-36
Libraries
• C++ Standard Libraries
• #include <Library_Name>
– Directive to "add" contents of library file to your program
– Called "preprocessor directive"
• Executes before compiler, and simply "copies“ library file into your
program file
1-38