1 of 70

Course Introduction

C++ Primer – GNU Compilation starters

C. Papachristos

Robotic Workers Lab

University of Nevada, Reno

CS-202

2 of 70

Your Instructor

CS-202 C. Papachristos

Christos Papachristos

Assistant Professor

Department of Computer Science & Engineering

  • Areas of Activity:

Robotics Research @ Collaborative Robotic Workers Lab (Co-RoboWork Lab) - UNR

Coding / SW Engineering for Field Robotics

  • Education

MS in Electrical & Computer Engineering

PhD in Autonomous (Aerial) Robotics

  • Find me at:

PE - 202D (Office) / EJCH - 253 (Lab)

cpapachristos@unr.edu , papachric@gmail.com

3 of 70

Course Requirements

CS-202 C. Papachristos

  • CS-135 ( @least a C grade )

Basic program design

Control structures for selection , iteration

Use functions , employ/implement prototypes, pass parameters

Multi-dimensional arrays (declaration/usage/passing as parameters)

Basic stream I/O (with external file usage)

ALL are Strict Prerequisites !

4 of 70

Course Rules

CS-202 C. Papachristos

Grading Policy (tentative):

You cannot earn a C in the course without having earned a C on both:

  • The weighted average of the Midterm and Final exams.
  • The weighted average of the Projects and Labs.

Plus/Minus grading will be assigned as indicated in the Syllabus.

Grade re-scaling may be assigned based on an outstanding or inferior Final exam.

Note: Also, you cannot earn a passing grade (D-) in the course without a passing grade on both categories.

Class presence will be required, tracked, and factored in, for the course’s Lab Sections. For general university policy regarding class absence, see UAM 3,020.

Component

Percentage

Projects & Labs

50% (Breakdown: 40% – 10% each)

Midterm Exam

20%

Final Exam

30%

5 of 70

Course Rules

CS-202 C. Papachristos

Tasks & Responsibilities:

Weekly Projects – Bi-weekly MAX

Turn in via WebCampus! LATE submission (24hrs max) incurs 20% penalty.

After 24hrs NO SUBMISSION WILL BE ACCEPTED.

Lab Assignments – In-Lab! NO SUBMISSION WILL BE ACCEPTED AFTER.

Academic Dishonesty:

Cheating, plagiarism or otherwise obtaining grades under false pretenses constitute academic dishonesty according to the code of this university. Academic dishonesty will not be tolerated and penalties can include filing a final grade of "F"; reducing the student's final course grade one or two full grade points; awarding a failing mark on the coursework in question; or requiring the student to retake or resubmit the coursework. For more details, see the University of Nevada, Reno General Catalog.

(Also, refer to Academic Standards in course syllabus and online)

6 of 70

Course Rules

CS-202 C. Papachristos

Tasks & Responsibilities:

Weekly Projects – Bi-weekly MAX

Turn in via WebCampus! LATE submission (24hrs max) incurs 20% penalty.

After 24hrs NO SUBMISSION WILL BE ACCEPTED.

Lab Assignments – In-Lab! NO SUBMISSION WILL BE ACCEPTED AFTER.

Academic Dishonesty:

Note:

There exist widely accessible and reliable tools to cross-compare you code:

vs your classmates’ code !

vs students’ code from previous semesters !

Semantic analysis and comparison means IT WILL CATCH similarly structured code, � even if you rename your variables / change indentation / etc. !

7 of 70

Course Rules

CS-202 C. Papachristos

Academic Standards Policy for Writing Code – CSE Department:

  • Sharing ideas with other students is fine, but you should write your own code. Never copy or read other students’ code, including code from previous years. Cosmetic changes, such as rewriting comments, changing variable names, and so forth to disguise the fact that your work is copied from someone else, are easy to detect and not allowed.
  • It is your responsibility to keep your code private. Sharing your code in public is prohibited, and may result in zero credit for the assignment.
  • If you find some external code (such as an open-sourced project) that could be reused as part of your assignment, you should first contact the instructor to see whether it is fine to reuse it. If the instructor permits it, she/he may announce it to the entire class so that all students could use it. And if you decide to reuse the external code, you should clearly cite it in comments and keep the original copyright in your code, if applicable.
  • You should be prepared to explain any code you submit, including code copied/modified from external sources.

  • Every student will be asked to sign the following statement for every programming assignment:�“This code is my own work. It was written without consulting a tutor or code written by other students.”

