CS302 - Data Structures using C++

Similar documents
Modern C++ for Computer Vision and Image Processing. Igor Bogoslavskyi and Cyrill Stachniss

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay

CS242 COMPUTER PROGRAMMING

CSCI 1061U Programming Workshop 2. C++ Basics

Looping and Counting. Lecture 3 Hartmut Kaiser hkaiser/fall_2012/csc1254.html

Looping and Counting. Lecture 3. Hartmut Kaiser hkaiser/fall_2011/csc1254.html

The C++ Language. Arizona State University 1

Fundamentals of Programming CS-110. Lecture 2

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

Programming with C++ as a Second Language

By the end of this section you should: Understand what the variables are and why they are used. Use C++ built in data types to create program

CHAPTER 1.2 INTRODUCTION TO C++ PROGRAMMING. Dr. Shady Yehia Elmashad

Types, Values, Variables & Assignment. EECS 211 Winter 2018

Object-oriented Programming for Automation & Robotics Carsten Gutwenger LS 11 Algorithm Engineering

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

Chapter 1. C++ Basics. Copyright 2010 Pearson Addison-Wesley. All rights reserved

This watermark does not appear in the registered version - Slide 1

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

Introduction to Programming EC-105. Lecture 2

Input And Output of C++

CS31 Discussion 1E. Jie(Jay) Wang Week3 Oct.12

Computer Programming : C++

Basic program The following is a basic program in C++; Basic C++ Source Code Compiler Object Code Linker (with libraries) Executable

Structured Programming Using C++ Lecture 2 : Introduction to the C++ Language. Dr. Amal Khalifa. Lecture Contents:

Type Aliases. Examples: using newtype = existingtype; // C++11 typedef existingtype newtype; // equivalent, still works

VARIABLES & ASSIGNMENTS

Why Is Repetition Needed?

Intro to Programming & C Why Program? 1.2 Computer Systems: Hardware and Software. Why Learn to Program?

Chapter 1 Introduction to Computers and C++ Programming

Outline. Introduction. Arrays declarations and initialization. Const variables. Character arrays. Static arrays. Examples.

LECTURE 02 INTRODUCTION TO C++

Introduction to Programming

Chapter 15 - C++ As A "Better C"

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)

REVIEW. The C++ Programming Language. CS 151 Review #2

DHA Suffa University CS 103 Object Oriented Programming Fall 2015 Lab #01: Introduction to C++

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 8/19/ Review. Here s a simple C++ program:

Introduction to Programming

Chapter 2. C++ Basics

