Professor Peter Cheung EEE, Imperial College

Similar documents
Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

6.096 Introduction to C++ January (IAP) 2009

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

2 nd Week Lecture Notes

Chapter 2: Introduction to C++

LECTURE 02 INTRODUCTION TO C++

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

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

EEE145 Computer Programming

Maciej Sobieraj. Lecture 1

A First Program - Greeting.cpp

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

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

UNIT- 3 Introduction to C++

CAMBRIDGE SCHOOL, NOIDA ASSIGNMENT 1, TOPIC: C++ PROGRAMMING CLASS VIII, COMPUTER SCIENCE

Preview from Notesale.co.uk Page 6 of 52

Full file at

Lecture 2 Tao Wang 1

Basics of Java Programming

Visual C# Instructor s Manual Table of Contents

Room 3P16 Telephone: extension ~irjohnson/uqc146s1.html

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

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

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

C: How to Program. Week /Mar/05

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

Computer Programming : C++

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

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

Programming, numerics and optimization

BIT Java Programming. Sem 1 Session 2011/12. Chapter 2 JAVA. basic

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

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

C++ Programming Basics

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

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

Chapter 2 - Introduction to C Programming

Chapter 2: Basic Elements of C++

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

Creating a C++ Program

Programming in C++ 4. The lexical basis of C++

Computer Science II Lecture 1 Introduction and Background

Getting started with Java

COMP 202 Java in one week

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

Programming in C Quick Start! Biostatistics 615 Lecture 4

ANSI C Programming Simple Programs

Recap. ANSI C Reserved Words C++ Multimedia Programming Lecture 2. Erwin M. Bakker Joachim Rijsdam

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Problem Solving With C++ Ninth Edition

3. Simple Types, Variables, and Constants

Objectives. In this chapter, you will:

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics

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

Programming. C++ Basics

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

Programming Fundamentals (CS 302 ) Dr. Ihsan Ullah. Lecturer Department of Computer Science & IT University of Balochistan

1st and 3rd September 2015

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

Full file at

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

CSc Introduction to Computing

Introduction to Computer Programming in Python Dr. William C. Bulko. Data Types

Fundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University

Programming for Engineers Introduction to C

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

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

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

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

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence

+2 Volume II OBJECT TECHNOLOGY OBJECTIVE QUESTIONS R.Sreenivasan SanThome HSS, Chennai-4. Chapter -1

Main Program. C Programming Notes. #include <stdio.h> main() { printf( Hello ); } Comments: /* comment */ //comment. Dr. Karne Towson University

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

Lexical Considerations

ADARSH VIDYA KENDRA NAGERCOIL COMPUTER SCIENCE. Grade: IX C++ PROGRAMMING. Department of Computer Science 1

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

Preview from Notesale.co.uk Page 2 of 79

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

1 Lexical Considerations

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

Tokens, Expressions and Control Structures

CS313D: ADVANCED PROGRAMMING LANGUAGE

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

Getting started with C++ (Part 2)

Introduction to C# Applications

Introduction to Programming using C++

Chapter 2: Data and Expressions

Chapter 1 Introduction to Computers and C++ Programming

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

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

1 Anatomy of a Program 4

5. Control Statements

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

BASIC ELEMENTS OF A COMPUTER PROGRAM

The C++ Language. Arizona State University 1

Topic 2: C++ Programming fundamentals

Introduction to C Programming. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan

Chapter 2. Outline. Simple C++ Programs

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

Transcription:

1/1 1/2 Professor Peter Cheung EEE, Imperial College In this lecture, we take an overview of the course, and briefly review the programming language. The rough guide is not very complete. You should use a suitable book as a proper reference for the language. The aim of this course is to familiarise you with a number of principles, concepts and techniques from computer science. These principles, concepts and techniques are general purpose. They apply whatever programming language you use (Java,, ), and whatever computer you re using (a PC, a Unix system, a Mac). Once you know basic engineering principles, concepts and techniques you ll find it easy to pick up new programming languages, new operating systems, etc. 1/3 1/4 You could get away with nothing. But a good textbook would help, such as: Problem Solving with, 5 th Edition, Walter Savitch, Addison Wesley, ISBN: 0321269756, 2004 ( 40.84). You can also get a full Tutorial free on the web at: http://www.functionx.com/cppbcb/ If you are serious about learning really how to programme well, then the following book (language independent) is a must: Code Complete, Steve McConnell, Microsoft Press, ISBN: 0735619670 ( 25.84). The principles you will learn include things like how to construct code that s easy to read, understand and modify. The concepts you will learn about include things like abstract data types, object-oriented programming, and so on. The techniques you will learn about include how to build data structures, like lists and trees, and algorithms for certain common tasks, like lookup and sorting.