8 of 70

Course Objectives

CS-202 C. Papachristos

Introductory-level experience to:

  • Object-oriented programming (OOP)
  • Object-oriented design (OOD)

Basic software engineering techniques , Proper program design principles

Pointers , Dynamic Memory

C++ libraries , Classes – operators , the STL

(Coding) Tools:

  • C++ programming language
  • GCC (GNU Compiler)
  • The GNU Make tool
  • Linux Operating System

9 of 70

Course Help

CS-202 C. Papachristos

Course & Projects:

Peer-Assisted Study Session (PASS) Leader:

Jazel A. Suguitan jazels@nevada.unr.edu

3 hrs in-class, 4 hrs PASS sessions

Teaching Assistants:

XinYing Wang, Bashira Akter Anima, Hudson Lynam, Yuchuan Liu

xinyingw@, banima@, hlynam@, ycliu@ [nevada.unr.edu]

50 mins per Lab section , Tutoring & Lab Quizzes

Disability Services:

Any student with a disability needing academic adjustments or accommodations is requested to speak with the Disability Resource Center as soon as possible to arrange for appropriate accommodations.

10 of 70

Course Week

CS-202 C. Papachristos

Course , Projects , Labs:

Projects will start this Thursday 1/23.

Labs will start this Thursday 1/23.

Monday

Tuesday

Wednesday

Thursday

Friday

 

 

 

Lab (8 Sections)

 

 

CLASS

 

CLASS

 

PASS Session

(Tentative)

PASS Session

(Tentative)

Project DEADLINE

NEW Project

 

11 of 70

Challenges

CS-202 C. Papachristos

Getting started:

The Linux environment (some transfer students could have a hard time).

Start with your Projects early on !

Familiarize yourselves with the Xubuntu environment at the ECC systems.

Don’t play down the significance of the Lab sessions.

Don’t wait to seek help. Benefit from all sources.

Your TAs.

Your PASS Leader.

WebCampus material (lectures, samples, etc.) & discussions.

The web… http://en.cppreference.com/w/cpp

http://www.cplusplus.com/reference/

12 of 70

Today’s Concepts

CS-202 C. Papachristos

Differences between programming languages

C++ vs Python

Compiled vs Interpreted programs

Programming “style” restrictions

C++ concepts (Learning C++ is only part of the deal)

Classes

Object-Oriented Programing

Object-Oriented Design

(But Remember: C++ is the “Latin” of programming languages)

13 of 70

Today’s Concepts

CS-202 C. Papachristos

Differences between programming languages

Compiled vs Interpreted programs

Programming “style” restrictions

C++ concepts (Learning C++ is still a significant part of the deal)

Classes

Object-Oriented Programing

Object-Oriented Design

(Remember: C++ is the “Latin” of programming languages)

  • Encapsulation
  • Inheritance
  • Polymorphism

14 of 70

Today’s Practices

CS-202 C. Papachristos

Using the Linux Operating System.

Developing under the GCC (GNU Compiler Collection) suite.

  • Linux basics, Shell usage introduction.
  • Text editor for code writing – gedit / emacs / nano / vim.

(IDEs such as Eclipse, XCode, Codeblocks etc. are not part of the supported toolchains, your programs will have to compile & run on installations like the ones on the machines of SEM321).

  • Compilation toolchain invocation.
  • Basics for large (sort of) software development project setup.

Goal : Code – Compile – Run

15 of 70

C++ Basic Info

CS-202 C. Papachristos

Created in 1979 by Bjarne Stroustrup – the originator. At Bell Labs (home of UNIX and C).

The story: “Invent a computer programming language so arcane and complex that no one except him would be able to use it.”

The background: “Languages like Simula and Ada.”

The anecdote: “Colleagues laughed a his first cut at an inscrutably hard language. Then, he went back to his lair and didn’t emerge until he had added references and templates.”

16 of 70

C++ Basic Info

CS-202 C. Papachristos

Added object-oriented features to C.

Renamed to C++ in honor of auto-increment operator.

Later standardized with several International Organization for�Standards (ISO) specifications.

  • Constantly expanding/updating standards:

Greatly influenced Java development (1991).

  • Popular modern OO language
  • Wide industry usage
  • Used in many types of applications
  • Object-Oriented
  • Portable (not as much as Java, but fairly so)
  • Efficient
  • Retains much of its C origins

C++98

