Introduction to Scientific Programming with C++

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

Computer Programming : C++

CS242 COMPUTER PROGRAMMING

The C++ Language. Arizona State University 1

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

2 nd Week Lecture Notes

! A program is a set of instructions that the. ! It must be translated. ! Variable: portion of memory that stores a value. char

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

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

Chapter 2. C++ Basics

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

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

Chapter 2: Basic Elements of C++

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

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

Chapter 2 C++ Fundamentals

A First Program - Greeting.cpp

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

Chapter 2: Introduction to C++

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

CSCE 110 PROGRAMMING FUNDAMENTALS

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 3 BASIC INSTRUCTION OF C++

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

CS102: Variables and Expressions

UNIT- 3 Introduction to C++

Section we will not cover section 2.11 feel free to read it on your own

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

Numerical Computing in C and C++ Jamie Griffin. Semester A 2017 Lecture 2

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

Objectives. In this chapter, you will:

LECTURE 02 INTRODUCTION TO C++

Introduction to Programming

Fundamentals of Programming CS-110. Lecture 2

Engineering Problem Solving with C++, Etter/Ingber

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

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

Chapter 3 Objects, types, and values. Bjarne Stroustrup

Outline. Review of Last Week II. Review of Last Week. Computer Memory. Review Variables and Memory. February 7, Data Types

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

Variables and Constants

Programming. C++ Basics

Introduction to Programming EC-105. Lecture 2

BASIC ELEMENTS OF A COMPUTER PROGRAM

Computing and Statistical Data Analysis Lecture 3

On a 64-bit CPU. Size/Range vary by CPU model and Word size.

Chapter 2. Outline. Simple C++ Programs

Chapter 2: Using Data

Chapter 3 Objects, Types, and Values

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

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

BITG 1233: Introduction to C++

Objects and Types. COMS W1007 Introduction to Computer Science. Christopher Conway 29 May 2003

A Java program contains at least one class definition.

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

Programming with C++ Language

Lecture 2 Tao Wang 1

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

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

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

Maciej Sobieraj. Lecture 1

Chapter 1 Introduction to Computers and C++ Programming

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

PIC 10A Pointers, Arrays, and Dynamic Memory Allocation. Ernest Ryu UCLA Mathematics

6.096 Introduction to C++ January (IAP) 2009

Professor Peter Cheung EEE, Imperial College

Introduction to Programming using C++

EEE145 Computer Programming

Chapter 2 Basic Elements of C++

IT 1033: Fundamentals of Programming Data types & variables

PIC 10A Flow control. Ernest Ryu UCLA Mathematics

Introduction to Programming

Full file at

Program Fundamentals

Scientific Computing

Overview (4) CPE 101 mod/reusing slides from a UW course. Assignment Statement: Review. Why Study Expressions? D-1

Basics of Java Programming

The sequence of steps to be performed in order to solve a problem by the computer is known as an algorithm.

3. Except for strings, double quotes, identifiers, and keywords, C++ ignores all white space.

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

Creating a C++ Program

LECTURE 3 C++ Basics Part 2

CSI33 Data Structures

Relational Operators and if. Class 10

Introduction to C++ Systems Programming

Introduction to Scientific Programming with C++

Chapter 2: Overview of C++

C++ As A "Better C" Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan.

Introduction to C++ General Rules, Conventions and Styles CS 16: Solving Problems with Computers I Lecture #2

Chapter 3 Syntax, Errors, and Debugging. Fundamentals of Java

Overview. - General Data Types - Categories of Words. - Define Before Use. - The Three S s. - End of Statement - My First Program

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

Computer System and programming in C

VARIABLES & ASSIGNMENTS

CS302 - Data Structures using C++

4. Structure of a C++ program

C++ Basic Elements of COMPUTER PROGRAMMING. Special symbols include: Word symbols. Objectives. Programming. Symbols. Symbols.

Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal

CSCI 1061U Programming Workshop 2. C++ Basics

Unit 3. Constants and Expressions

Transcription:

Introduction to Scientific Programming with C++ Session 0: Basics Martin Uhrin edited by Andrew Maxwell and Ahmed Al Refaie UCL November 6, 2016 1 / 26

Table of Contents 1 Introduction to language 2 Program structure 3 Variables, constants and data types Defining variables Naming variables Constants Scope 4 Operators 5 Basic input and output 2 / 26

Introduction to language Introduction to C++ A little history Created in 1979 as an extension of C by this guy: Figure: Bjarne Stroustrup, creator of C++. Built to be fast and scalable and so has a mix of high and low-level constructs. 3 / 26

Program structure Hello World! Where it all begins // My first C ++ program Output: Hello world! # include < iostream > int main () { std :: cout << " Hello world!"; return 0; }../code/0 basics/lectures/hello world.cpp 4 / 26