1/5 1/6 But general-purpose programming principles, concepts and techniques can only be acquired by doing lots of programming. Programming is like riding a bike it can t be learned from a book, it requires lots of practise. So we have to learn via a particular programming language on a particular machine. On this course we use using Borland Builder (BCB). The language is an object-oriented variant of the C language. Object-oriented means that code and data can be bundled together into a single entity called an object. Classes of objects are organised into hierarchies. More on this later in the course. But Borland Builder (BCB) is not just a programming language. It s a whole development environment (IDE). It includes an editor and a debugger, as well as a compiler. BCB is also a visual development environment. It supplies lots of support for building the graphical user interface (GUI) of a program. It contains a Visual Library (VCL) which helps you to write visual programmes. 1/7 1/8 The course will touch on each of the following topics. A review of Software engineering principles Data structures Lists Ordered lists Trees Ordered trees Hash tables is a programming language. It is a block structured, strongly typed, procedural language. It s a lot like C or or Java, but arguably more flexible and more widely used than others. Parsing Object-orientation

1/9 1/10 Block structured means that the flow of control in a program is strictly mediated by a small number of constructs, namely sequences of statements, conditional statements (e.g. if (<condition>) then <statements> else <statement>), and loops (e.g. while condition <statement>). Here is a skeleton program in. (This is a console program. It doesn t use the fancy user interface features of BCB.) This include statement specifies the header file iostream.h to be used. It defines standard i/o cin and cout. #include <iostream.h> int main() Strongly typed means that the programmer has to declare the type of each variable used in the program, ie: whether it is an integer, a string, an array, or whatever. Procedural means that the program specifies a series of instructions and the order in which they are to be carried out. In a declarative language, by contrast, the programmer only describes the meanings of things functions or predicates and leaves it to the computer to work out the details of how computations are to be performed. Prolog is an example of a declarative language. All programs with a line of this form. It always starts with main(). All statements are terminated by a semicolon. When exit, the main programme returns a value 0 to signify no error has occurred. cout << Hello, World! ; cout << endl; getchar(); return 0; 1/11 1/12 Comments are placed between braces: This is a comment The older notation: (* This is a comment *) Comments are placed between /* and */ /* This is a comment */ The second method: a comment is placed after //. Then it extends to the end of the line: x = x+1; // A comment to the end of the line. PASCAL IS CASE-BLIND. Names can use letters and digits but must with a letter, e.g.: is case-sensitive. Names can use letters, digits and the underscore character, but must with a letter or the underscore, e.g.: amount, x1, str3a amount, x1_, _str3a Extracts from and Side by Side, Maria Litvin. (http://www.skylit.com/pascpp/)

1/13 1/14 A compound statement is placed between and end: <statement1> ; <statement2> Semicolon is optional before end and is usually required after end, unless followed by another end. A compound statement is placed between braces: <statement1> ; <statement2> ; Semicolon is required before the closing brace, and usually omitted after it. char integer real boolean type Color = (Red, Green, Blue); char int long short float double long double char, int, short, and long may be preceded by the unsigned keyword. double is a double-precision real number. bool is in the process of becoming standard. enum Color Red, Green, Blue; 1/15 1/16 All declarations of constants in the main program or in a procedure or a function are grouped together under the keyword const: const Pi = 3.14; Rate = 0.05;.05 not allowed Hour = 3600; Dollar = '$'; Greeting = 'Hello, World!'; There are no "escape" characters. Two single quotes in a row in a literal string represent one single quote character: writeln ('Let''s have fun!'); Declarations of constants are the same as declarations of variables with initialization, but they are preceded by the keyword const: const double Pi = 3.14, Rate =.05; // or 0.05; const int Hour = 3600; const char Dollar = '$'; const char Greeting[] = "Hello, World!"; // Also allowed: const double R = 5., Pi = 3.14, Area = Pi * R * R; recognizes so-called "escape characters" for special char constants. These are written as a backslash (which serves as the "escape" character) followed by some mnemonic char. For example '\n' newline '\'' single quote '\\' backslash '\"' double quote '\a' alarm (bell) '\f' form feed '\t' tab '\r' carriage return Character constants with escape chars are used the same way as regular char constants. For example: const char CR = '\r'; // Carriage Return cout << "Hello, World\n"; All declarations of variables in the main program or in a procedure or a function are grouped together under the keyword var: SomeProcedure (); var r : real; i, j : integer; star : char; match : boolean; No initialization is allowed in declarations. Declarations of variables (or constants) may be placed more or less anywhere in the code, before they are used. Beginners are advised to place them at the top of main() or at the top of a function to avoid complications with the scope rules. Global variables, declared outside any function (and outside main()), are allowed, but should be avoided. Values of variables may be initialized to constants or previously defined variables or expressions: SomeFunction () double r = 5.; int i = 0, j = i+1; char star = '*';

