0% found this document useful (0 votes)
16 views

Lec1. C++ Basics

The document discusses a C++ programming course, including an overview of topics covered, textbooks used, grading criteria, course policies, and a sample C++ program. It provides details about variables, data types, literals, constants, and arithmetic operators in C++.

Uploaded by

Majd AL Kawaas
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Lec1. C++ Basics

The document discusses a C++ programming course, including an overview of topics covered, textbooks used, grading criteria, course policies, and a sample C++ program. It provides details about variables, data types, literals, constants, and arithmetic operators in C++.

Uploaded by

Majd AL Kawaas
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 38

Chapter 1

C++ Basics

Copyright © 2017 Pearson Education, Ltd.


All rights reserved.
CMPS 212
Intermediate programming with data
structures
Section MWF 8:00-8:50
Prof: Mohamed Nassar
Office: Bliss Hall, 228
Email: [email protected]
Office Hours: MW 10:00 to 12:00 pm or by appointment

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

CMPS 212 1-3


Course Activities
• Lab
– The lectures are complemented by one 3-hour weekly
session in the computer lab
– We strongly encourage you to bring your laptops to the
labs
– https://mingw-w64.org/doku.php/download (for windows)
– Visual Studio Code (https://www.youtube.com/watch?v=DIw02CaEusY)
• Assignments
– Assignments will be given weekly and all assignments
should be submitted to Moodle on or before the due date

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;

• uninitialized variable will simply have some garbage value


– garbage value : pattern of zeros and ones was left in its memory location by
the last program that used that portion of memory.
– to avoid an uninitialized variable is to initialize variables when declared:
• int myValue = 0;
• double rate = 0.07, time, balance = 0.00;

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

• Use named constants instead: Meaningful name to represent data


const int NUMBER_OF_STUDENTS = 24;
• Now use it’s name wherever needed in program
• value cannot be changed

– possible to declare more the one constant in one


const int BRANCH_COUNT = 10, WINDOW_COUNT = 10;

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;
}

Enter the amount of your deposit $100


In one year, that deposit will grow to
$106.9 an amount worth waiting for.
1-22
Arithmetic Precision Examples
• 17 / 5 evaluates to 3 in C++!
– Both operands are integers, therefore integer division is performed!
• 17.0 / 5 equals 3.4 in C++!
– one operand is "double type“, Double "precision" division is performed!
• int intVar1 =1, intVar2=2;
intVar1 / intVar2;
– Performs integer division!
– Result: 0!

• Calculations done "one-by-one"


– 1 / 2 / 3.0 / 4 performs 3 separate divisions.
• First 1 / 2 equals 0
• Then 0 / 3.0 equals 0.0
• Then 0.0 / 4 equals 0.0! 1-23
Type Casting
• static_cast<double> is like a function that takes an
argument of almost any type and returns an “equivalent” value of
type double
– static_cast<double>(m)
• Explicitly "casts" value of m to double type and returns it
– Example expression:
doubleVar = static_cast<double>intVar1 / intVar2;
• Casting forces double-precision division to take place among two integer
variables!
• Implicit or "Automatic“ casting
• 17 / 5.5 : This expression causes an "implicit type cast" to take place,
casting the 17  17.0
• Explicit type conversion
• (double)17 / 5.5 : Same as above, using explicit cast
1-24
Shorthand Operators
• Increment & Decrement Operators
– Just short-hand notation
– Increment operator, ++
intVar++; is equivalent to intVar = intVar + 1;
– Decrement operator, --
intVar--; is equivalent to intVar = intVar – 1;
• Post-Increment : intVar++
– Uses current value of variable, THEN increments it

• 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;

This code segment produces the output:


4
3
int n = 2, valueProduced;
valueProduced = 2 * (++n);
cout << valueProduced << endl;
cout << n << endl;

This code segment produces the output:


6
3
1-26
Console Input/Output
• I/O objects cin, cout, cerr
• Defined in the C++ library called <iostream>
• Must have these lines (called pre-processor directives) near start of
file:
– #include <iostream>
using namespace std;
– Tells C++ to use appropriate library so we can use the I/O objects cin, cout,
cerr

Copyright © 2017 Pearson Education, Ltd. All rights reserved. 1-27


Console Output
• What can be outputted?
– Any data can be outputted to display screen
• Variables, Constants, Literals
• Expressions (which can include all of above)
cout << numberOfGames;
cout << " games played.";

– Cascading: multiple values in one cout


cout << numberOfGames << " games played.";

• 2 values are outputted:


"value" of variable numberOfGames,
literal string " games played."

Copyright © 2017 Pearson Education, Ltd. All rights reserved. 1-28


Separating Lines of Output
• New lines in output
– Recall: "\n" is escape sequence for the char "newline"
• A second method: object endl
Examples:
cout << "Hello World\n";
• Sends string "Hello World" to display, & escape sequence "\n", skipping to next
line
cout << "Hello World" << endl;
• Same result as above

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

Copyright © 2017 Pearson Education, Ltd. All rights reserved. 1-30


#include <iostream>
#include <string>
Input/Output (1 of 2)
using namespace std;
int main( ) {
string dogName;
int actualAge;
int humanAge;
cout << "How many years old is your dog?" << endl;
cin >> actualAge;
humanAge = actualAge * 7;
cout << "What is your dog's name?" << endl;
cin >> dogName;
cout << dogName << "'s age is approximately " <<
"equivalent to a " << humanAge << " year old human."
<< endl;
return 0;
}

How many years old is your dog?


5
What is your dog's name?
Rex
Rex's age is approximately equivalent to a 35 year old human..
1-31
#include <iostream>
#include <string>
Input/Output (2 of 2)
using namespace std;
int main( ) {
string dogName;
int actualAge;
int humanAge;
cout << "How many years old is your dog?" << endl;
cin >> actualAge;
humanAge = actualAge * 7;
cout << "What is your dog's name?" << endl;
cin >> dogName;
cout << dogName << "'s age is approximately " <<
"equivalent to a " << humanAge << " year old human."
<< endl;
return 0;
}

How many years old is your dog?


10
What is your dog's name?
Mr. Bojangles
Mr.'s age is approximately equivalent to a 70 year old human. 1-32
Formatting Output
• Formatting numeric values for output
– Values may not display as you’d expect!
cout << "The price is $" << price << endl;
• If price (declared double) has value 78.5, you might get:
– The price is $78.500000 or:
– The price is $78.5
• We must explicitly tell C++ how to output numbers in our programs!
• "Magic Formula" to force decimal sizes:
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
– force all future cout’ed values to have exactly two digits after the decimal
– Example: cout << "The price is $" << price << endl;
• Now results in the following: The price is $78.50
• Can modify precision "as you go" as well!

Copyright © 2017 Pearson Education, Ltd. All rights reserved. 1-33


#include <iostream>
using namespace std;
int main()
{
int number;
double price;
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
cout << "enter a number of items \n";
cin >> number;
cout << " Enter a unit price\n" ;
cin >> price;
cout << "nbr of tems * unit price :" << price * number
<< endl;
return 0;
}

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

• C++ has many libraries


– Input/output, math, strings, etc.

Copyright © 2017 Pearson Education, Ltd. All rights reserved. 1-37


Namespaces
• Namespace is a collection of name definitions
• For now: interested in namespace "std"
– All standard libraries we will be using are defined in the std
• Examples: #include <iostream>
using namespace std;
• Includes entire standard library of name definitions
• make only some names in a namespace available to your program,
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
• Can specify just the objects we want

1-38

You might also like