C++03

C++11

C++14

C++17

C++20

Note: OLD !

(and C++03 more or less just fixes C++98 defects)

17 of 70

Procedural vs Object-Oriented

CS-202 C. Papachristos

Procedural

Modular units: functions

Program structure: hierarchical

Data and operations are not bound to each other

Examples:

C, Pascal, Basic, Python

Object-Oriented (OO)

Modular units: objects

Program structure: a graph

Data and operations are bound to each other

Examples:

C++, Java, Python

A collection of Objects

A hierarchy of functions

18 of 70

Procedural vs Object-Oriented

CS-202 C. Papachristos

The ATM Machine paradigm

Fundamental Software Development problems:

  • Maintainability
  • Adaptability (modularity)
  • Expressiveness

19 of 70

Procedural vs Object-Oriented

CS-202 C. Papachristos

Procedural

Focused on the question: “What should the program do next?” Structure program by:

  • Splitting into sets of tasks and subtasks.
  • Make Functions for tasks.
  • Perform tasks in sequence (computer).

Large amount of data and/or tasks makes projects/programs unmaintainable.

Object-Oriented (OO)

Package-up self-contained & modular pieces of code.

The world is made up of interacting Objects.

Pack away details into boxes (Objects), allowing us to consider them in their abstract form.

Focus on their (numerous) interactions.

Key concepts:

A collection of Objects

A hierarchy of functions

  • Encapsulation
  • Inheritance
  • Polymorphism

20 of 70

Classes

CS-202 C. Papachristos

What is a … Class

C++ Classes are very similar to C Structs, in that they both include user-defined sets of data items, which collectively describe some entity such as a Student, a Book, an Airplane, or a data construct such as a String, a ComplexNumber, etc…

Bank Account

account number

owner’s name

balance

interest rate

more?

deposit money

withdraw money

check balance

transfer money

more?

Operations

(behaviors)

Type

Attributes (state)

String

sequence of characters

encoding

more?

compute length

concatenate

test for equality

more?

class BankAccount

class String

21 of 70

Classes

CS-202 C. Papachristos

What is a … Class

A non-primitive & user-defined data type containing:

  • Attributes – make up the object’s state
  • Operations – define the object’s behaviors

Bank Account

account number

owner’s name

balance

interest rate

more?

deposit money

withdraw money

check balance

transfer money

more?

Operations

(behaviors)

Type

Attributes (state)

String

sequence of characters

encoding

more?

compute length

concatenate

test for equality

more?

class BankAccount

class String

22 of 70

Objects

CS-202 C. Papachristos

What is an … Object

A particular instance of a class.

Scrooge’s Account

Wilde’s Account

Smith’s Account

43-261-5

Adam Smith

$ 1,766 . 00

2.5 %

12-345-6

Ebenezer Scrooge

$ 9,999,999,999 . 99

0.0125 %

65-432-1

Oscar Wilde

$ 8 . 45

3.5 %

account number

owner’s name

balance

interest rate

class BankAccount

Bank Account

For any of these accounts, one can…

  • Deposit money
  • Withdraw money
  • Check the balance
  • Transfer money

deposit money

withdraw money

check balance

transfer money

23 of 70

Interpreters, Compilers, Hybrids

CS-202 C. Papachristos

Interpreted Languages (e.g. JavaScript, Perl, Ruby)

translate & execute

source code

interpreter

compile

source code

binary code

execute

compiler

command

compile

translate & execute

source code

bytecode

Java Virtual Machine (JVM)

Java compiler

Interpreter translates source into binary operations and executes it.

Small, easy to write

Interpreter is a program unique to each platform (i.e. operating system).

Compiled Languages (e.g. C, C++)

Many other models: (e.g. Java, Python etc.)

Bytecode is platform independent

Java Virtual Machine (the target platform) is an interpreter that is platform dependent.

Compiler is platform dependent.

Code once compiled is expressed in the instructions of the target machine�(e.g. target architecture).

24 of 70

C++ Compilation & Linkage

CS-202 C. Papachristos

C++ source code

Linux

C++

compiler

Windows

C++

compiler

Linux

linker

Linux C++ binary

Linux C++ executable code

Windows

linker

Windows C++ binary

Windows C++ executable code

Linux C++

code library

binary library code

Windows C++

code library

binary �library code

Any

text editor

25 of 70

C++ Compilation & Linkage

CS-202 C. Papachristos

