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

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

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. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

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

Introduction to Programming

Objectives. In this chapter, you will:

Chapter 2. C++ Basics

UNIT- 3 Introduction to C++

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

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

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

The C++ Language. Arizona State University 1

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

Operators. Java operators are classified into three categories:

Chapter 2 Basic Elements of C++

Add Subtract Multiply Divide

CS242 COMPUTER PROGRAMMING

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

BITG 1233: Introduction to C++

Chapter 1 Introduction to Computers and C++ 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

C++ Support Classes (Data and Variables)

A First Program - Greeting.cpp

Introduction to C++ Programming. Adhi Harmoko S, M.Komp

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

Chapter 2. Lexical Elements & Operators

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

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are:

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

Creating a C++ Program

CSCI 1061U Programming Workshop 2. C++ Basics

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

YOLOP Language Reference Manual

Contents. Jairo Pava COMS W4115 June 28, 2013 LEARN: Language Reference Manual

Lecture 3 Tao Wang 1

Introduction to C++ Programming Pearson Education, Inc. All rights reserved.

printf( Please enter another number: ); scanf( %d, &num2);

Fundamentals. Fundamentals. Fundamentals. We build up instructions from three types of materials

Informatica e Sistemi in Tempo Reale

5. Control Statements

Fundamentals of Programming

Unit 3. Operators. School of Science and Technology INTRODUCTION

CS102: Variables and Expressions

UNIT-2 Introduction to C++

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

Lecture 4 CSE July 1992

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.

Computer Programming : C++

Fundamental of Programming (C)

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

Programming with C++ as a Second Language

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

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

Basics of Java Programming

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

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

age = 23 age = age + 1 data types Integers Floating-point numbers Strings Booleans loosely typed age = In my 20s

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

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

Full file at

The following expression causes a divide by zero error:

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

Decisions, Decisions. Testing, testing C H A P T E R 7

Algorithms and Programming I. Lecture#12 Spring 2015

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

Unit 6 - Software Design and Development LESSON 3 KEY FEATURES

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

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

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

C: How to Program. Week /Mar/05

Program Fundamentals

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

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

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

Introduction to Scientific Programming with C++

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

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

Java+- Language Reference Manual

CHRIST THE KING BOYS MATRIC HR. SEC. SCHOOL, KUMBAKONAM CHAPTER 9 C++

Chapter 2. Outline. Simple C++ Programs

Week 4 Lecture 1. Expressions and Functions

Variables and Constants

Variables, expressions and statements

7/8/10 KEY CONCEPTS. Problem COMP 10 EXPLORING COMPUTER SCIENCE. Algorithm. Lecture 2 Variables, Types, and Programs. Program PROBLEM SOLVING

CIS 130 Exam #2 Review Suggestions

Course Outline. Introduction to java

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 3: SEP. 13TH INSTRUCTOR: JIAYIN WANG

IT 374 C# and Applications/ IT695 C# Data Structures

Unit 3, Lesson 2 Data Types, Arithmetic,Variables, Input, Constants, & Library Functions. Mr. Dave Clausen La Cañada High School

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

Chapter 2 - Introduction to C Programming

Unit 6 - Software Design and Development LESSON 3 KEY FEATURES

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

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

Introduction to C ++

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

CS201 Some Important Definitions

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

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

Transcription:

First Program

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

C++ programs consist of a series of instructions written in using the C++ syntax Usually broken down into a number of functions And often in different files A C++ program needs to be translated into something that a computer can understand This process is called compiling A compiler translates high-level language code into machine code

correct errors Source File (.cpp) write in a text editor Debugged Executable compile preprocessor handles directives Object File (binary) test Other Object Files linker links files Executable File

Most OSs include C++ compilers and allow a program to be compiled and run To compile and run a program in Linux follow these steps Write the program using a text editor Compile the program using the g++ compiler Run the program created by compilation by typing its name

Assume there is a C++ file named test.cpp Open a Terminal window in Linux At the command prompt type g++ o test test.cpp The o switch (or flag) tells the compiler to name the object file that is being created test test.cpp is the name of the file to be compiled To run the newly created file type./test

In reality if we ve just finished writing our first C++ file it will fail to compile Because it contains compilation errors That is, mistakes in C++ syntax The compiler will print a list of errors That we can then fix More on this later...

An alternative to using the Terminal to compile programs is to use an IDE Integrated Development Environment An IDE combines a text editor, a compiler, a debugger and (many) other tools There are many IDEs Visual Studio (Windows) Code::Blocks (cross-platform) Xcode (Mac OS) Eclipse

Assume we want to simplify fractions 4/16 = 1/4 105/135 = 7/9 To simplify a fraction Find the greatest common divisor (gcd) of the numerator and denominator Using Euclid's algorithm Divide numerator and denominator by the gcd

