C++ Programming Lecture 1 Software Engineering Group

Similar documents
2 nd Week Lecture Notes

GE U111 Engineering Problem Solving & Computation Lecture 6 February 2, 2004

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

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

C++ Programming Lecture 4 Software Engineering Group

Loops! Loops! Loops! Lecture 5 COP 3014 Fall September 25, 2017

5. Control Statements

Basic memory model Using functions Writing functions. Basics Prototypes Parameters Return types Functions and memory Names and namespaces

CSI33 Data Structures

Programming Fundamentals. With C++ Variable Declaration, Evaluation and Assignment 1

Control Structures. Lecture 4 COP 3014 Fall September 18, 2017

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

More Flow Control Functions in C++ CS 16: Solving Problems with Computers I Lecture #4

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

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

CSc Introduc/on to Compu/ng. Lecture 8 Edgardo Molina Fall 2011 City College of New York

Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS240 BRANCHING STATEMENTS

Programming Language. Functions. Eng. Anis Nazer First Semester

LECTURE 5 Control Structures 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.

CSCE 206: Structured Programming in C++

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

Computing and Statistical Data Analysis Lecture 3

C++ PROGRAMMING. For Industrial And Electrical Engineering Instructor: Ruba A. Salamh

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

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

1 Unit 8 'for' Loops

To become familiar with array manipulation, searching, and sorting.

Programming with C++ as a Second Language

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

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

C++ Programming Lecture 7 Control Structure I (Repetition) Part I

Flow Control. CSC215 Lecture

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

Review of the C Programming Language for Principles of Operating Systems

C++ Support Classes (Data and Variables)

Chapter 5. Repetition. Contents. Introduction. Three Types of Program Control. Two Types of Repetition. Three Syntax Structures for Looping in C++

Fundamentals of Programming CS-110. Lecture 2

CSE 452: Programming Languages. Outline of Today s Lecture. Expressions. Expressions and Control Flow

Introduction. C provides two styles of flow control:

Introduction to Programming Using Java (98-388)

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

Review of the C Programming Language

Your first C++ program

EP578 Computing for Physicists

COP 2000 Note Framework Chapter 5 - Repetition Page 1

Pace University. Fundamental Concepts of CS121 1

CSCE 110 PROGRAMMING FUNDAMENTALS

3/12/2018. Structures. Programming in C++ Sequential Branching Repeating. Loops (Repetition)

5. Selection: If and Switch Controls

C++ Programming Lecture 2 Software Engineering Group

Unit 7. 'while' Loops

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

4.1. Chapter 4: Simple Program Scheme. Simple Program Scheme. Relational Operators. So far our programs follow a simple scheme

Local and Global Variables

CSCI 1061U Programming Workshop 2. C++ Basics

Iteration. Side effects

Introduction to Programming EC-105. Lecture 2

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:

VARIABLES & ASSIGNMENTS

Chapter 3 - Functions

Chapter 4. Procedural Abstraction and Functions That Return a Value. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

STUDENT OUTLINE. Lesson 8: Structured Programming, Control Structures, if-else Statements, Pseudocode

Lab Instructor : Jean Lai

There are algorithms, however, that need to execute statements in some other kind of ordering depending on certain conditions.

Chapter 17 - Notes Recursion

