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

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

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

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

Full file at

LECTURE 3 C++ Basics Part 2

Expressions and Casting. Data Manipulation. Simple Program 11/5/2013

UNIT- 3 Introduction to C++

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

Expressions and Casting

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

Chapter 2: Introduction to C++

Visual C# Instructor s Manual Table of Contents

Chapter 2 Basic Elements of C++

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

CHAPTER 3 Expressions, Functions, Output

CS113: Lecture 3. Topics: Variables. Data types. Arithmetic and Bitwise Operators. Order of Evaluation

THE INTEGER DATA TYPES. Laura Marik Spring 2012 C++ Course Notes (Provided by Jason Minski)

Operators. Lecture 3 COP 3014 Spring January 16, 2018

The C++ Language. Arizona State University 1

C OVERVIEW BASIC C PROGRAM STRUCTURE. C Overview. Basic C Program Structure

Programming for Engineers Iteration

Objectives. In this chapter, you will:

LECTURE 02 INTRODUCTION TO C++

C OVERVIEW. C Overview. Goals speed portability allow access to features of the architecture speed

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

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

These are reserved words of the C language. For example int, float, if, else, for, while etc.

Variables and literals

CS 151 Review #3. // More than one variable can be defined // in a statement. Multiple variables are // separated by a comma.

Lecture 3. More About C

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

Computer System and programming in C

CS313D: ADVANCED PROGRAMMING LANGUAGE

Reserved Words and Identifiers

9/5/2018. Overview. The C Programming Language. Transitioning to C from Python. Why C? Hello, world! Programming in C

Programming. C++ Basics

Overview of C. Basic Data Types Constants Variables Identifiers Keywords Basic I/O

The C Programming Language. (with material from Dr. Bin Ren, William & Mary Computer Science)

Course Outline Introduction to C-Programming

3. Java - Language Constructs I

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

Will introduce various operators supported by C language Identify supported operations Present some of terms characterizing operators

CS112 Lecture: Primitive Types, Operators, Strings

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

Module 2 - Part 2 DATA TYPES AND EXPRESSIONS 1/15/19 CSE 1321 MODULE 2 1

Chapter 2: Using Data

Programming in C++ 5. Integral data types

Fundamental of Programming (C)

Chapter 3 Structure of a C Program

Introduction to C++ Lecture Set 2. Introduction to C++ Week 2 Dr Alex Martin 2013 Slide 1

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

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Creating a C++ Program

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

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

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

ENGINEERING 1020 Introduction to Computer Programming M A Y 2 6, R E Z A S H A H I D I

PIC 10A Flow control. Ernest Ryu UCLA Mathematics

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

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

Outline. Performing Computations. Outline (cont) Expressions in C. Some Expression Formats. Types for Operands

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

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

Two Types of Types. Primitive Types in Java. Using Primitive Variables. Class #07: Java Primitives. Integer types.

Basics of Programming

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

Declaration and Memory

4. Inputting data or messages to a function is called passing data to the function.

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

c) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance.

QUIZ. 1. Explain the meaning of the angle brackets in the declaration of v below:

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

Expressions. Arithmetic expressions. Logical expressions. Assignment expression. n Variables and constants linked with operators

Operators and Expressions:

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

Maciej Sobieraj. Lecture 1

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

Chapter 3. Numeric Types, Expressions, and Output

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

Data Types and Variables in C language

Fundamentals of Programming

Add Subtract Multiply Divide

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

Formatting & Style Examples

IPCoreL. Phillip Duane Douglas, Jr. 11/3/2010

Introduction to C ++

Introduction to Programming

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++

Chapter 7. Basic Types

ECE 122 Engineering Problem Solving with Java

CS101: Fundamentals of Computer Programming. Dr. Tejada www-bcf.usc.edu/~stejada Week 1 Basic Elements of C++

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

Getting started with C++ (Part 2)

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

CS112 Lecture: Variables, Expressions, Computation, Constants, Numeric Input-Output

Lab # 02. Basic Elements of C++ _ Part1

BASIC ELEMENTS OF A COMPUTER PROGRAM

Transcription:

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

Visual Studio in QM PC rooms Microsoft Visual Studio Community 2015. Bancroft Building 1.15a; Queen s W207, EB7; Engineering W128.D. Student PC services - click "View timetable" to check a specific room.

IDE for Mac Visual Studio for Mac - doesn t support C++, it is for C# and F# Options for an IDE include Xcode, developed by Apple Other IDEs include Eclipse and NetBeans - both of these for Windows, Linux or Mac. Setting up Eclipse or NetBeans is more involved than Xcode, need to separately install a compiler. Stackoverflow page Another Stackoverflow page

Visual Studio installation options Guide Workloads -> "Desktop development with C++" is the best option. Then there is no need to customize the other options, which are "Individual components" and "Language packs". If this takes up too much hard-drive space (6-7 GB), then there is a version called Visual Studio Express Scroll down the page to find "Express 2015 for Windows Desktop". There is also a 2017 version (preview version).