FORM 1 (Please put your name and form # on the scantron!!!!) CS 161 Exam I: True (A)/False(B) (2 pts each):

5. Assuming gooddata is a Boolean variable, the following two tests are logically equivalent. if (gooddata == false) if (!

CS2141 Software Development using C/C++ C++ Basics

Exceptions, Case Study-Exception handling in C++.

Getting started with C++ (Part 2)

1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol.

1 Unit 8 'for' Loops

Chapter Overview. C++ Basics. Variables and Assignments. Variables and Assignments. Keywords. Identifiers. 2.1 Variables and Assignments

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 1/9/ Review. Here s a simple C++ program:

Introduction to C++ Systems Programming

CS

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Working with Batches of Data

Chapter 2: Basic Elements of C++

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

! A literal represents a constant value used in a. ! Numbers: 0, 34, , -1.8e12, etc. ! Characters: 'A', 'z', '!', '5', etc.

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Exercise 1.1 Hello world

A First Program - Greeting.cpp

Variables. Data Types.

CS31 Discussion. Jie(Jay) Wang Week8 Nov.18

Chapter 2: Introduction to C++

Chapter 2: Special Characters. Parts of a C++ Program. Introduction to C++ Displays output on the computer screen

Character Set. The character set of C represents alphabet, digit or any symbol used to represent information. Digits 0, 1, 2, 3, 9

Engineering Problem Solving with C++, 3e Chapter 2 Test Bank

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)

C++ Basics. Lecture 2 COP 3014 Spring January 8, 2018

Exercise 3 Logical Operators, Branching, Loops. Informatik I für Mathematiker und Physiker (HS 2015) Yeara Kozlov

CMPS 221 Sample Final

COMP322 - Introduction to C++ Lecture 02 - Basics of C++

Programming. C++ Basics

Creating a C++ Program

CSCI 123 Introduction to Programming Concepts in C++

CPE 112 Spring 2015 Exam II (100 pts) March 4, Definition Matching (8 Points)

Cours de C++ Introduction

C++ Programming Lecture 1 Software Engineering Group

Discussion 1H Notes (Week 3, April 14) TA: Brian Choi Section Webpage:

C++ Programming: From Problem Analysis to Program Design, Third Edition

Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS242 ARRAYS

Informatik I (D-ITET) Übungsstunde 9, Hossein Shafagh

Computer Science II Lecture 2 Strings, Vectors and Recursion

Numbers. John Perry. Spring 2017

Another Simple Program: Adding Two Integers

CHAPTER 3 BASIC INSTRUCTION OF C++

1. Match each of the following data types with literal constants of that data type. A data type can be used more than once. A.

Objectives. In this chapter, you will:

Lecture 7. Log into Linux New documents posted to course webpage

Integer Data Types. Data Type. Data Types. int, short int, long int

CS3157: Advanced Programming. Outline

CSCE 206: Structured Programming in C++

PIC 10A Flow control. Ernest Ryu UCLA Mathematics

Chapter 7. Additional Control Structures

In this chapter you will learn:

Introduction to Scientific Programming with C++

Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts

Name SECTION: 12:45 2:20. True or False (12 Points)

Lecture 3 Tao Wang 1

Chapter 1 INTRODUCTION

Transcription:

CS302 - Data Structures using C++ Pre-Course: Variables, Basic Types, Control Structures Kostas Alexis Slides inspired by the course Modern C++, Uni Bonn: http://www.ipb.uni-bonn.de/teaching/modern-cpp/

Declaring Variables Variable declaration follows a certain pattern <TYPE> <NAME> [ = <VALUE>]; Every variable has a type Variables cannot change their type Good practice: initialize variables if you can int unitialized_var; // not good practice bool initialized_var = true; // good practice

Naming Variables Name must start with a letter Give variables meaningful names Don t be afraid to use longer names Don t include type in the name Don t use negation in the name GOOGLE-STYLE name variables in snake_case all lowercase, underscores separate words C++ is case sensitive

Built-in Types bool programming_is_great = true; char carret_return = \n ; int your_favorite_number = 10; short small_int = 10; long big_int = 10; float fraction = 0.01f; double precise_num = 0.01; auto some_int = 13; auto some_float = 13.0f; auto some_double = 13.0; // Boolean: true or false // Single character // Integer number // Short number // Long number // Single precision float // Double precision float // Automatic type [int] // Automatic type [float] // Automatic type [double]

Operations on arithmetic types All character, integer and floating point types are arithmetic Arithmetic operations: +, -, &, / Comparisons <, >, <=, >=, == return bool a += 1 a = a+1, same for -=, *=, /=, etc Avoid == for floating point types

Some additional operations Boolean variables have logical operations: (or), && (and),! (not) bool is_nice_temperature = (!is_cold &&!is_hot) is_around25c; Additional operations on integer variables: / is integer division: 7/3 == 2 % is module division: 7%3 == 1 Increment operator: a++ ++a a+=1 Derement operator: a-- --a a -=1 Do not use (de)increment operators within another expression (e.g., a = (a++) + ++ b)

Strings #include <string> to use std::string Concatenate strings with + Check if str is empty with str.empty() Works out of the box with I/O streams #include <iostream> #include <string> int main() { std::string help = Hello ; std::cout << Type your name: << std::endl; std::string name = ; // Init empty std::cin >> name; // Read name std::cout << hello +, + name +! << std::endl; return 0; }

Use std::array for fixed size collection of items #include <array> to use std::array Store a collection of items of same type Create from data: array<float, 3> arr = {1.0f, 2.0f, 3.0f}; Access items with arr[i] indexing starts with 0 Number of stored items: arr.size() Useful access aliases First item: arr.front() == arr[0] Last item: arr.back() == arr[arr.size() 1]

Use std::vector when number of items is unknown before-wise #include <vector> to use std::vector Vector is implemented as a dynamic table Access stored items just like in std::array Remove all elements: vec.clear() Add a new item in one of two ways: vec.emplace_back(value) // preferred, c++11 vec.push_back(value) // historically better known Consider it to be a default container to store collections of items on any same type

Optimize vector resizing Many push_back/emplace_back operations force vector to change its size many times reserve(n) ensures that the vector has enough memory to store n items The parameter n can een be approximate std::vector<std::string> vec; const int kiternum = 100; // Always call reserve if you know the size vec.reserve(kiternum); for (int i=0; I < kiternum; ++i) { vec.emplace_back( hello ); }

Example vector #include <string> #include <vector> #include <iostream> using namespace std; int main() { vector<int> numbers = {1, 2, 3}; vector<string> names = { name1, name2 }; names.emplace_back( another_string ); cout << First name: << names.front() << endl; cout << Last number: << numbers.back() << endl; return 0; }

Variables live in scopes There is a single global scope Local scopes start with { and end with } All variables belong to the scope where they have been declared All variables die in the end of their scope This is the core of C++ memory system int main() { // start of main scope float some float = 13.13f; // create variable { // new inner scope auto another_float = some_float; // copy variable } // another_float dies return 0; } // some float dies

Any variable can be const Use const to declare a constant The compiler will guard it from any changes Keyword const can be used with any type GOOGLE-STYLE names constants in CamelCase starting with a small letter k: const float kimportantfloat = 20.0f; const in ksomeint = 20; const std::string khello = hello ; const is part of type: variable ksomeint has type const int Good practice: declare everything const unless it has to change

References to variables We can create a reference to any variable Use & to state that a variable is a reference float& ref = original_variable std::string& hello_ref = hello; Reference is part of type: variable ref has type float& Whatever happens to a reference happens to the variable and vice versa Yields performance gain as references avoid copying data.

References to variables We can create a reference to any variable Use & to state that a variable is a reference float& ref = original_variable std::string& hello_ref = hello; Reference is part of type: variable ref has type float& Whatever happens to a reference happens to the variable and vice versa Yields performance gain as references avoid copying data.

Const with references References are fast but reduce control To avoid unwanted changes use const const float& ref = original_variable; const std::string& hello_ref = hello; #include <iostream> using namespace std; int main() { int num = 42; int& ref = num; const int& kref = num; ref = 0; cout << ref << << num << << kref << endl; num = 42; cout << ref << << num << << kref = endl; return 0; }

If statement if (STATEMENT) { // this is executed if STATEMENT == true } else if (OTHER_STATEMENT) { // this is executed if (STATEMENT == false) && (OTHER_STATEMENT == true) } else { // this is executed if neither is true } Used to conditionally execute code All the else cases can be omitted if needed STATEMENT can be any Boolean expression

Switch statement switch (STATEMENT) { case CONST_1: // this is executed if STATEMENT == CONST_1 break; case CONST_2: // this is executed if STATEMENT == CONST_2 break; default: // this runs if no other option worked } Used to conditionally execute code Can have many case statements. break exists the switch block STATEMENT usually returns int or enum value

While loop while (STATEMENT) { } // Loop while STATEMENT == true typically condition is changed within the loop Usually used when the exact number of iterations unknown a priori Easy to form an endless loop by mistake

For loop for (INITIAL CONDITION; END_CONDITION; INCREMENT) { } // This happens until END_CONDITION == false In C++ for loops are comparably fast. Less flexible than while but less error-prone Use for when number of iterations is fixed and while otherwise

Range for Loop Iterating over standard containers like array or vector has simpler syntax Avoid mistakes with indices Show intent with syntax Has been added in C++ for (const auto& value : container) { // This happens for each value in the container }

Exit loops and iterations We have control over loop iterations Use break to exit the loop Use continue to skip to next iteration while (true) { int i = /* Magically get new int */ if ( i % 2 == 0) { cerr << I << endl; } else { break; } }

Thank you