C++ source code

Linux

C++

compiler

Windows

C++

compiler

Linux

linker

Linux C++ binary

Linux C++ executable code

Windows

linker

Windows C++ binary

Windows C++ executable code

Linux C++

code library

binary library code

Windows C++

code library

binary �library code

Any

text editor

26 of 70

C++ Compilation & Linkage

CS-202 C. Papachristos

C++ source code

Linux

C++

compiler

Windows

C++

compiler

Linux

linker

Linux C++ binary

Linux C++ executable code

Windows

linker

Windows C++ binary

Windows C++ executable code

Linux C++

code library

binary library code

Windows C++

code library

binary �library code

Any

text editor

27 of 70

C++ Compilation & Linkage

CS-202 C. Papachristos

C++ source code

Linux

C++

compiler

Windows

C++

compiler

Linux

linker

Linux C++ binary

Linux C++ executable code

Windows

linker

Windows C++ binary

Windows C++ executable code

Linux C++

code library

binary library code

Windows C++

code library

binary �library code

Any

text editor

28 of 70

C++ Compilation & Linkage

CS-202 C. Papachristos

C++ source code

Linux

C++

compiler

Windows

C++

compiler

Linux

linker

Linux C++ binary

Linux C++ executable code

Windows

linker

Windows C++ binary

Windows C++ executable code

Linux C++

code library

binary library code

Windows C++

code library

binary �library code

Any

text editor

29 of 70

C++ Compilation & Linkage

CS-202 C. Papachristos

C++ source code

Linux

C++

compiler

Windows

C++

compiler

Linux

linker

Linux C++ binary

Linux C++ executable code

Windows

linker

Windows C++ binary

Windows C++ executable code

Linux C++

code library

binary library code

Windows C++

code library

binary �library code

Any

text editor

30 of 70

C++ Compilation & Linkage

CS-202 C. Papachristos

From:

31 of 70

C++ Compilation & Linkage

CS-202 C. Papachristos

From:

32 of 70

C++ Compilation & Linkage

CS-202 C. Papachristos

From:

33 of 70

C++ Compilation & Linkage

CS-202 C. Papachristos

From:

34 of 70

C++ Compilation & Linkage

CS-202 C. Papachristos

From:

35 of 70

C++ Compilation & Linkage

CS-202 C. Papachristos

g++ -Wall –O3 –std=c++11 –o prog1 prog1.cpp

g++ -Wall –O3 –std=c++11 –c -o prog1.o prog1.cpp

g++ -Wall –O3 –std=c++11 –c -o prog2.o prog2.cpp

g++ -Wall –O3 –std=c++11 –o prog12 prog1.o prog2.o

g++ -Wall –O3 –std=c++11 –o prog12 prog1.o prog2.o -lm

g++ -Wall –O3 –std=c++11 –o prog1 prog1.cpp -lm

Standalone Compile

Compile Objects & Link

Linking

Running under (Linux)

./prog1

From:

36 of 70

C++ Compilation & Linkage

CS-202 C. Papachristos

g++ -Wall –O3 –std=c++11 –o prog1 prog1.cpp

g++ -Wall –O3 –std=c++11 –c -o prog1.o prog1.cpp

g++ -Wall –O3 –std=c++11 –c -o prog2.o prog2.cpp

g++ -Wall –O3 –std=c++11 –o prog12 prog1.o prog2.o

g++ -Wall –O3 –std=c++11 –o prog12 prog1.o prog2.o -lm

g++ -Wall –O3 –std=c++11 –o prog1 prog1.cpp -lm

Standalone Compile

Compile Objects & Link

Linking

Running under (Linux)

./prog1

Optional

From:

37 of 70

C++ Compilation & Linkage

CS-202 C. Papachristos

g++ -Wall –O3 –std=c++11 –o prog1 prog1.cpp

g++ -Wall –O3 –std=c++11 –c -o prog1.o prog1.cpp

g++ -Wall –O3 –std=c++11 –c -o prog2.o prog2.cpp

g++ -Wall –O3 –std=c++11 –o prog12 prog1.o prog2.o

g++ -Wall –O3 –std=c++11 –o prog12 prog1.o prog2.o -lm

g++ -Wall –O3 –std=c++11 –o prog1 prog1.cpp -lm

Standalone Compile

Compile Objects & Link

Linking

Running under (Linux)

./prog1

From:

38 of 70