Saying that "we want to simplify fractions" is a somewhat vague problem description Input The user will be prompted to enter two integers Output The program will print the simplified result in the form numerator / denominator Process Find the gcd of the numerator and denominator Print numerator gcd a "/" and denominator gcd

#include <iostream> int main() { int numerator = 0; int denominator = 1; // Get user input std::cout << "Enter the numerator: "; std::cin >> numerator; std::cout << "Enter the denominator: "; std::cin >> denominator; // Compute GCD of numerator and denominator using Euclid's algorithm int a = numerator; int b = denominator; while (a!= b) { if (a > b) { a = a - b; } else { b = b - a; } } } // Print result std::cout << std::endl << numerator/a << "/" << denominator/a << std::endl; return 0;

The program has a number of sections Introductory comments That describe the program Omitted from previous slide for space An include statement That imports library functions A main function That actually does the work The main function includes an implementation of Euclid's algorithm (the while statement)

Comments document programs They explain what a program does And how it works They are ignored by the compiler /* Program to simplify a fraction Author: John Edgar Date: January 2017 */ A comment starts with /* and ends with */ And may include more than one line Writing comments is an important part of writing a maintainable program And you will lose marks if you don t write comments in assignments...

There are two ways of writing comments Starting with /* and ending with */ Or single line comments that start with // and continue to the end of the line Either method of commenting is acceptable The // style is particularly useful for single line comments

The include statement is a pre-processor directive The pre-processor operates before the compiler #include tells the pre-processor to include the contents of iostream in our program Opens the iostream file Copies its contents Pastes it, replacing the include directive

The iostream file contains information that our program need For this program it is access to cin and cout Which are used for standard input and output Usually input from the keyboard and output to the monitor iostream contains input and output functions Input and output streams Programs will often need to use functions and classes from library files

C++ programs have one main function that executes when the program is run This function has to be called main We will write (lots of) other functions that we will give different names to The main function always has the same general form