Program structure Hello World dissection // My first C++ program #include <iostream> int main() { std::cout << "Hello World!"; return 0; } 5 / 26

Program structure Going from source code to an executable Figure: Compilation and linking of a C++ program 1. There are range of compilers, some common ones are g++ (GNU), icc (Intel), pgicc (PGI) and others. 1 Source http://www.aboutdebian.com/compile.htm c Keith Parkansky 6 / 26

Program structure Whitespace Definition whitespace spaces, tabs, and (sometimes) new lines. Completely equivalent as far as compiler is concerned: # include < iostream > int main (){std :: cout <<" Hello world!"; return 0;} # include < iostream > int main () { std :: cout << " Hello world!" ; return 0 ; } 7 / 26

Program structure Case sensitivity C++ is case sensitive! This means that: int main () is different from INT MAIN () which is different from int Main () and only the first version is correct. 8 / 26

Program structure Comments Two types of comment can be used: // This is a line comment. // It ends at the end of the line. // int myvariable = 0; This code will not execute! /* This is a C- style comment. It ends when the closing star - slash is reached. */ Use comments liberally - they are enormously useful! Do Avoid stating the obvious. A good comment will not say what is happening but rather why. 9 / 26

Variables, constants and data types Defining variables Defining a variable Definition variable A named portion of memory used to store a determined value. Let s define some variables: int aninteger ; double adouble ; unsigned short i; float x, y, z; Format: variable type variable name, variable name2; 10 / 26

Variables, constants and data types Naming variables Naming variables A variable name is an example of an identifier. Definition identifier an identifier is a sequence of characters used to denote the name of a variable, function 2, class 2 or any entity you need to refer to in your code. Identifiers can be any sequence of letters, digits or underscore characters but they must not: start with a digit, be one of the reserved keywords 3. Definition keyword a word that has a special meaning in the C++ language. 2 We ll see what these are shortly. 3 See http://en.cppreference.com/w/cpp/keyword for full list. 11 / 26

Variables, constants and data types Naming variables Naming variables Do Give variables meaningful names, even if this means more typing! Good: daysofweek, sumsq, isenabled, unitcell Would the variable name make sense in that context when looking at the code a year later? Use variable names, much like comment, to convey intent, e.g.: double rootmeansquare ; //.. go on to calculate rms This will make it obvious to the user that the code after this variable should calculate the rms and store it in this variable. Don t Use abbreviations unless they re VERY common. Use bad names: data, drange, a, ccn, value, one 12 / 26

Variables, constants and data types Naming variables Variable types Fundamental data types: Type Size Values bool 1 byte true or false int 4 bytes -2,147,483,648 to 2,147,483,647 double 8 bytes 2.2e-308 to 1.8e308 char 1 byte 256 character values unsigned short int 2 bytes 0 to 65,353 short int 2 bytes -32,768 to 32,767 unsigned int 4 bytes 0 to 4,294,967,295 unsigned long int 8 bytes 0 to 18,446,744,073,709,551,615 long int 8 bytes -9,223,372,036,854,775,807 to 9,223,372,036,854,775,807 float 4 bytes 1.2e-38 to 3.4e38 13 / 26

Variables, constants and data types Naming variables Using variables # include < iostream > int main () { double G = 6.6738 e -11; double massofearth = 5.9722 e24 ; double massofmoon = 7.3477 e22 ; double r = 384400 e3; double force ; force = G * massofearth * massofmoon / ( r * r); std :: cout << " Force between Earth and Moon is: " << force << "\n"; } return 0;../code/0 basics/lectures/force calc.cpp Pretty easy, right? 14 / 26

Variables, constants and data types Constants Constants Spot the difference: # include <iostream > int main () { const double G = 6.6738 e -11; const double massofearth = 5.9722 e24 ; const double massofmoon = 7.3477 e22 ; const double r = 384400 e3; double force ; force = G * massofearth * massofmoon / (r * r); std :: cout << " Force between Earth and Moon is: " << force << "\n"; G = 7e -11; // WON T COMPILE. WHAT KIND OF A UNIVERSE WOULD WE BE LIVING IN // IF G COULD VARY?? } return 0; Do../code/0 basics/lectures/force calc const.cpp Make everything const unless it absolutely has to vary. This has benefits for both the speed and correctness of your code. 15 / 26

Variables, constants and data types Scope Scope All variables have a finite life time. They are created and destroyed! Definition scope the region of a program that a variable can be used in. This determines the lifetime of a variable. The scope of a variable is defined by the block, formed by braces {}, within which it is declared. Don t Figure: Variable scope 4. Declare variables in global scope. Limit the scope as much as possible to reduce chance of side-effects. Global constants, however, are fine. 4 Source: http://www.cplusplus.com/doc/tutorial/variables/. 16 / 26