C++ Compilation & Linkage

CS-202 C. Papachristos

g++ -Wall –O3 –std=c++11 –o prog1 prog1.cpp

g++ -Wall –O3 –std=c++11 –c -o prog1.o prog1.cpp

g++ -Wall –O3 –std=c++11 –c -o prog2.o prog2.cpp

g++ -Wall –O3 –std=c++11 –o prog12 prog1.o prog2.o

g++ -Wall –O3 –std=c++11 –o prog12 prog1.o prog2.o -lm

g++ -Wall –O3 –std=c++11 –o prog1 prog1.cpp -lm

Standalone Compile

Compile Objects & Link

Linking

Running under (Linux)

./prog1

Just Compile them

From:

39 of 70

C++ Compilation & Linkage

CS-202 C. Papachristos

g++ -Wall –O3 –std=c++11 –o prog1 prog1.cpp

g++ -Wall –O3 –std=c++11 –c -o prog1.o prog1.cpp

g++ -Wall –O3 –std=c++11 –c -o prog2.o prog2.cpp

g++ -Wall –O3 –std=c++11 –o prog12 prog1.o prog2.o

g++ -Wall –O3 –std=c++11 –o prog12 prog1.o prog2.o -lm

g++ -Wall –O3 –std=c++11 –o prog1 prog1.cpp -lm

Standalone Compile

Compile Objects & Link

Linking

Running under (Linux)

./prog1

And then Link them

From:

40 of 70

C++ Compilation & Linkage

CS-202 C. Papachristos

g++ -Wall –O3 –std=c++11 –o prog1 prog1.cpp

g++ -Wall –O3 –std=c++11 –c -o prog1.o prog1.cpp

g++ -Wall –O3 –std=c++11 –c -o prog2.o prog2.cpp

g++ -Wall –O3 –std=c++11 –o prog12 prog1.o prog2.o

g++ -Wall –O3 –std=c++11 –o prog12 prog1.o prog2.o -lm

g++ -Wall –O3 –std=c++11 –o prog1 prog1.cpp -lm

Standalone Compile

Compile Objects & Link

Linking

Running under (Linux)

./prog1

Also Link to an external Library libm.so

Note: Actually libstdc++ requires libm, so with g++ it is automatically linked.

From:

41 of 70

C++ Compilation & Linkage

CS-202 C. Papachristos

g++ -Wall –O3 –std=c++11 –o prog1 prog1.cpp

g++ -Wall –O3 –std=c++11 –c -o prog1.o prog1.cpp

g++ -Wall –O3 –std=c++11 –c -o prog2.o prog2.cpp

g++ -Wall –O3 –std=c++11 –o prog12 prog1.o prog2.o

g++ -Wall –O3 –std=c++11 –o prog12 prog1.o prog2.o -lm

g++ -Wall –O3 –std=c++11 –o prog1 prog1.cpp -lm

Standalone Compile

Compile Objects & Link

Linking

Running under (Linux)

./prog1

From:

42 of 70

C++ Compilation & Linkage

CS-202 C. Papachristos

g++ -Wall –O3 –std=c++11 –o prog1 prog1.cpp

g++ -Wall –O3 –std=c++11 –c -o prog1.o prog1.cpp

g++ -Wall –O3 –std=c++11 –c -o prog2.o prog2.cpp

g++ -Wall –O3 –std=c++11 –o prog12 prog1.o prog2.o

g++ -Wall –O3 –std=c++11 –o prog12 prog1.o prog2.o -lm

g++ -Wall –O3 –std=c++11 –o prog1 prog1.cpp -lm

Standalone Compile

Compile Objects & Link

Linking

Running under (Linux)

./prog1

From:

43 of 70

Hands-on C++ Compilation & Project Submission

CS-202 C. Papachristos

Log into Xubuntu at the ECC – or – install a Virtual Machine and the same Xubuntu OS on your laptop:

https://unr.canvaslms.com/courses/49327/files/folder/Projects/VirtualBox%20Installation%20Guides#

  1. Right click on the desktop screen, choose “Create Document” → “Empty File”, name it proj_1.cpp
  2. Double-click to open it (with the default text editor – gedit ), write your code and save it.
  3. Back on the Desktop screen, click the Blue sign on the top-left, and then click on “Terminal Emulator”
  4. In the terminal give the command “cd Desktop” to go to the Desktop folder
  5. In the same terminal give the command “g++ -Wall –std=c++03 -o proj_1 proj_1.cpp” to compile your code
  6. If it compiles correctly you will have a proj_1 file created which is your executable
  7. You can run to test the executable by giving the command “./proj_1” in the same terminal screen. If it compiles and runs, you can take the source code (proj_1.cpp) and put it in an archive file (zip, tar.gz) together with the documentation file. Then upload this compressed archive file on WebCampus.
  8. You will find the program that creates compressed files by clicking on the Blue sign on the top-left, and then go to “Accessories” → “Archive Manager”. You can add the files to compress via drag-and-drop.
  9. Go online in WebCampus and submit this archive file (only submit archive files .zip/.rar/.tar.gz/… that contain all your Project deliverables).

44 of 70

C++ Primer

CS-202 C. Papachristos

#include <iostream>

using namespace std;

int main()

{

int numberOfCodeLines;

cout << "Hello new programming enthusiast! "

<< "Welcome to C++.\n";

cout << "How many lines of C code have you written in your life?" << endl;

cin >> numberOfCodeLines;

if (numberOfCodeLines < 10000) {

cout << "You might find C++ to have a very steep learning curve." << endl;

}

else {

cout << "Your background might very well save the day!" << endl;

}

return 0;

}

45 of 70

#include <iostream>

using namespace std;

int main()

{

int numberOfCodeLines;

cout << "Hello new programming enthusiast! "

<< "Welcome to C++.\n";

cout << "How many lines of C code have you written in your life?" << endl;

cin >> numberOfCodeLines;

if (numberOfCodeLines < 10000) {

cout << "You might find C++ to have a very steep learning curve." << endl;

}

else {

cout << "Your background might very well save the day!" << endl;

}

return 0;

}

C++ Primer

CS-202 C. Papachristos

Preprocessor directives (e.g. Includes), Function Prototypes

  • also, namespaces

46 of 70

#include <iostream>

using namespace std;

int main()

{

int numberOfCodeLines;

cout << "Hello new programming enthusiast! "

<< "Welcome to C++.\n";

cout << "How many lines of C code have you written in your life?" << endl;

cin >> numberOfCodeLines;

if (numberOfCodeLines < 10000) {

cout << "You might find C++ to have a very steep learning curve." << endl;

}

else {

cout << "Your background might very well save the day!" << endl;

}

return 0;

}

C++ Primer

CS-202 C. Papachristos

The main – Note: returns an int

47 of 70

#include <iostream>

using namespace std;

int main()

{

int numberOfCodeLines;

cout << "Hello new programming enthusiast! "

<< "Welcome to C++.\n";

cout << "How many lines of C code have you written in your life?" << endl;

cin >> numberOfCodeLines;

if (numberOfCodeLines < 10000) {

cout << "You might find C++ to have a very steep learning curve." << endl;

}

else {

cout << "Your background might very well save the day!" << endl;

}

return 0;

}

C++ Primer

CS-202 C. Papachristos

Variable Definition

48 of 70

#include <iostream>

using namespace std;

int main()

{

int numberOfCodeLines;

cout << "Hello new programming enthusiast! "

<< "Welcome to C++.\n";

cout << "How many lines of C code have you written in your life?" << endl;

cin >> numberOfCodeLines;

if (numberOfCodeLines < 10000) {

cout << "You might find C++ to have a very steep learning curve." << endl;

}

else {

cout << "Your background might very well save the day!" << endl;

}

return 0;

}

C++ Primer

CS-202 C. Papachristos

Console Output

49 of 70

#include <iostream>

using namespace std;

int main()

{

int numberOfCodeLines;

cout << "Hello new programming enthusiast! "

<< "Welcome to C++.\n";

cout << "How many lines of C code have you written in your life?" << endl;

cin >> numberOfCodeLines;

if (numberOfCodeLines < 10000) {

cout << "You might find C++ to have a very steep learning curve." << endl;

}

else {

cout << "Your background might very well save the day!" << endl;

}

return 0;

}

C++ Primer

CS-202 C. Papachristos

Console Input

50 of 70

#include <iostream>

using namespace std;

int main()

{

int numberOfCodeLines;

cout << "Hello new programming enthusiast!\n"

<< "Welcome to C++.\n";

cout << "How many lines of C code have you written in your life?" << endl;

cin >> numberOfCodeLines;

if (numberOfCodeLines < 10000) {

cout << "You might find C++ to have a very steep learning curve." << endl;

}

else {

cout << "Your background might very well save the day!" << endl;

}

return 0;

}