int main() { the return type of the function the function s parameter list (empty) the name of the function, main in this case // stuff you want to happen } return 0; semi-colon, you ll see lots of these return statement, more on this later opening and closing curly brackets

A program is a sequence of instructions executed in order The order in which instructions are given is important And cannot be arbitrarily changed with the expectation that the same results will occur When main executes it starts with the first line and ends when it reaches the return statement Any instructions after the return statement will not be executed Various control statements may change program flow to allow loops or branching

Semi-colons show the end of C++ instructions Most C++ statements are written on one line However, the newline character does not indicate the end of a statement Don't forget semi-colons As the program won't compile without them Generally, you need a semi-colon after each statement that does not start or end with { or }

The simplify program uses four variables Variables are used to store data Variables can be initialized or changed using the assignment operator, = The variables in simplify all have the same type The type specifies what kind of data is stored int numerator = 0; int denominator = 1; int a = numerator; int b = denominator; These variables are type int - used to store whole numbers A variable's type is specified when only it is declared Thereafter variables are referred to just by name without noting the type

identifiers (names) int a, b; type or list of integer variables, separated by commas int a = 213; declaration and initialization Note that it is important to give variables meaningful names; I used a and b because Euclid's algorithm finds the greatest common denominator of two arbitrary integers

Simplify includes operations on integer data Subtraction and division Assignment An operation requires an operator and at least one operand a = a b; assignment is a binary operation since there are two operands, one on the left and one on the right left operand operator right operand? the right operand is the result of a-b note that this one statement contains two binary operations with a distinct order

Loops are constructs that perform repetition That is they repeat code inside the body of the loop until some condition is met If the condition cannot be met the loop will continue running forever (an infinite loop) In the simplify program the loop continues to run as long as a and b have different values The code that is repeated is contained within {}s that come after the condition

while(a!= b) { if(a > b){ a = a-b; }else{ b = b-a; } } keyword (while) and condition the condition (a is not equal to b) evaluates to true or false the body of the loop is repeatedly executed until the condition is false the condition compares values stored in the integer variables

while(condition) { //loop body } the condition is a comparison that evaluates to true or false conditions can be more complex and may not involve comparisons the loop body consists of the statements that are to be repeated the condition is tested before each iteration of the loop If the condition is true the statements in the body of the loop are executed if the condition is false the program jumps to the statement after the loop body's closing bracket

If statements are constructs that allow decisions to be made One set of statements is performed if the condition is true Another set of statements is performed if the condition is false Unlike loops, if statements do not perform repetition One set of statements is performed and the program continues from the end of the if statement

Both while loops and if statements use conditions A condition is a Boolean expression that evaluates to true or false Boolean expressions compare two values with a comparison operator One of <, <=, >, >=, == (equal to),!= (not equal to) More complex conditions are possible and these will be discussed later in the course

if(a > b) { a = a-b; }else{ b = b-a; } keyword (if) and condition the condition (a > b) is true if a is greater than b and false otherwise executed if a is greater than b keyword else, i.e. otherwise... executed if a is not greater than b if statements are not required to have an else clause

The last line of the program prints the result using cout std::cout << std::endl << numerator/a << "/" << denominator/a << std::endl; The << operator is used to output data of each type << is the insertion operator Text is written as a double-quoted string, e.g. "/" The std::endl constant prints a newline character A string is a sequence of characters Strings can be of any length And must be enclosed in ""s

A text editor designed for use with C++ colours words to aid readers Different text editors use different colours The Linux text editor uses different colours from those presented in this presentation It is common to colour the following Keywords (blue in presentation) Strings, i.e. words enclosed by ""s (red) Comments (green)

Indentation is used to indicate flow of control Everything in the main function s brackets is indented underneath the word main The body of the while loop is farther indented under the while statement Indentation helps the reader, not the compiler Even though indentation is ignored by the compiler it is still very important Our goal is not just to produce programs that work but to produce programs that are easy to maintain i.e. that are easy for people to understand

#include <iostream> int main() { int numerator = 0; int denominator = 1; keywords // Get user input std::cout << "Enter the numerator: "; std::cin >> numerator; std::cout << "Enter the denominator: "; std::cin >> denominator; // Compute GCD of numerator and denominator using Euclid's algorithm int a = numerator; int b = denominator; while (a!= b) { if (a > b) { a = a - b; } else { b = b - a; } } strings comments } // Print result std::cout << std::endl << numerator/a << "/" << denominator/a << std::endl; return 0; indentation

And here is the same program with no comments, colours or sensible formatting #include <iostream> int main(){int numerator = 0;int denominator = 1;std::cout << "Enter the numerator: ";std::cin >> numerator;std::cout << "Enter the denominator: ";std::cin >> denominator; int a = numerator;int b = denominator; while (a!= b) {if (a > b) { a = a - b; }else { b = b - a; }}std::cout << std::endl << numerator / a << "/" << denominator / a << std::endl;return 0; } This program does compile and run correctly but is very difficult to read Important note if the above program was submitted as a solution to an assignment it would lose a lot of marks, even though it works There is a lot more to writing a good program than producing something that works

Let's critique the simplify program Major criticisms Very limited application But beware bloat No GUI Bare bones input and output Lack of error handling GCD calculation should be a function

type identifier (name) int age;... age = 23;... age = age + 1; declares a variable of type int stores the value 23 in age this compound statement actually does three things: retrieves the value stored in age (23) calculates the sum of 23 and 1 (24) stores 24 in age

A variable is declared only once Variables must be declared before they are used Variables may be declared in a list Each variable is separated by a comma Variables declared Known as initialization may be assigned a value when

int days = 213; declaration and initialization int hours, minutes, seconds; list of integer variables, separated by commas

Declaring a variable reserves space for the variable s data in main memory A variable can only be declared once Repeating a declaration is an attempt to declare a new variable with the same name Which is illegal Variables with the same name are allowed as long as their scope is different

Variables should be initialized before first being used That is, given sensible starting values This can be done at the same time as they are declared Forgetting to initialize variables can result in unexpected and unwanted results Note that a memory location can never be empty Since it is a sequence of bits

Variables in simplify were declared as type int, and int is a reserved word or keyword Part of the C++ language There are other keywords, many of which we will encounter in this course A text editor designed for writing C++ programs will usually indicate keywords by colour Keywords cannot be used as variable names Fortunately

A token is the smallest unit of a program Tokens include Reserved words: parts of the C++ language Identifiers: names defined by the user Variables Functions Constants Structures Classes

User created names must only contain Letters, both upper and lower case Digits (0 to 9) The underscore character (_) Identifiers must begin with a letter or _ By convention variables usually start with a lower case letter C++ is case sensitive age and age are different identifiers

Identifiers should be descriptive to make programs easier to understand Names should be a reasonable length, and Give information about the identifier's purpose Say we want to store a rectangle's height height, or rect_height, or rectheight are fine ht, or, even worse, a, are not descriptive variablefortheheightofarectangle is too long

cycle A!star (!) int (reserved word) Score (though upper case not recommended for a variable) xc-y (-) race#1 (#) my_variable (but not descriptive) Int (but horrible why?) cmpt130variable (but not descriptive) 3rdVariable (starting 3)

A variable declaration should begin with the type of the variable A variable name should Be legal Only contain a-z, A-Z, 0-9 or _ Not be a reserved word Start with a lower case letter Convey meaning

A variable is a value stored in main memory Main memory = RAM = Random Access Memory Values are encoded in binary A variable is therefore a sequence of binary digits (bits) of a particular length Variables have: A type the kind of data the variable stores A value the data stored in the variable An address the location of the variable

In the example program we saw two types of operations Numeric operations Assignments Sometimes the meaning of an operator may be dependent on the type of the operands e.g. division

C++ uses normal arithmetic operators These can be used wherever it is legal to use a value of the type produced by an expression The result of the operators varies somewhat based on the type of the operands The +, -, and * operations perform addition, subtraction, and multiplication The result of division is determined by type

When both operands are integers the / operator performs integer division The number of times the RHS goes into the LHS 11 / 3 is equal to 3 The % (modulus) operator returns the remainder in integer division 11 % 3 is equal to 2

It is common to add one to (some) variables C++ provides the increment operator, ++ count++; // adds one to count This is typically used with ints but can be used with other numeric types There is also a decrement operator, -- There are two ways to use increment prefix and postfix x++ may have a different result from ++x

The increment operator can be used before or after a variable Before is the prefix version: ++x After is the postfix version: x++ The prefix ++ increments the variable before other operations in the statement The postfix ++ increments the variable after other operations in the statement

The assignment operator, =, is used to assign values to variables The value on the right side is stored in the variable on the left side The bit representation of the left operand is copied to the memory address of the right operand The type of the right operand must be compatible with the left operand More on this later

C++ has shorthand operators that combine assignment and arithmetic count += 2; // count = count+2 cost -= rebate; /* cost = cost rebate */ bonus *= 2; // bonus = bonus*2 time /= speed; /* time = time/speed */ These operators are just typing shorthand They still retrieve the value of the variable, perform the operation and then store the result in it

In a complex expression operations are performed one at a time in order The order is determined by precedence rules Expressions in ()s are evaluated first Then function calls Then normal arithmetic precedence (*,/) then (+,-) Assignment is usually last More complete precedence rules will be provided later in the course

A constant is a special kind of variable Used to represent a value that does not change such as the value of pi Use constants to name values in a program that won t change To avoid magic numbers in a program Numbers whose origin is unclear This makes a program easier to understand and easier to modify

Constants are declared by preceding the variable declaration with the keyword const The constant must be given a value, and cannot be changed in the program By convention constants are written in capitals Assume that there are 10 branches in a program to maintain bank information const int BRANCH_COUNT = 10;

To use a function write the name of the function followed by its arguments The arguments must be in parentheses If there are no arguments the function name must be followed by empty parentheses The arguments must be of the appropriate type Some functions return values And are usually assigned to a variable Or used in a calculation

printf("hello world"); answer = sqrt(7.9); printf has no return value the result of calling sqrt is assigned to answer area = PI * pow(radius, 2); function names function arguments pow executes, and is replaced by its return value

Function calls in statements have precedence over most other operations Such as arithmetic or comparisons A function is executed and its result returned before other operations are performed The function call is replaced by its return value Which may then be used in a calculation

When a function is called program execution switches to the function Each statement in the function is executed in turn until The last line is reached, or A return statement is processed Execution then returns to the line of code where the function was called from The function call is replaced by the return value

It may be helpful to think of a function as a black box That has inputs and produces output through some process input output

Consider this line of code: x = sqrt(y); What is necessary for this to work? x and y must be existing variables sqrt must be a valid function name But that's not all! The sqrt function must Return a value, that is compatible with x's type Require input of a type compatible with y's type

Here is another example x = sqrt(y) + 4; There are a number of steps here The program switches execution to sqrt function Which computes the return value The return value replaces the function call 4 gets added to the result of calling sqrt And the result of the sum is assigned to x

We will use many functions in this course Including ones we have written ourselves When using a function, it must be given the appropriate arguments Arguments are information that the function needs to perform its task They are given to (passed to) the function in the brackets following the function s name

Most programs contain errors Most large working programs contain errors A substantial amount of time is spent finding and fixing errors (known as debugging) We can categorize errors into three very broad types Compilation and Linker errors Run-time errors Logic errors

These errors prevent a program from being compiled Compilers are very picky and complain at the slightest mistake, some common errors are Misspelled words, C++ is case sensitive, so int is different from Int Missing semi-colons, or brackets, or quotes Incorrect arguments for functions You will spend a lot of time looking for errors

Once a program compiles and runs there is still testing (and work) to do Run-time errors cause programs to crash As a result, for example, of input type errors These need to be predicted and handled in some way Logic errors cause programs to return incorrect results And need to be caught by rigorous testing