Data types Different types of data are used in C++. We need to explicitly state what kind we are using. C++ bool int unsigned int long long double float char Data type true/false integer non-negative integer integer (larger range) real number real number (less precision than double) character (single letter a, b etc.)

Storage for data types Information in the computer s memory is stored as a series of 0s and 1s. The smallest unit of memory is one bit, which holds a 0 or 1. Eight bits make one byte. The fundamental data types (int, double, bool etc.) are stored in memory that is a whole number of bytes.

Typical storage for data types On current (and recent) widely-used computers and operating systems, the following are the amount of memory that each data type uses: C++ Data type bytes bool true/false 1 int integer 4 unsigned int non-negative integer 4 long long integer (larger range) 8 double real number 8 float real number (less precision) 4 char character (single letter) 1

C++ standard rules There is a set of rules called the C++ standard. This sets out the rules that a compiler should follow when implementing and interpreting C++ code. For integer data types, the standard specifies a minimum amount of storage. For floating point data types (float, double), the standard doesn t say anything except that double is at least as much storage as float. Where the C++ standard doesn t specify what should happen, this is said to be "implementation-defined".

Checking limits of data types It is possible to check the ranges of data types on your operating system and compiler. #include <limits>... cout << sizeof(int) << endl; cout << numeric_limits<int>::max() << endl; cout << numeric_limits<int>::min() << endl; numeric_limits reference 64 bit systems

Declaring and initializing variables When a variable is first named, that is a declaration. We can give it a value at the same time (initializing it), or we can wait and give it a value later. Best to give it a value at the same time if possible, to avoid making use of a variable that has not been given a value. int k = 1; int h; h = 2;

Operators The arithmetic operators have their usual meaning + - * / These are known as "binary operators", because they take two input numbers to produce their result. Similar to other programming languages, * / have higher precedence than + -. You can use round brackets to make the precedence more clear. 4.3/2.1+1.6*7 is the same as (4.3/2.1)+(1.6*7) both are different from 4.3/(2.1 + 1.6)*7

Integer division Need to be careful when dividing integers - result of dividing two integers is an integer, so result may be truncated. Numbers entered directly in the code are called literals. E.g. int x=2; 2 is a literal here. Specifically, it is an integer literal. 2.0 and 2. are double literals. Try this: double x = 7/4; double y = 7.0/4.0; cout << x << endl; cout << y << endl;

Modulus Sometimes you do want integer division, and also the modulus (or remainder) operator: int a = 7; int n = 4; int q = a/n; int r = a%n; q is the quotient, r is the modulus. These satisfy a = nq + r Various conventions when one or more integer is negative. In C++, integer division truncates towards 0, so (-7)/4 results in 1. Then (-7)%4 must be 3.

Type conversions Different data types can be converted to one another, either explicitly or automatically. There are several methods for explicit conversion: int a=7; int n=4; double x = a/n; // no conversion of a and n double y = (double)a/(double)n; // C-style cast double z = double(a)/double(n); // function-style cast // C++-style cast: double w = static_cast<double>(a)/static_cast<double>(n); C++-style cast can be safer sometimes, but C-style cast is also fine for examples with simple numeric variables as above.

Automatic conversions In cases such as double x = 3; int k = 2; double y = k; there are implicit conversions from int to double. We can also make conversions that lose some information (or may do). These are legal C++, but the compiler may give a warning. double x = 3.5; int k = x; float y = x;

Increment/decrement operators C++ also allows unary operators. These change the value of a single variable. The increment/decrement operators add or subtract 1: ++, -- int k = 5; k++; k--; ++k; --k; This is where the name C++ comes from, as it is C with something added.

Increment/decrement operators The prefix operators ++k, --k change the value, and then make use of the updated value. The postfix operators k++, k-- change the value, but make use of the initial value. This only makes a difference if it is part of a larger expression. int h = 5; int m = h++; int k = 5; int n = ++k;

Changing a single variable If we want to change the value of a variable in other ways, we can use a unary operator: int k = 5; k += 3; k -= 2; double x = 3.4; x *= 2.4; x /= 3.5; All four of these work with integers or floating point (such as double) variables. The earlier point about integer division applies here too.

Changing a single variable We could also have done the following: int k = 5; k = k+3; k = k-2 double x = 3.4; x = x*2.4; x = x/3.5; For these examples, the unary operator += etc. is more concise, but we can extend the examples on this slide to more complicated expressions such as x = 2.0*x + 3.5/x;

Testing for equality The single = that we have already used is the assignment operator. To test if two variables are equal we use == int m = 4; int n = 3+2; bool b = m==n; cout << b << endl; bool variables are mapped to 0 for false and 1 for true. We can output the value as "true" or "false" as follows: cout << boolalpha << b << endl;

