cs201 introduction to sabancı university 1 chapter 2 writing and understanding c++ l writing...

21
CS201 Introduction to Computing @ Sabancı University 1 Chapter 2 Writing and Understanding C++ Writing programs in any language requires understanding the syntax and semantics of the programming language Syntax is similar to rules of spelling and grammar: After main() you should put { Semantics is what a program means Approaches of learning programming languages Template based Examine example programs and make analogies Like a child learns how to speak First learn syntax and semantics, then start by writing small programs, ... Like learning a foreign language Which one do you prefer? We will follow the second method

Upload: derek-barton

Post on 18-Jan-2018

216 views

Category:

Documents


0 download

DESCRIPTION

CS201 Introduction to Sabancı University 3 Anatomy of a C++ Program #include statements make libraries of classes and functions accessible to the program ä Utility functions and tools that make the programmer’s life easier are defined in libraries ä Helps programmers develop code independently in a standard way ä Compiler needs access to interface, what the functions look like, but not to implementation of those functions This is in the #include d file ex. #include for input/output functions  all programs that use standard C++ libraries should have using namespace std;

TRANSCRIPT

Page 1: CS201 Introduction to Sabancı University 1 Chapter 2 Writing and Understanding C++ l Writing programs in any language requires understanding

CS201 Introduction to Computing @ Sabancı University 1

Chapter 2Writing and Understanding C++

Writing programs in any language requires understanding the syntax and semantics of the programming language Syntax is similar to rules of spelling and grammar:

• After main() you should put { Semantics is what a program means

Approaches of learning programming languages Template based

• Examine example programs and make analogies• Like a child learns how to speak

First learn syntax and semantics, then start by writing small programs, ...• Like learning a foreign language

Which one do you prefer? We will follow the second method

Page 2: CS201 Introduction to Sabancı University 1 Chapter 2 Writing and Understanding C++ l Writing programs in any language requires understanding

CS201 Introduction to Computing @ Sabancı University 2

Towards Understanding of C++ “Hello World” program. No biggie!

#include <iostream>using namespace std;

// traditional first program

int main(){

cout << "Hello world" << endl; /* display */return 0;

} This program must be

typed compiled (hello.cpp => hello.obj) linked (Build) (hello.obj and any other object modules linked

together => project.exe) executed

Page 3: CS201 Introduction to Sabancı University 1 Chapter 2 Writing and Understanding C++ l Writing programs in any language requires understanding

CS201 Introduction to Computing @ Sabancı University 3

Anatomy of a C++ Program #include statements make libraries of classes and

functions accessible to the program Utility functions and tools that make the programmer’s

life easier are defined in libraries Helps programmers develop code independently in a

standard way Compiler needs access to interface, what the functions

look like, but not to implementation of those functions• This is in the #included file • ex. #include <iostream> for input/output functions

all programs that use standard C++ libraries should have using namespace std;

Page 4: CS201 Introduction to Sabancı University 1 Chapter 2 Writing and Understanding C++ l Writing programs in any language requires understanding

CS201 Introduction to Computing @ Sabancı University 4

Anatomy of a C++ Program Comments make programs readable by humans (and by

assistants!) Easier maintenance Try to use natural language, do not repeat the code!

• Bad examplearea = pi*r*r; /* area is pi*r*r */

• Better examplearea = pi*r*r; /* calculate area */

• Using “//” make the line comment line• Between /* and */

Compiler disregards comments

Comments in your homework affect your grades

In VC++, comments are in green

Page 5: CS201 Introduction to Sabancı University 1 Chapter 2 Writing and Understanding C++ l Writing programs in any language requires understanding

CS201 Introduction to Computing @ Sabancı University 5

Anatomy of a C++ Program Execution of the program begins with main Each program must have a main function Execution of C++ programs is organized as a sequence of

statements Unless otherwise stated, statements execute

sequentially one after another• Branching, repetition are possible (we will see them later)

The main function returns a value to the operating system or environment• return 0• Why 0? Because 0 means no problem encountered!

Page 6: CS201 Introduction to Sabancı University 1 Chapter 2 Writing and Understanding C++ l Writing programs in any language requires understanding

CS201 Introduction to Computing @ Sabancı University 6

Rules Rules Rules Now some syntax rules and definitions ABC of C++ What is an “identifier”? Reserved words Symbols and compound symbols What is a “literal”?

Types of literals Variables and basic types Where to use blanks, line breaks? Where to use semicolon? Basic Input/Output

Page 7: CS201 Introduction to Sabancı University 1 Chapter 2 Writing and Understanding C++ l Writing programs in any language requires understanding

CS201 Introduction to Computing @ Sabancı University 7

Identifiers Names of elements in a program

Names of variables, functions, classes, etc. Sequence of letters (a .. z, A ..Z), digits (0 ..9) underscore _ Cannot start with a digit

number1 validnumber_1 validMe_myself valid1number not valid

Do not start with an underscore Case sensitive

Number1 and number1 are not the same Pick meaningful names in the context of your program and improve the

self-readability of the code (do not use your boy/girlfriend’s name!) First occurrence of an identifier must be its declaration

Standard declarations are in #include files We will see how to declare user-defined variables, functions, etc. as

time goes by

Page 8: CS201 Introduction to Sabancı University 1 Chapter 2 Writing and Understanding C++ l Writing programs in any language requires understanding

CS201 Introduction to Computing @ Sabancı University 8

Reserved Words (Keywords) Special and fixed meanings

built-in in C++ language no need to have libraries, etc.

Cannot be changed by programmer int return Full list is Table 2.1 of the textbook

You cannot use a reserved word for a user-defined identifier

In MS VC++, reserved words are automatically blue

Page 9: CS201 Introduction to Sabancı University 1 Chapter 2 Writing and Understanding C++ l Writing programs in any language requires understanding

CS201 Introduction to Computing @ Sabancı University 9

Symbols Non-digit and non-letter characters with special meanings Mostly used as operators (some examples are below, full list later)

+ addition, sign- subtraction, minus= assignment/ division* multiplication% modulus

Compound symbols (two consecutive symbols – one meaning), examples below, full list later/**/<<>>== equality comparison

Page 10: CS201 Introduction to Sabancı University 1 Chapter 2 Writing and Understanding C++ l Writing programs in any language requires understanding

CS201 Introduction to Computing @ Sabancı University 10

Literals Fixed values Different types

Integer3 454 -43 +343

Real3.1415 +45.44 -54.6 1.2334e3Last one is 1.2334 times 10 to the power 3 (scientific notation)

String• Sequences of characters• Within double quotes (quotes are not part of the string)• Almost any characters is ok (letters, digits, symbols)"Hello my friend" "10 is bigger" "10 > 22 ?"

Page 11: CS201 Introduction to Sabancı University 1 Chapter 2 Writing and Understanding C++ l Writing programs in any language requires understanding

CS201 Introduction to Computing @ Sabancı University 11

Variables and types Variables are used to store data that can change during program

Memory locations of certain sizes Data input must be stored in a variable Results are stored in variables generally defined at the beginning of functions (no strict rule on the place

of definition except being before the first use) Basic types (more to follow)

Integerint list of identifiers separated by comma ;int number1, age, deniz;

Realfloat list of identifiers separated by comma ;float area, circumference;• There is another real type called double

that we will see later String

string list of identifiers separated by comma ;string myname;

number1 age

Memory

deniz

area

circumference

myname

Page 12: CS201 Introduction to Sabancı University 1 Chapter 2 Writing and Understanding C++ l Writing programs in any language requires understanding

CS201 Introduction to Computing @ Sabancı University 12

Arithmetic Operations Operators: * - + / % Operands: values that operator combines

variables or literals Combination of operators and operands is called expression Syntax and semantics for arithmetic operations

Addition, subtraction: + and –, for int, real (float and double)

23 + 4 x + y d – 14.0 + 23 5 - 3 + 2 Multiplication: *, for int, real (float and double) 23 * 4 y * 3.0 d * 23.1 * 4 5 – 3 * 2 Division: /, different for int and real number types (double, float)• for int operands result is the integer part of division

21 / 4 is 5 21 / 4.0 is 5.25 x / y Modulus: %, remainder of division, only for int 21 % 4 is 1 18 % 2 is 0 x % y

-1

4

Page 13: CS201 Introduction to Sabancı University 1 Chapter 2 Writing and Understanding C++ l Writing programs in any language requires understanding

CS201 Introduction to Computing @ Sabancı University 13

Assignment Operator

variable = expresion To store a new value in a variable The value of expression becomes

the value of variable Previous value of variable is lost

int a, b;a = 45;b = a+54;a*b = 332; wrong syntax

Be careful about the types of left and right hand sides they must match compiler may or may not warn you

Memory

a

45

name

value

b

99

Page 14: CS201 Introduction to Sabancı University 1 Chapter 2 Writing and Understanding C++ l Writing programs in any language requires understanding

CS201 Introduction to Computing @ Sabancı University 14

Example Program Write a program to calculate the area of a circle

program first input a name and print a greeting input the radius calculate and display area

identify literals, identifiers, symbols, variables and expressions in this program

#include <iostream>#include <string>using namespace std;

// area calculation program

int main(){

int radius;float area;string myname;cout << "Please enter your name: ";

cin >> myname;cout << "Hello " << myname << "! Welcome to my area calculation program" << endl;cout << "Please enter the radius of your circle: ";cin >> radius;area = 3.14*radius*radius;cout << "the area is: " << area << endl;

return 0;}

Page 15: CS201 Introduction to Sabancı University 1 Chapter 2 Writing and Understanding C++ l Writing programs in any language requires understanding

CS201 Introduction to Computing @ Sabancı University 15

Issues What happens if the user enters a real number for radius?

wrong result solution: real radius

Can we combinecout << "Hello " << myname << "! Welcome to my area calculation program" << endl;cout << "Please enter the radius of your circle: ";

Yes Can we eliminate the variable area?

Yes

Page 16: CS201 Introduction to Sabancı University 1 Chapter 2 Writing and Understanding C++ l Writing programs in any language requires understanding

CS201 Introduction to Computing @ Sabancı University 16

Where to use Blanks You must have at least one blank

between two words (identifiers or keywords) between a word and numeric literal

You cannot have a blank within a word within a compound symbol within a literal

• except string literals, in string literals blanks are blanks At all other places

blanks are optional Several blanks are functionally same as single blank

except within string literals

Page 17: CS201 Introduction to Sabancı University 1 Chapter 2 Writing and Understanding C++ l Writing programs in any language requires understanding

CS201 Introduction to Computing @ Sabancı University 17

Where to use Line Breaks and Semicolon As a general rule, line breaks are possible whenever blank is

possible exception: a string literal must start and finish on the

same line Where to use a semicolon?

general rule: at the end of a statement but there are exceptions

• variable declaration: variable declaration is not a statement but you have to use semicolon at the end of each declaration

it may be hard to identify the statements• is #include <iostream> a statement?

an ability that will be gained over time

Page 18: CS201 Introduction to Sabancı University 1 Chapter 2 Writing and Understanding C++ l Writing programs in any language requires understanding

CS201 Introduction to Computing @ Sabancı University 18

Stream output Output is an essential part of our programs cout is the standard output stream (monitor), Accessible via #include<iostream> Objects are inserted onto stream with insertion operator <<

Objects are literals, variables or expressions expressions are evaluated before output whatever exists within a string literal between " " are displayed

Different objects separated by insertion operator <<cout << "yadda yadda" << endl << "yadda" << endl;cout << "gross = " << 12*12 << endl;cout << 5 << " in. = "; cout << 5*2.54 << " cm. " << endl; endl means “end of line” (defined in iostream)

it causes the next output displayed at the beginning of the next line Line breaks in the program do not finish the output line in the

output screen

yadda yaddayaddagross = 1445 in. = 12.7 cm.

Page 19: CS201 Introduction to Sabancı University 1 Chapter 2 Writing and Understanding C++ l Writing programs in any language requires understanding

CS201 Introduction to Computing @ Sabancı University 19

Stream Input cin

standard input stream (from keyboard) you can input only into variables extraction operator >> is used between cin and variablescin >> variable1 >> variable2 >> variable3 .......... ;

int a, b, anynum;

cin >> b >> anynum >> a;

Data entry must be in the same order of variables in cin statement first the value for b, then the value for anynum, then the value

of a must be entered by the user using the keyboard

Page 20: CS201 Introduction to Sabancı University 1 Chapter 2 Writing and Understanding C++ l Writing programs in any language requires understanding

CS201 Introduction to Computing @ Sabancı University 20

Stream Input You have to have at least one blank between any two input

entry Multiple blanks are OK

You may input values at several lines for a single cin statement

You cannot display something using cin statement

Important note on terminology “reading a value” means such an input

Page 21: CS201 Introduction to Sabancı University 1 Chapter 2 Writing and Understanding C++ l Writing programs in any language requires understanding

CS201 Introduction to Computing @ Sabancı University 21

Stream Input – Example showing the operation