Week 2: Console I/O and Operators Arithmetic Operators. Integer Division. Arithmetic Operators. Gaddis: Chapter 3 (2.14,3.1-6,3.9-10,5.

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

Structured Programming. Flowchart Symbols. Structured Programming. Selection. Sequence. Control Structures ELEC 330 1

PIC 10A. Lecture 3: More About Variables, Arithmetic, Casting, Assignment

Programming with C++ Language

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. The Increment and Decrement Operators

Objectives. Chapter 4: Control Structures I (Selection) Objectives (cont d.) Control Structures. Control Structures (cont d.) Relational Operators

Chapter 2 Control in Programming. lecture 2 1

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Functions. Lecture 6 COP 3014 Spring February 11, 2018

Slide 1 CS 170 Java Programming 1 The Switch Duration: 00:00:46 Advance mode: Auto

Compilation and Execution Simplifying Fractions. Loops If Statements. Variables Operations Using Functions Errors

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 (!

c++ keywords: ( all lowercase ) Note: cin and cout are NOT keywords.

CS302 - Data Structures using C++

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program

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

These are notes for the third lecture; if statements and loops.

Chapter 4 - Notes Control Structures I (Selection)

PIC 10A Flow control. Ernest Ryu UCLA Mathematics

LOGO BASIC ELEMENTS OF A COMPUTER PROGRAM

Chapter 4: Control Structures I (Selection) Objectives. Objectives (cont d.) Control Structures. Control Structures (cont d.

Why Is Repetition Needed?

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

REPETITION CONTROL STRUCTURE LOGO

BITG 1233: Introduction to C++

The C++ Language. Arizona State University 1

CS313D: ADVANCED PROGRAMMING LANGUAGE

C++ Data Types. 1 Simple C++ Data Types 2. 3 Numeric Types Integers (whole numbers) Decimal Numbers... 5

Chapter 4 Computation

University of Technology. Laser & Optoelectronics Engineering Department. C++ Lab.

Input And Output of C++

CS 1428 Review. CS 2308 :: Spring 2016 Molly O Neil

Transcription:

C++ Programming Lecture 1 Software Engineering Group Philipp D. Schubert

Contents 1. More on data types 2. Expressions 3. Const & Constexpr 4. Statements 5. Control flow 6. Recap

More on datatypes: build-in arrays A variable can hold a value of a certain type Example int i = 42; What if I need 10 integers for solving a task? int one = 1; int two = 2; Use arrays and if I need 1000 integers or more? Build-in arrays can store N objects of the same type They are stored in one contiguous block of memory (one after another)

More on datatypes: build-in arrays Create an array of 4 integers int array[4]; array[0] = 10; array[1] = 20; array[2] = 30; array[3] = 40; cout << array[0] << endl; cout << array[3] << endl; int number = array[2]; What does this print? Problems An array does not know its size! Increases probability for out of bounds! You want to use vector instead! // next time! Caution Never ever try something like array[-3] = 12; or array[5] = 13; If indices are out-of-bounds we have undefined behavior At best Program crashes At worst Program continues Results are nonsense and you are not even aware of that

Multi-dimensional arrays Arrays can have multiple dimensions Example a 2D array (which is a matrix) int matrix[2][2]; matrix[0][0] = 1; matrix[0][1] = 2; matrix[1][0] = 3 matrix[1][1] = 4; int n = matrix[1][0]; // What is n's content? You can create arrays of arbitrary dimensions Analog to n is 3 matrix = 1 2 3 4, matrix Z2 2

Expressions An expression is a sequence of operators and their operands, that specifies a computation. Expression evaluation may produce a result and may generate side-effects. [en.cppreference.com] Operands can be variables or literals Operators [Table from http://en.cppreference.com]

Expressions Examples: arithmetic, consider int i = 5; -i i + 10 i 5 * 2 * 2 6 * 6 --i 11 % i Evaluates to -5 15-15 36 4 1 [Table from http://en.cppreference.com]

Expressions Examples: comparison, consider int i = 5; i == 5 i > 100 i <= 5 100 >= 99 Evaluates to 1 or true 0 or false 1 or true 1 or true [Table from http://en.cppreference.com]

Expressions Examples: comparison & logic, consider int i = 5;!(i == 5) (i > 100) (i == 5) (i <= 5) && (-10 <= 1) false true Evaluates to 0 or false 1 or true 1 or true 1 or true [Table from http://en.cppreference.com]

Expressions Keep operators precedence in mind In doubt always use parentheses ( expr ) expr than gets evaluated first kindergarten s rule [Table from http://en.cppreference.com]

Operator = (assign) revisited = is the assignment operator Not the mathematical equals (check for equality would be ==) Example int value = 10; In words: evaluate the expression on the right side and shove the result into the variable called value! int other = 2 * 2 + 3; // other is 7 An assignment has a left-hand side and a right-hand side Lvalue and Rvalue An lvalue is an address (e.g. a variable) An rvalue is an expression that can be evaluated

Variables revisited: const qualifier Variables can be qualified with const Do qualify constant variables with const! Examples const double PI = 3.1415926535; const int fortytwo = 21+ 21; const double value = calculatevalue(); const int i; PI = 3; fortytwo = 12; double a = PI * 2; cout << fortytwo << endl; // ok: initialized at compile time // ok: initialized at compile time // ok: initialized at run time // error: i is uninitialized const // error: PI is const // error: fortytwo is const // ok: PI is only read // ok: fortytwo is only read Constant variables can be read, but never written to after initialization Use const as much as possible It will prevent you from making errors

constexpr or calculating ahead of time Use constexpr for constant expressions Variables can be constexpr constexpr double d = 2.5*6.8+120; constexpr int i = 12*12; Functions can be constexpr as well // next lecture Note: constexpr produces constant values (d and i cannot be changed, d and i are const) Usually 1. compile source code to executable program 2. run compiled program Constant expressions are evaluated at compile time! Effectively pre-computing Leads to increased performance constexpr similar to const but evaluated at compile time

Statements Statements are fragments of the C++ program that are executed in sequence. The body of any function is a sequence of statements. [en.cpp.reference.com] Example int i = 2*3+10; // this is a statement int j = 10; // j is 10 i = j; // content of i is overwritten with js content cout << i << endl; // prints 10 Note that i = j; overrides i s content with whatever j s content is

Mathematical formulas and functions Use #include <cmath> to include mathematical functions pow(), sqrt(), abs(), sin(), cos(), Have a look at http://en.cppreference.com/w/cpp/header/cmath We will talk about functions in detail next time For now just use them What is the C++ equivalent to x = 2, x R double x = sqrt(2); What is the C++ equivalent to y = 1 4 e3, y R double y = 1/4*exp(3);

Statements C++ includes the following types of statements 1. Expression statements // e.g. n = n + 1; 2. Compound statements (blocks) // next 3. Selection statements // today 4. Iteration statements // today 5. Jump statements // e.g. return 0; in our main(), later on 6. Declaration statements // e.g. int i = 10; 7. Try blocks // later on 8. Atomic and synchronized blocks // later on

Compound Statements Compound statements or blocks are brace-enclosed sequences of statements Example { int i = 42; int j = i + 10; Note something like this is possible int i = 1; { cout << i << endl; int i = 2; cout << i << endl; { int i = 3; cout << i << endl; cout << i << endl;

Scopes: { and A variable can be defined multiple times with the same name (usually don t do it) Each name that appears in a C++ program is only valid in some portion of the source code called its scope! { int i = 42; int j = i + 10; If a variable goes out of scope it can no longer be accessed Example { int i = 42; // i can be used in this block (its scope) // i goes out of scope at this point i = 13; // error: i can no longer be used

Statements C++ includes the following types of statements 1. Expression statements // e.g. n = n + 1; 2. Compound statements (blocks) // done! 3. Selection statements // next! 4. Iteration statements // today 5. Jump statements // e.g. return 0; in our main(), later on 6. Declaration statements // e.g. int i = 10; 7. Try blocks // later on 8. Atomic and synchronized blocks // later on

Selection statements aka control flow Just a bunch of statements is not powerful How to express: You passed if you ve got more than 50% in the exercises, otherwise you fail. We need conditional code execution Three kinds of selection statements exist Selection statements or control flow constructs in C++ are if ( condition ) statement if ( condition ) statement else statement switch ( condition ) statement Note a statement can be a compound statement or a block The condition is an expression that can be evaluated to true or false

If statement if ( condition ) statement Example int i = 10; if (i < 100) { cout << i is smaller than 100" << endl; If statements allow to execute specific code depending on a condition! If only a single statement should be executed one can omit the braces { and int i = 10; if (i < 100) cout << i is smaller than 100" << endl;

If statement with else branch if ( condition ) statement else statement Example int i = 10; if (i < 100) { cout << i is smaller than 100" << endl; else { cout << i is bigger than 100" << endl; If statements allow to execute specific code depending on a condition! Braces not needed here: only one statement should be executed in each branch int i = 10; if (i < 100) cout << i is smaller than 100" << endl; else cout << i is bigger than 100" << endl;

If statement There might be more than two branches Example int i = 3; if (i == 1) { cout << i is 1" << endl; else if (i == 2) { cout << i is 2" << endl; else if (i == 3) { cout << i is 3" << endl; else { cout << i is something else" << endl;

Switch statement switch ( condition ) statement Similar to the if statement More convenient if many conditions to check switch is optimized for this purpose switch ( expression ) { case expression: // branch break; default: // default branch break;

Switch statement Switch in action Example on the right What number will be printed? What is printed if c is X' char c = 'D'; switch (c) { case 'A': cout << 1 << endl; break; case 'B': cout << 2 << endl; break; case 'C': cout << 3 << endl; break; case 'D': cout << 4 << endl; break; default: cout << -1 << endl; break;

Statements C++ includes the following types of statements 1. Expression statements // e.g. n = n + 1; 2. Compound statements (blocks) // done! 3. Selection statements // done! 4. Iteration statements // next! 5. Jump statements // e.g. return 0; in our main(), later on 6. Declaration statements // e.g. int i = 10; 7. Try blocks // later on 8. Atomic and synchronized blocks // later on

Iteration statements aka loops The previous statements on their own are not powerful enough Example calculate sum from 1 to 100! int i = 1+2+3+...+100; But if we want to sum from 1 to 10 or from 1 to 1000000? What if your user can choose the upper end? You can not write an infinite number of programs up-frond! Iteration statements or loop constructs in C++ are while ( condition ) statement do statement while ( expression); for ( init-statement (optional); condition ; expression (optional) ) statement for ( for-range-decl : for-range-init) statement Note a statement can be a compound statement or a block

for loop Problem: sum up the numbers from 1 to 100! int sum = 1+2+3+...+100; cout << "result: " << sum << endl; Better use a loop Structure of a for loop for ( init-statement (optional); condition (optional) ; expression (optional) ) statement int sum = 0; for (size_t i = 1; i <= 100; ++i) { sum += i; // means: sum = sum + i; Note: variables from outside the loop can be used inside! Same holds for loop counter! What is going on? 1. i is initialized (only once) 2. condition is checked I. If true II. I. execute loop body II. If false execute expression (usually increases loop counter), go to 2. I. skip the loop

for loops Problem: sum up the numbers from 1 2 to 100 2! int sum = 0; for (size_t i = 1; i <= 100; ++i) { sum += i*i; Observe: we can use the counter variable inside the loop! Loops can have arbitrary steps int sum = 0; for (int i = 10; i < 4; i+=10) { sum += i; cout << sum << endl;

Caution "Stupid is as stupid does. What does this print? int sum = 0; for (int i = 1; i < 3; ++i) { sum += i; --i; cout << sum << endl;

Another kind of for loop for loop for ( init-statement (optional); Example Condition (optional) ; expression (optional) ) statement int sum = 0; for (size_t i = 1; i <= 100; ++i) { sum += i; range for loop (or range for) for ( for-range-decl : for-range-init) statement Example int sum = 0; vector<int> vec = {1, 2, 3, 4, 5; for (int i : vec) { sum += i; Ubiquitous Useful when working on containers // later on! Detail: container has to implement begin() and end() // later on!

While loops while loop while ( condition ) statement Example int sum = 0; int i = 1; while (i <= 100) { sum += i; i++; Rejecting while loop

While loops Same as for for-loop: "Stupid is as stupid does. int i = 1; while (i < 2) { cout << "not wise" << endl; One has to leave the loop at some point Condition has (usually) to be evaluated to false at some point Sometimes a infinite loop is what you want Infinite for loop for (;;) { // do stuff Infinite while loop while (true) { // do more stuff

Another kind of while loop while loop while ( condition ) statement Example int sum = 0; int i = 1; while (i <= 100) { sum += i; i++; do while loop do statement while ( expression); Example int sum = 0; int i = 300; do { sum += i; while (i <= 100); Rejecting while loop Body might not be executed Non-rejecting while loop! Body is executed at least once

4 basic loops Types of loops For Range for While Do while All loops are equivalent Can be transformed into each other Example see right Use the most natural one for each situation! int i = 1; int counter = 0; do { i = i + 1; counter++; while (counter < 3); int i2 = 1; int counter2 = 0; i2 = i2 + 1; counter2++; while (counter2 < 3) { i2 = i2 + 1; counter2++;

Breaking loops Loops can be broken Use break keyword Break leaves the loop it is used in Example int i = 1; while (i > 0) { i += 1; break; [Image from http://matrix.wikia.com/]

Breaking loops Loops can be broken Use break keyword Break leaves the loop it is used in Very useful when combined with an if statement Example int sensor_value; while (true) { // do measurements sensor_value = getsensorvalue(); if (sensor_value == 0) { break; // do other stuff [Image from http://matrix.wikia.com/]

Jumping loop iterations Loop iterations can be jumped over Use continue keyword Causes a jump to the end of loop body Very useful when combined with an if statement Example for (int i = 0; i < 10; i++) { if (i!= 5) { continue; cout << i << " "; What will be printed? break would have landed on the other roof [Image from images.google.de]

A note on { and and control flow You can leave { and if you just want one statement to be executed if you use if-, for-, range-for- or while-statements Examples If int i; if (...) i = 1; else i = 2; For int sum = 0; for (int i = 0; i < 10; ++i) sum += i;

A note on nesting You can nest loops and if statements Example nested loops for (int i = 0; i < 5; ++i) { for (int j = 0; j < 5; ++j) { cout << "#"; cout << "\n"; What does this code print? ##### ##### ##### ##### #####

A note on nesting You can nest loops and if statements Example nested if statements int i = 15; if (i >= 10) { if ((i % 5) == 0) { cout << "i is greater than 9 and dividable by 5" << endl; else { cout << "i is greater than 9" << endl; else { cout << "i is smaller than 10" << endl; What does this code print?

Algorithm and program With todays lecture you have already a Turing-Complete language That is, you can compute everything that a Turing-Machine can compute That is, you can compute everything that is computable! https://de.wikipedia.org/wiki/alan_turing https://en.wikipedia.org/wiki/turing_machine Nice movie: http://www.imdb.com/title/tt2084970/ Algorithm versus program An algorithm is a description of how to solve a problem A program is an algorithm formulated for the computer C++ programs are algorithms described in a bunch of statements You can now have the first tools to formulate algorithms in C++

Algorithms, Maths & C++ You almost always can translate mathematics to C++ How to obtain a solution for a given task? Usually: I. Start with a problem II. III. IV. Abstract the problem & find an algorithm (a way of solving the problem) Formulate algorithm in mathematics Formulate mathematic algorithm in a programming language (e.g. C++) V. The resulting program then solves the problem I will try to make links between mathematics and C++ as often as possible Mathematics and programming are very similar Computer science is mathematics with electricity!, Dirk Frettlöh

A fun example: calculating an integral Calculate 0 1 4 1+x 2 dx Assumption: We don t know how to calculate an antiderivative of f x = 4 1+x 2 Solution: use numerical integration 10 lines Uses simple arithmetic A computer is very fast at arithmetic #include <iostream> #include <cmath> using namespace std; int main() { long double integral_val = 0.0; long double x = 0.0; const size_t N = 1000000; constexpr long double step_width = abs(0-1) / (long double) N; for (size_t n = 0; n < N; ++n) { integral_val += 4 / (1 + x*x); // evaluate function a point x x += step_width; integral_val = integral_val / N; cout << integral_val << endl; return 0; [Figure from wolframalpha.com]

Recap Build-in arrays Expressions Assignments Qualifiers Simple statements Mathematical formulas Scopes Statements Selection: if and switch Iteration: for and while Nesting Algorithms, mathematics and computer science

Thank you for your attention Questions?