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

Similar documents
Add Subtract Multiply Divide

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

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

CS106X Handout 03 Autumn 2012 September 24 th, 2012 Getting Started

Introduction to C++ Dr M.S. Colclough, research fellows, pgtas

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.

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

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

[CSE10200] Programming Basis ( 프로그래밍기초 ) Chapter 7. Seungkyu Lee. Assistant Professor, Dept. of Computer Engineering Kyung Hee University

LECTURE 5 Control Structures Part 2

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

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

In this chapter you will learn:

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

Engineering Problem Solving with C++, Etter/Ingber

Unit 3. Operators. School of Science and Technology INTRODUCTION

Lecture 3. Input and Output. Review from last week. Variable - place to store data in memory. identified by a name should be meaningful Has a type-

Chapter 2. C++ Basics

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

Programming - 1. Computer Science Department 011COMP-3 لغة البرمجة 1 لطالب كلية الحاسب اآللي ونظم المعلومات 011 عال- 3

Chapter 2: Basic Elements of C++

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

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

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

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

Scientific Computing

Introduction to Programming

*Starting Out with C++: From Control Structures through Objects, 7/E* by *Tony Gaddis* COMPUTER PROGRAMMING LECTURE 05 LOOPS IMRAN IHSAN

CS313D: ADVANCED PROGRAMMING LANGUAGE

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

Chapter 2. Outline. Simple C++ Programs

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

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.

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

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

Computer Programming : C++

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

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

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

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

Units 0 to 4 Groovy: Introduction upto Arrays Revision Guide

Increment and the While. Class 15

Objectives. In this chapter, you will:

CSI33 Data Structures

UNIT- 3 Introduction to C++

o Counter and sentinel controlled loops o Formatting output o Type casting o Top-down, stepwise refinement

REPETITION CONTROL STRUCTURE LOGO

PIC 10A Flow control. Ernest Ryu UCLA Mathematics

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. Looping. ++ is the increment operator.

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

Introduction to Programming EC-105. Lecture 2

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

CHAPTER 2.2 CONTROL STRUCTURES (ITERATION) Dr. Shady Yehia Elmashad

Lecture 5. Review from last week. Selection Statements. cin and cout directives escape sequences

The cin Object. cout << "Enter the length and the width of the rectangle? "; cin >> length >> width;

Introduction to Programming

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

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

Programming Fundamentals

Fundamentals of Programming CS-110. Lecture 2

2 nd Week Lecture Notes

CS Exam 2 Study Suggestions

Another Simple Program: Adding Two Integers

Chapter 1 Introduction to Computers and C++ Programming

C++ Quick Guide. Advertisements

Homework #3 CS2255 Fall 2012

CSCI 123 Introduction to Programming Concepts in C++

CSCE 110 PROGRAMMING FUNDAMENTALS

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

Unit 7. 'while' Loops

Variables and Operators 2/20/01 Lecture #

Chapter 3: Operators, Expressions and Type Conversion

Creating a C++ Program

Chapter 2 - Control Structures

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

IS 0020 Program Design and Software Tools

LECTURE 02 INTRODUCTION TO C++

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

From Pseudcode Algorithms directly to C++ programs

Arithmetic Operators. Binary Arithmetic Operators. Arithmetic Operators. A Closer Look at the / Operator. A Closer Look at the % Operator

CS2141 Software Development using C/C++ Stream I/O

Programming. C++ Basics

Lecture 3 Tao Wang 1

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

Data Types and the while Statement

Overview of C, Part 2. CSE 130: Introduction to Programming in C Stony Brook University

Getting started with C++ (Part 2)

Your first C++ program

Simple Java Programming Constructs 4

WEEK 4 OPERATORS, EXPRESSIONS AND STATEMENTS

Chapter 2: Introduction to C++

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

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

Chapter 6. I/O Streams as an Introduction to Objects and Classes. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

Declaration and Memory

Lecture 5: Making Decisions

BITG 1233: Introduction to C++

COMP Primitive and Class Types. Yi Hong May 14, 2015

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

Transcription:

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

More Arithmetic Operators More Arithmetic Operators In the first session the basic arithmetic operators were introduced. In addition to these, C++ contains a number of other operators which are, in effect, shorthand for common combinations of the basic operators. Copy Assignment Operators Because statements such as: a = a + b; are very common there exists a shorthand. a += b; Introduction to C++ Week 2 Dr Alex Martin 2013 Slide 2

More Arithmetic Operators Similar Copy Assignment Operators exist for subtraction, multiplication, division and modulus. -= *= /= %= For example, the code a = 2; a*= 2; will result in a containing the value 4. Introduction to C++ Week 2 Dr Alex Martin 2013 Slide 3

More Arithmetic Operators Pre- and Post- increment/decrement Operators c++; is shorthand for c=c+1; However, this operator comes in two flavours: ++c; c++; Called the pre-increment and post-increment operators respectively. Introduction to C++ Week 2 Dr Alex Martin 2013 Slide 4