Other relational operators Comparing values > < >= <= Like ==, these return a bool value. cout << boolalpha << (3<5) << endl; int h = 4; int k = 5; bool b = h<=k; cout << boolalpha << b << endl;

And, or, not && and or! not!= not equal int h = 6; int k = 4; bool c = h>k && h<5; bool d = h!= k; bool e = (h!=3) == (k<h); bool f =!e (3<2); In some programming languages, the single symbols & and are used, but these have a different meaning in C++. We won t need them - they are for manipulating individual bits within numbers.

Operator precedence Rules for operator precedence are given here We haven t mentioned many of these yet. As with simple arithmetic operators, you can use round brackets to make the precedence more clear. Or split statements into more than one line. && (and) has higher precedence than (or)

Program control Various ways of controlling the flow of a program If, else Loops: either through a predetermined range or until some condition is met.

if, else int h = 3; int k = 5; if(k==h) cout << "Equal" << endl; else cout << "Not equal" << endl; Sometimes people put these on one line: if(k==h) cout << "Equal" << endl; else cout << "Not equal" << endl;

if, else If we have more than one command after if or else, then we need to put the code in a block using {}. int h = 3; int k = 5; int num_equal = 0; if(k==h){ num_equal++; cout << "Equal" << endl; } else{ cout << "Not equal" << endl; }

if, else if, else We can chain together multiple options: int k = 7; if(k<5){ cout << "Less than 5" << endl; } else if(k>5){ cout << "Greater than 5" << endl; } else{ cout << "Equal to 5" << endl; } As before, we can use {} for multiple-line blocks of code, although they are not needed in the example here.

While In a while loop, we keep repeating a set of commands as long as some condition is met. int k = 1; while(k<100){ cout << k << endl; k *= 3; } If the condition inside the while(...) test is false the first time around, then we skip the block inside the brackets {} and never execute those commands.

Do while With a while loop, the code inside the loop does not execute at all if the initial test is false. It may be that we want the code to always execute at least once. Then we can use a do... while(...) loop. int k = 1; do{ cout << k << endl; k *= 3; }while(k<100);

For If we want to execute a set of commands a pre-determined number of times, then a for loop is best. The structure is: for(init-statement; condition-expression; end-expression){ statement; } This is almost the same as the following while loop init-statement; while(condition-expression){ statement; end-expression; }

For For example: for(int i=0; i<10; i++){ cout << i << endl; } This is (almost) equivalent to int i=0; while(i<10){ cout << i << endl; i++; } There is a difference between the two, as the variable i only exists inside the for loop, but it is declared outside the while loop, so continues to exist afterwards.

Scope The scope of a variable is that part of the code for which is exists and can be referred to. Variables declared inside {} blocks, or if, else, while, for statements only exist in that part of the code and disappear outside of it. for(int i=0; i<10; i++){ cout << i << endl; double x = 3.2; } cout << i << endl; cout << x << endl; This code should not compile, as i and x only exist inside the loop.

Scope We can use {} around a block of commands, even without any if, for etc., and then variables declared inside are not visible outside. int k = 2; { int h = 3; } cout << k << endl; cout << h << endl; This should also not compile.

Ending loops early To leave a loop entirely, we can use break for(int i=0; i<6; i++){ cout << i << endl; if(i==3) break; } cout << "Done" << endl; To skip to the next loop iteration, we can use continue for(int i=0; i<6; i++){ cout << i << endl; if(i==3) continue; cout << i+10 << endl; } cout << "Done" << endl;

Nesting loops and other control structures The various control structures can be nested within each other in whatever way makes sense for what we are trying to do. for (int i = 1; i<5; i++) { for (int j = 1; j<6; j++){ int n = i*j; if (n>10) break; cout << i*j << endl; } }

Indentation Indentation is used to make the code structure more clear. Code inside blocks such as for loops and if statements is indented by one tab relative to the code outside. Indent styles Visual Studio has automatic indentation. It also allows code collapsing, to hide blocks of code, and matching of brackets (these are separate from indentation).

Input, output to screen We have already seen cout <<, for character output. We can input to the program using cin >>. To do this we need to declare a variable to hold the input. int k; cin >> k; cout << k+3 << endl; When the program reaches cin, it waits for input, which we type in and then press the "enter" key. These are C++-style output. There is a C-style of output and input which we will not cover - it uses functions called printf and scanf.

Formatting output Output with cout (and later to a file) does not contain spaces unless we specify them. int k = 3; int h = 2; cout << k << " " << h << endl; cout << k << "\t" << h << "\n"; \t is a tab character, and \n is a newline character, which we could use instead of endl.

Formatting output One more option is to set the number of decimal places in numerical output using setprecision. For this we need to include another header file, which as before goes at the top of the code file #include <iomanip>... double x=1.0/3.0; cout << setprecision(12) << x << endl;

Further reading Schildt book: pages 59 to 74 has more on data types and operators. Chapter 3 (pages 79 to 117) covers control statements such as if, else, for, while. Online version