C++ Primer

CS-202 C. Papachristos

Selection Structures /

Flow Control

51 of 70

C++ Primer

CS-202 C. Papachristos

Sample Dialog 1:

Hello new programming enthusiast!

Welcome to C++.

How many lines of C code have you written in your life?

1000

You might find C++ to have a very steep learning curve.

Sample Dialog 2:

Hello new programming enthusiast!

Welcome to C++.

How many lines of C code have you written in your life?

1000000

Your background might very well save the day!

User Types in

1000 at the prompt

User Types in

1000000

at the prompt

52 of 70

#include <iostream>

using namespace std;

int main()

{

int numberOfCodeLines;

cout << "Hello new programming enthusiast! "

<< "Welcome to C++.\n";

cout << "How many lines of C code have you written in your life?" << endl;

cin >> numberOfCodeLines;

if (numberOfCodeLines < 10000) {

cout << "You might find C++ to have a very steep learning curve." << endl;

}

else {

cout << "Your background might very well save the day!" << endl;

}

return 0;

}

C++ Primer

CS-202 C. Papachristos

Return value

53 of 70

C++ Identifiers & Variables

CS-202 C. Papachristos

C++ Identifiers

Can’t use keywords/reserved words.

Case-sensitivity and validity of identifiers.

Meaningful names!

Used for variables, class names, and more.

Variables

Must declare all data before use in program.

  • A memory location to store data for a program.
  • Referenced by the variable name.

54 of 70

Variable Declaration

CS-202 C. Papachristos

C++ Variables

When we declare a variable, we tell the compiler:

When and where to set aside memory space for the variable.

How much memory to set aside.

How to interpret the contents of that memory;

  • I.e., the specified data type.

int a ;

double b ;

What name we will be referring to that location in memory;

  • I.e. by its identifier, or name.

int a ;

double b ;

55 of 70

Variable Declaration

CS-202 C. Papachristos

C++ Variables

Syntax: <type> <legal identifier> ;

Examples:

int sum ;

float average ;

double grade = 98 ;

Must be declared before being used

Must be declared to be of a specific & known type �(e.g. int, float, char, etc.)

Don’t forget the semicolon at the end!

56 of 70

Variable Declaration

CS-202 C. Papachristos

C++ Variables

Naming conventions are rules for names of variables to improve readability

Different standards exist, suggested:

Start with a lowercase letter

Indicate "word" boundaries with an uppercase letter

Restrict the remaining characters to digits and lowercase letters

topSpeed bankRate1 timeOfArrival

Indicate "word" boundaries with an underscore

top_speed bank_rate_1 time_of_arrival

Note: variable names are still case sensitive!

Widely-used standard:

Google standard https://google.github.io/styleguide/cppguide.html

57 of 70

Data Types

CS-202 C. Papachristos

Primitive Types

Tables from:

Absolute C++

Copyright © 2016

Pearson, Inc.

All rights reserved.

58 of 70

Data Types

CS-202 C. Papachristos

Primitive Types

Mostly seen/used primitive types.

Tables from:

Absolute C++

Copyright © 2016

Pearson, Inc.

All rights reserved.

59 of 70

Data Assignment

CS-202 C. Papachristos

You can (and often should) initialize data in declaration statement

Note: Otherwise results can be “Undefined” if you don’t initialize!

int myValue; 1; 0; -1; 234251; -32141521;

int myValue = 0; 0;

Assigning data during execution

Value Categories (C++ Heritage from C) :

Lvalues (left-side) & Rvalues (right-side)

Lvalues must be variables

Rvalues can be any expression

Example: distance = rate * time;

Lvalue: "distance

Rvalue: "rate * time" (Note: The entire expression)

???

OK

Note: More complicated than where they�can appear, but keeping it simple for now …

Note: Actually C++ has

GLvalues, Xvalues, PRvalues )

60 of 70

You can (and often should) initialize data in declaration statement

Note: Otherwise results can be “Undefined” if you don’t initialize!

int myValue; 1; 0; -1; 234251; -32141521;

int myValue = 0; 0;

Assigning data during execution

Value Categories (C++ Heritage from C) :

Lvalues (left-side) & Rvalues (right-side)

Lvalues must be variables

Rvalues can be any expression