Operators Simple operators Assignment: = a = 5; a = b; Arithmetic operators: +, -, *, /, % All obvious with the exception of the modulo operator (%). This gives the remainder after division e.g. a = 22 % 7; will set a to 1 as 22 7 = 3 7 remainder 1. Compound assignment: +=, -=, *=, /=, %= Perform the operation on the current value of the variable and then set it to the new value, e.g.: a += 5; a *= b; 17 / 26

Operators Integer arithmetic Warning! In C++ integer arithmetic truncates (effectively rounds down): int a = 20; int b = 7; int someinteger = a / b; // = 2 Storing the result in a double doesn t help as the arithmetic has already been done: double somedouble = a / b; // = 2 double anotherdouble = 20/7; // = 2 What gives? To get around we can cast the variable to another type: 1 somedouble = static_cast < double >( dividend ) / static_cast < double >( divisor ); // = 2.85714 2 anotherdouble = 20./7.; // = 2.85714 18 / 26

Operators Unary operators: ++, -- a ++; This is equivalent to: a += 1; Relational and equality operators: ==,!=, >, <, >=, <= Evaluates to a boolean (true or false) value e.g.: bool arenotequal = ( a!= b); Don t Mix up = and == this will cause endless headaches! Consider: a = 5; b = 6; areequal = ( a = b); This is a problem because C++ considers any number other than 0 be true! 19 / 26

Operators Logical operators:!, &&, These act on boolean values in the following ways: NOT a!a AND a b a && b OR a b a b true false false true true true true true false false false true false false false false true true true true false true false true true false false false Do Keep it simple: don t try and do too much in a single line. While this: result = (i < 10) && (++ i < n); is a valid expression, deciphering what it does is a lot of work. Instead use: result = i < 10; ++i; result = result && i < n; 20 / 26

Operators Operator precedence No, you got first... Precedence Op. Associativity 1 ++ --! Left to Right 2 * / % 3 + - 4 < <= > >= Left to Right 5 ==!= 6 && 7 8 = Right to Left Operator precedence tells you the order that an expression will be evaluated in. Some are obvious but consider: a = 21 + 7 % 2; which could be interpreted as a = 21 + (7 % 2); // this a = (21 + 7) % 2; // or this. In fact the first version is correct. 21 / 26

Operators Do Use parentheses to make an expressions more clear even if they are not necessary. 22 / 26

Operators Operator precedence No, you got first... Precedence Op. Associativity 1 ++ --! Left to Right 2 * / % 3 + - 4 < <= > >= Left to Right 5 ==!= 6 && 7 8 = Right to Left Operators that have the same precedence are evaluated according to their associativity e.g.: a = b = c; // evaluates as a = (b = c); because = is right to left associative. While: a * b % c; // evaluates as (a * b) % c; are left to right associative. 23 / 26

Basic input and output Standard output (cout) You ve already met cout, it uses the indirection operator (<<) to print to the screen e.g.: std :: cout << " Have some pi: "; std :: cout << 3. 1415926; std :: cout << a; We can use << more than once in the same statement: double t0 = 1.5, t1 = 2.5; cout << " t0: " << t0 << ", t1: " << t1 << ", delta : " << t1 - t0; Output: t0: 1.5, t1: 2.5, delta: 1 If you want a new line you have to use \n: double t0 = 1.5, t1 = 2.5; cout << "t0: " << t0 << "\ nt1 : " << t1 << "\n"; Output: t0: 1.5 t1: 2.5 24 / 26

Basic input and output Standard input (cin) Extracting information out of the user To get input from the user, use the extraction operator (>>) of the cin object (pronounced see-in) e.g.: double radius ; std :: cin >> radius ; at this point the program will stop and wait for the user to enter a number and push RETURN. As with output we can use >> more than once in a statement e.g.: std :: cin >> width >> height ; in this case the program will wait for two sets of numbers to be entered. They can be separated by a space, tab or a newline. 25 / 26

Basic input and output Complete example Putting it all together # include < iostream > int main () { unsigned int width, height ; std :: cout << " Please enter a width and height : "; std :: cin >> width >> height ; std :: cout << " Area is: " << width * height << "\ n"; const double ratio = static_cast < double >( height ) / static_cast < double >( width ); std :: cout << " Ratio is: 1:" << ratio << " ( width : height )" << "\n"; const bool issquare = ( width == height ); std :: cout << " Is it a square? " << issquare << "\ n"; } return 0;../code/0 basics/lectures/rect info.cpp 26 / 26