More Arithmetic Operators Consider the code fragment: c = 1; a = ++c; This illustrates the pre-increment operator which means "Add 1 to c and assign result to a". This will result in both a and c containing the value 2. Introduction to C++ Week 2 Dr Alex Martin 2013 Slide 5

More Arithmetic Operators This should be compared with: c = 1; a = c++; Which illustrates the post-increment operator which means "Assign c to a then add 1 to c". In this case c will contain the value 2 but a the value 1. There are also corresponding pre- and post-decrement operators -- Introduction to C++ Week 2 Dr Alex Martin 2013 Slide 6

More about iostreams More about iostreams Previously we introduced the output stream cout which which we have used to print simple text and expressions to the console. e.g. int i=10;... cout << "i = " << i << endl; The iostreams package defined in <iostream> provides the functionality for simple input of data as well as output. In fact 3 streams are defined: cin cout cerr standard input stream standard output stream standard error (output) stream Introduction to C++ Week 2 Dr Alex Martin 2013 Slide 7

More about iostreams For all of the built-in types (int, double, char etc.) operators << and >> are defined to allow output and input to these standard streams. e.g. in the program readint.cpp the lines: int i; cout << "Enter an integer" << endl; cin >> i; cout << "i= " << i << endl; write the character string "Enter an integer" to the standard output stream then reads the value of i from the standard input. Finally the string "i= ", followed by the value of i is written to the standard output. Introduction to C++ Week 2 Dr Alex Martin 2013 Slide 8

More about iostreams Formatted Output These streams may be manipulated to allow fine control over the format of output. In general this is complicated and a full description is beyond the scope of this course. ( Those who are brave can read Stroustrup chapter 21 ). Here we discuss a few of the most useful features. The output format used for floating point numbers is changed through the special state manipulation functions: cout.setf( ios::scientific, ios::floatfield ); cout.setf( ios::fixed, ios::floatfield ); sets the format to scientific form e.g. 1.234e+03 sets the format to fixed point format cout.setf( std::_ios_fmtflags(0), ios::floatfield ); resets the format to the default (general) format Introduction to C++ Week 2 Dr Alex Martin 2013 Slide 9

More about iostreams The precision used when formatting floating point numbers (only) is controlled by the precision() (member) function. e.g. cout.precision(8); Sets the precision to 8 figures (or for the scientific or fixed formats 8 decimal places). The default precision is 6. This remains continuously in force until the precision() function is called again. Introduction to C++ Week 2 Dr Alex Martin 2013 Slide 10

More about iostreams The width() function specifies the minimum number of characters to be used for the NEXT output operation ONLY. This is demonstrated by the example iwidth.cpp int i=12; cout<<i<<endl; cout.width(4); cout<<i<<endl; cout.width(8); cout<<i<<endl; will print something like: 12 12 12 In the second output statement 12 is preceded by 2 spaces in a field of 4 characters giving the output. In the third output statement 12 is preceded by 6 spaces in a field of 8 characters giving the output. Introduction to C++ Week 2 Dr Alex Martin 2013 Slide 11

The If Statement In order to write any but the most trivial program there needs be some mechanism to allow the conditional execution of a block of code. In C++ this facility is provided by the if statement. Introduction to C++ Week 2 Dr Alex Martin 2013 Slide 12

The If Statement In its simplest form we require the conditional execution of only one statement: if( logical_expression ) a_single_statement ; e.g. if ( x > 5 ) cout << " x is greater than 5 " << endl; If (and only if) the logical_expression is evaluated to be logically TRUE then the following statement is evaluated. Introduction to C++ Week 2 Dr Alex Martin 2013 Slide 13

If statement In the more general case, where there are several statements to conditionally execute, we surround the block of code with curlies {} if( logical_expression ) {......... } Introduction to C++ Week 2 Dr Alex Martin 2013 Slide 14

Introduction to C++ The Relational Operators In order to form a logical_expression there is a special set of operators which allow the comparison of two variables (or expressions): There are 6 operators: == is equal to!= is NOT equal to > is greater than >= is greater or equal to < is less than <= is less than or equal to DO NOT confuse the equality operator, ==, with the assignment operator, =. Introduction to C++ Week 2 Dr Alex Martin 2013 Slide 15

If statement An expression formed using a relational operator always evaluates to be logical TRUE or FALSE. Some examples of the use of relational operators in the if statement: if ( i == 10 ) cout << " i is 10! " << endl ; if ( (x*x + y*y) > 5 ) { cout << " x-squared + y-squared is greater than 5 " << endl; } Introduction to C++ Week 2 Dr Alex Martin 2013 Slide 16

Logical operators The Logical Operators It is often useful to combine several conditions in a single logical expression. To do this there are 3 logical operators : && Logical AND Logical OR! Logical NOT Introduction to C++ Week 2 Dr Alex Martin 2013 Slide 17

logical operators These operators obey the rules of Boolean Algebra. If A and B are logical expressions then the results of these operators are according to this truth table A B A B A&&B!A T T T T F T F T F F F T T F T F F F F T Introduction to C++ Week 2 Dr Alex Martin 2013 Slide 18