Example: distance = rate * time;

Lvalue: "distance

Rvalue: "rate * time" (Note: The entire expression)

Note: “Reading” from an Uninitialized variable is

Undefined Behavior

4.1 Lvalue-to-rvalue conversion

1 - A glvalue of a non-function, non-array type T can be converted to a prvalue. … If the object to which the glvalue refers is not an object of type T … or if the object is uninitialized, a program that necessitates this conversion has undefined behavior.

Data Assignment

CS-202 C. Papachristos

???

OK

61 of 70

Compatibility of Data Assignments

Type mismatches

Cannot place value of one type into variable of another type !

But sometimes, a conversion is possible …

int intVar = 2.99; 2 is assigned to intVar!

Only the integer part “fits”, so that’s all that goes …

Called “Implicit Type Conversion”

Literals

2, 5.75, 'Z', "Hello World\n"

Also known as “constants”: can’t change in program

Data Assignment

CS-202 C. Papachristos

62 of 70

Literals / Literal Data

Examples:

2 // Literal constant int

5.75 // Literal constant double

'Z' // Literal constant char

"Hello World\n" // Literal constant string

Cannot change their values during execution

Called “literals” because you “literally typed” them in your program!

Program Data

CS-202 C. Papachristos

63 of 70

Constants / Constant Data

You should not use literal constants directly in your code –

It might seem obvious to you, but not so:

limit = 52 ;

Is this weeks per year... or cards in a deck?

  • Instead, use named constants.
  • Give the constants names.

Also allows you to change multiple instances in a central place.

Program Data

CS-202 C. Papachristos

64 of 70

Constants / Constant Data

Two ways to go about this:

One way: Preprocessor Define

#define WEEKS_PER_YEAR 52

(Note: there is no “=”)

Alternative way: Constant Variable

Append “const” keyword to declaration

const float PI = 3.14159;

Program Data

CS-202 C. Papachristos

This means that the Preprocessor will just replace the WEEKS_PER_YEAR text in the code before compilation.

    • WEEKS_PER_YEAR itself is not a variable !

PI is a fully-fledged variable !

    • This means we know its type and can dependably predict its behavior across code !

65 of 70

Console Input / Output by-Example

Terminal/Console Input

  • Waits for and captures console input.
  • Attempts to interpret as int.
  • Stores result in variable int_value.

#include <iostream>

using namespace std;

int main ( ) {

int int_value;

char cString_value[10];

cin >> int_value;

cin >> cString_value;

return 0;

}

CS-202 C. Papachristos

66 of 70

Console Input / Output by-Example

Terminal/Console Input

  • Waits for and captures console input.
  • Attempts to interpret as C-string (char array).
  • Stores result in variable cString_value.

#include <iostream>

using namespace std;

int main ( ) {

int int_value;

char cString_value[10];

cin >> int_value;

cin >> cString_value;

return 0;

}

CS-202 C. Papachristos

67 of 70

Console Input / Output by-Example

Terminal/Console Input

#include <iostream>

using namespace std;

int main ( ) {

int int_value;

char cString_value[10];

cin >> int_value;

cin >> cString_value;

return 0;

}

Note: Make you type up to 9 characters (C-strings require +1 NULL-terminating character) otherwise you might get weird results…

CS-202 C. Papachristos

68 of 70

Console Input / Output by-Example

Terminal/Console Output

#include <iostream>

using namespace std;

int main ( ) {

int int_value;

char cString_value[10];

cout << "Give me an Integer" << endl ;

cin >> int_value;

cout << "Give me a String" << endl ;

cin >> cString_value;

cout << "Number: " << int_value << " and String: " << cString_value << endl;

return 0;

}

  • Prints a literal string.
  • Appends a new-line at the end.

CS-202 C. Papachristos

  • Prints another literal string.
  • Appends a new-line at the end.

69 of 70

Console Input / Output by-Example

Terminal/Console Output

#include <iostream>

using namespace std;

int main ( ) {

int int_value;

char cString_value[10];

cout << "Give me an Integer" << endl ;

cin >> int_value;

cout << "Give me a String" << endl ;

cin >> cString_value;

cout << "Number: " << int_value << " and String: " << cString_value << endl;

return 0;

}

  • Prints a literal string, an int,�a C-string, a new-line, etc…

CS-202 C. Papachristos

70 of 70

Time for Questions !

CS-202

CS-202 C. Papachristos