1/17 1/18 var str : packed array [1..80] of char; grid : array [1..32, 1..25] of integer; The packed keyword is recommended for an array of characters to save space. The range of subscripts can start from any number, but usually starts from 1. Here str[1] refers to the first element of the array str. compilers normally report an error if a subscript value is out of range. char str[80]; int grid[32][25]; The subscript for the first element of the array is 0. Here str[0] refers to the first element of the array str and str[79] to the last element. compilers do not verify that a subscript value is within the legal range. Arrays can be initialized in declarations. For example: int fibonaccinumbers[6] = 1,1,2,3,5,8; char phrase[80] = "Hello, World!"; The type keyword is used to define enumerated and subrange types, array types, and records: type DigitType = 0..9; Subrange type ColorType = (Red, Green, Blue); Enumerated type WordType = packed array [1..30] of char; Array type The typedef keyword is used to define aliases for built-in (and, if desired, user-defined) types: // Used later in declarations as: typedef unsigned char BYTE; // BYTE pixel; typedef double MONEY; // MONEY price = 9.95; typedef int BOARD[8][8]; // BOARD board; 1/19 1/20 Procedures and functions take arguments of specified types. Procedures do not explicitly return a value. Functions return a value of the specified type. procedure DoSomething (arg1 : integer; arg2 : char); ****************************************************** function ComputeSomething (arg1, arg2 : integer) : real; ComputeSomething := <expression>; The return value in a function is indicated by using the assignment statement. There are no procedures, everything is a function. Functions take arguments of specified types and return a value of the specified type. Functions that do not explicitly return a value are designated as void functions. void DoSomething (int arg1, char arg2) Functions of the type other than void return a value of the specified type. The return value is indicated by using the return statement. double ComputeSomething (int arg1, int arg2) return <expression>; A function can have multiple return statements. A void function can have return statements without any value to return. if ( <condition)> ) return; PYKC This Jan is 2006 used to quit early and return to the calling statement.

1/21 1/22 The var keyword is used (passing parameter by reference), or without var (passing parameter by value) : procedure Swap (var x, y : integer); procedure QuadraticEquation (a, b, c : real; var x1, x2 : real); The & symbol is used: void Swap (int &x, int &y); void QuadraticEquation (double a, double b, double c, double &x1, double &x2); := (assignment) + * / ("real" division) div ("integer" division) mod (modulo division) Arithmetic operations are allowed only for integer and real operands. div and mod are used only with integer operands. No arithmetic operation are allowed for variables of the char or boolean types. The result of an arithmetic operation has integer type when both operands have integer type and real when at least one of the operands is real. The "real" division / is an exception: the result is always a real value, even if operands are integers. The result of div is the quotient truncated to an integer (in the direction of 0). Examples: var x : real; n : integer; x := 2 / 3; x gets the value of 0.666667 n := 2 div 3; n gets the value of 0 1/23 1/24 = (assignment) + * / % ( modulo division). Arithmetic operations are allowed for all built-in types, including char, although % makes sense only for integral types (char, int, long, short, etc.). char operands use the actual binary value stored in that byte and have a range from 127 to 127. They are first automatically converted to int in arithmetic operations. The intermediate type of the result is always the same as the type of the operands. If the operands have different types, the "shorter" operand is first promoted to the type of the "longer" operand (e.g. int may be promoted to long; or long to double). Examples: double x; x = 2. / 3; // x gets the value of 0.666667 x = 2 / 3; // x gets the value of 0 (!!!) No such thing. The compound arithmetic operators are very much a part of the style and are widely used. // Is the same as: a++; // a = a + 1; b = a++; // b = a; a = a + 1; b = ++a; // a = a + 1; b = a; a ; // a = a 1; Also: a; a += b; // a = a + b; Also: a =b; a *= b; a /= b; a %= b;

1/25 1/26 Built-in functions: abs(x) sqrt(x) sin(x) cos(x) exp(x) ln(x) sqr(x) arctan(x) Standard library functions (require #include <math.h>): int abs(int x); double fabs(double x); double sqrt(double x); double sin(double x); double cos(double x); double exp(double x); double log(double x); // Natural logarithm double pow(double base, double exponent); double atan(double x); Has built-in boolean type and constants true and false. The result of relational operators has the type boolean. = <> < <= > >= Any integer non-zero value is treated as "true," and zero as "false." bool type is in the process of becoming standard. If not supported by their compiler, programmers may use their own definition. For example: typedef int bool; #define false 0 #define true 1 The result has the type bool and has the value false or true: ==!= < <= > >= 1/27 1/28 and or not Example: function LeapYear(yr : integer) : boolean; LeapYear := ((yr mod 4 = 0) and ((yr mod 100 <> 0) or (yr mod 400 = 0))); &&! Example: bool LeapYear (int yr) return (yr % 4 == 0 && (yr % 100!= 0 yr % 400 == 0)); PYKC Jan 2006 Use Level 3 computer lab or install a copy of BCB on your own machine. Complete Lesson 1 & Lesson 2 of the following Tutorial on the web: http://www.functionx.com/cppbcb/lesson01.htm http://www.functionx.com/cppbcb/lesson02.htm