If statement The combination of logical operators and the relational operators allows one to build up complex logical expressions, e.g. if ( ( x > 5 ) && ( x < 10 ) ) { cout << " x is between 5 and 10 " << endl; } Introduction to C++ Week 2 Dr Alex Martin 2013 Slide 19

The Nature of truth in C++ The Nature of Truth in C++ In C++ an expression which evaluates to 0 is equivalent to logically FALSE whilst ANY other value is logically TRUE. Thus in the expression: if (1) cout << " This is silly " << endl; Will always execute the output statement. Introduction to C++ Week 2 Dr Alex Martin 2013 Slide 20

if...else Often one wants to choose between execution of two or more blocks of code, depending on the results of logical expressions. To make a simple choice between two options one can use a if... else construct Introduction to C++ Week 2 Dr Alex Martin 2013 Slide 21

if...else The general block form looks like: if(logical_expression ) {... } else {... } Introduction to C++ Week 2 Dr Alex Martin 2013 Slide 22

if..else if More complex constructs can be built using nested if statements, or the logically equivalent if... else if construct: if(logical_expression ) {... } else if ( another_logical_expression ) {... } Introduction to C++ Week 2 Dr Alex Martin 2013 Slide 23

if..else if..else Here is an example, similar to inttest.cpp, showing how to choose between the three cases: i=0, i<0 and i>0 : if ( i == 0) { cout << " i is 0 " << endl; } else if ( i < 0 ) { cout << " i is less than 0 " << endl; } else { cout << " i is greater than 0 " << endl; } Introduction to C++ Week 2 Dr Alex Martin 2013 Slide 24

while loops Loops: The while Statement A very common programming task involves the evaluation of an expression several times with different variable values. Rather than tediously typing in many lines of repetitive code it is convenient to introduce the idea of a loop construct. The while( ) Statement is the simplest way of allowing repetition of some code...a loop in the program. Introduction to C++ Week 2 Dr Alex Martin 2013 Slide 25

while loops Introduction to C++ Week 2 Dr Alex Martin 2013 Slide 26

while loops It takes the general block form: while ( logical_expression ){... } Examples of some logical_expressions are: I < 10 i less than 10 J > 20 j greater than 20 k == j k equal to j Don't confuse the equality operator with assignment. Introduction to C++ Week 2 Dr Alex Martin 2013 Slide 27

while loops While the logical_expression is True then the series of statements within the curlies are evaluated until the logical_expression is False The following code fragment calculates adds up the numbers between 1 and 10 int sum = 0; int k = 0; while ( k < 10 ) { k = k + 1; sum = sum + k; } Introduction to C++ Week 2 Dr Alex Martin 2013 Slide 28

do...while loops do...while blocks The do...while statement is a variation of the while statement in which a block of statements is evaluated at least once before a logical test is made: Introduction to C++ Week 2 Dr Alex Martin 2013 Slide 29

do...while loops The example above may be rewritten using do...while: int sum = 0, k = 0; do { k = k + 1; sum = sum + k; } while( k < 10 ); A complete version of this program is available Introduction to C++ Week 2 Dr Alex Martin 2013 Slide 30

For loops More General Loops: The for Statement C++ has a very general and flexible way of forming loops using the for statement. It may be thought of a generalized while loop. Usually S1 and S3 are used to initialize and update a counter variable. Introduction to C++ Week 2 Dr Alex Martin 2013 Slide 31

For loops The following code fragment demonstrates its use: (S1) (E1) (S3) for ( int i = 0; i < 20; i++) { }... This code defines a loop, the loop variable i, which takes in turn the values 0,1,2,...19, for each value of i the block of code enclosed by the curlies is evaluated. The block of code is therefore executed 20 times A general for construct always has 3 statements. These are Introduction to C++ Week 2 Dr Alex Martin 2013 Slide 32

For loops N.B. A variable such as i, is said to be declared within the scope of the for loop ONLY. You can not access it from OUTSIDE the loop (though you can declare another variable with the same name). This is also true if you declare a variable within the for loop's curlies. The following sumsqs2.cpp calculates the sum-of-squares between 1 and 10: int sum=0; for(int i=1; i<=10; i++){ sum+=i*i; cout << " Sum of squares, i= " << i << " Sum = " << sum <<endl; } Introduction to C++ Week 2 Dr Alex Martin 2013 Slide 33

For loops You should generally use an integer variable as the for loop counter to ensure the loop is evaluated the correct number of times. For example, because of possible rounding errors its difficult to be certain, how many times the following loop is evaluated: double delta=1.0/3.0; for(double x=2; x<=5; x+=delta ){... } Introduction to C++ Week 2 Dr Alex Martin 2013 Slide 34

For loops To avoid such problems you should use an integer loop counter and derive the floating value from it. So the above bad example could be rewritten as so: or double delta=1.0/3.0; for(int i=0; i<=15; i++ ){ double x = 2.0 + i*delta;... } double delta=1.0/3.0; double x=2.0; for(int i=0; i<=15; i++ ){... x+=delta; } Introduction to C++ Week 2 Dr Alex Martin 2013 Slide 35

Introduction to C++ Introduction to C++ Week 2 Dr Alex Martin 2013 Slide 36