C++ Basics Part I Part II. Slide 2 Part I: basics.

Slides:



Advertisements
Similar presentations
Variables in C Amir Haider Lecturer.
Advertisements

C++ Basics Variables, Identifiers, Assignments, Input/Output.
Structure of a C program
C Programming Basics Lecture 5 Engineering H192 Winter 2005 Lecture 05
C++ Basics. COMP104 C++ Basics / Slide 2 Introduction to C++ * C++ is a programming language for manipulating numbers and user-defined objects. * C++
© 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5/e Starting Out with C++: Early Objects 5 th Edition Chapter 2 Introduction.
The Fundamentals of C++ Basic programming elements and concepts JPC and JWD © 2002 McGraw-Hill, Inc.
C++ Numerical Data Input/Output Programming. COMP 102 Prog Fundamentals I:C++ Numerical Data, Input/Output /Slide 2 Rules for Division l C++ treats integers.
Chapter 2: Introduction to C++.
Basic Elements of C++ Chapter 2.
Programming Introduction to C++.
CSC 125 Introduction to C++ Programming Chapter 2 Introduction to C++
© Janice Regan, CMPT 128, Jan CMPT 128: Introduction to Computing Science for Engineering Students Data representation and Data Types Variables.
Introduction to C++ Programming Introduction to C++ l C is a programming language developed in the 1970's alongside the UNIX operating system. l C provides.
A Variable is symbolic name that can be given different values. Variables are stored in particular places in the computer ‘s memory. When a variable is.
Copyright 2006 Addison-Wesley Brief Version of Starting Out with C++ Chapter 2 Introduction to C++
Program A computer program (also software, or just a program) is a sequence of instructions written in a sequence to perform a specified task with a computer.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-1 Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
Introduction to C++ // Program description #include directives int main() { constant declarations variable declarations executable statements return.
Data & Data Types & Simple Math Operation 1 Data and Data Type Standard I/O Simple Math operation.
The Fundamentals of C++ Chapter 2: Basic programming elements and concepts JPC and JWD © 2002 McGraw-Hill, Inc. Modified by S. Sudarshan.
C++ Programming: Basic Elements of C++.
Copyright © 2012 Pearson Education, Inc. Chapter 2: Introduction to C++
Introduction to C++ Programming COMP102 Prog. Fundamentals I:Introduction to C++ / Slide 2 Introduction to C++ l C is a programming language developed.
Introduction to C++ Basic Elements of C++. C++ Programming: From Problem Analysis to Program Design, Fourth Edition2 The Basics of a C++ Program Function:
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 2: Introduction to C++
Chapter 3 – Variables and Arithmetic Operations. Variable Rules u Must declare all variable names –List name and type u Keep length to 31 characters –Older.
1 COMS 261 Computer Science I Title: C++ Fundamentals Date: September 9, 2005 Lecture Number: 6.
A Simple Java Program //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { public static void main(String[]
1 Comments Allow prose or commentary to be included in program Importance Programs are read far more often than they are written Programs need to be understood.
C++ Basics Programming. COMP104 Lecture 5 / Slide 2 Introduction to C++ l C is a programming language developed in the 1970s with the UNIX operating system.
Variables in C Topics  Naming Variables  Declaring Variables  Using Variables  The Assignment Statement Reading  Sections
Variables in C Topics  Naming Variables  Declaring Variables  Using Variables  The Assignment Statement Reading  Sections
1 CSC 1111 Introduction to Computing using C++ C++ Basics (Part 1)
CMSC 104, Version 8/061L09VariablesInC.ppt Variables in C Topics Naming Variables Declaring Variables Using Variables The Assignment Statement Reading.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 2 Introduction to C++
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-1 Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
2.1 The Part of a C++ Program. The Parts of a C++ Program // sample C++ program #include using namespace std; int main() { cout
Bill Tucker Austin Community College COSC 1315
Variables, Identifiers, Assignments, Input/Output
Chapter 1.2 Introduction to C++ Programming
Chapter Topics The Basics of a C++ Program Data Types
Chapter 1.2 Introduction to C++ Programming
Chapter 1.2 Introduction to C++ Programming
Basics (Variables, Assignments, I/O)
Chapter 1.2 Introduction to C++ Programming
Chapter 2: Introduction to C++
Programming Introduction to C++.
Basic Elements of C++.
Mr. Shaikh Amjad R. Asst. Prof in Dept. of Computer Sci. Mrs. K. S
Basic Elements of C++ Chapter 2.
2008/10/01: Lecture 8 CMSC 104, Section 0101 John Y. Park
Basics (Variables, Assignments, I/O)
C++ fundamentals Lecture 1, Chapter 2 – pp /22/2018 Y K Choi.
2.1 Parts of a C++ Program.
Variables in C Topics Naming Variables Declaring Variables
C++ Basics.
Variables, Identifiers, Assignments, Input/Output
Variables in C Topics Naming Variables Declaring Variables
COMS 261 Computer Science I
Chapter 2: Introduction to C++.
Programming Introduction to C++.
COMS 261 Computer Science I
Variables in C Topics Naming Variables Declaring Variables
2008/10/01: Lecture 8 CMSC 104, Section 0101 John Y. Park
Variables in C Topics Naming Variables Declaring Variables
Variables in C Topics Naming Variables Declaring Variables
The Fundamentals of C++
Variables in C Topics Naming Variables Declaring Variables
Presentation transcript:

C++ Basics Part I Part II

Slide 2 Part I: basics

Slide 3 C++ C is a programming language developed in the 1970s with the UNIX operating system C is ‘procedural’, and efficient and portable across different hardware platforms C++ is a better C, and C is a subset of C++ C programs should run in C++ C++ supports Data abstraction “object-oriented” programming Generic programming

Slide 4 The first program #include using namespace std; int main(){ cout << “Hi!” << endl; }

Slide 5 Variables and Assignments The most fundamental programming language constructs!

Slide 6 What is a variable? l Name --- identifier l Type --- size A variable (also an object) is a named memory location for a value (that we can write to, retrieve, and manipulate) 1000 X It can be best thought of as a container/box for a value

Slide 7 Variable Declarations Variable declaration syntax: ; Examples: int nickel; int penny; A variable must be declared before it can be used! int main(){ x = 5;// illegal: x was not declared } what is syntax, semantics?

Slide 8 A variable can be initialized in a declaration: int x = 3; Several variables of the same type can be declared in the same declaration (though it is better to put them on separate lines): int height, width; A variable must have only one type. For example, a variable of the type int can only hold integer values.

Slide 9 Basic Data Types Integer data type: int int temperature=32; Real number data type: double double height=1.68; Character data type: char char letter=‘a’; Class matters! Don’t mix up the types!!!

Slide 10 A data type is defined by its operators! For numbers (integers and real numbers are different!) Addition, + Subtraction, - Multiplication, * Division, /

Slide 11 Memory Depiction double y = 12.5; int Temperature = 32; char Letter = 'c'; int Number; 'c' y Temperature Letter Number Memory location Internal data representation: bits, binary numbers

Slide 12 Variable names --Identifiers An identifier is a name for variables, constants, functions, etc. It consists of a letter (including the underscore) followed by any sequence of letters, digits or underscores Names are case-sensitive. The following are unique identifiers: Hello, hello, whoami, whoAMI, WhoAmI Names cannot have special characters in them e.g., X=Y, J-20, #007, etc. are invalid identifiers. C++ keywords cannot be used as identifiers. Choose identifiers that are meaningful and easy to remember.

Slide 13 Keywords (Reserved words) Reserved words have a special meaning in C++. The list of reserved words: asm, auto, bool, break, case, catch, char, class, const, continue, default, delete, do, double, else, enum, extern, float, for, friend, goto, if, include, inline, int, long, namespace, new, operator, private, protected, public, register, return, short, signed, sizeof, static, struct, switch, template, this, throw, try, typedef, union, unsigned, using, virtual, void, volatile, while

Slide 14 Variable initialization A variable can be initialized in a declaration: int x = 3; Always initialize your variables, which are not always automatically initialized!!! Different ways of initialization int x = 3; int x(3);

Slide 15 Assignment Statements Assignment syntax: = ; Examples: int n, m, k;// declaration n = 5; m = 6 + 4; k = n + m; k = k / 2; An assignment gives and changes the value of a variable.

Slide 16 A variable must be assigned a value before it can be used. Variables are not automatically initialized in C++. int x, y;// x declared, but not initialized // x and y have random values y = x;// the random value in x assigned to y Once a value has been placed in a variable, it stays there until the program changes it.

Slide 17 int NewStudents = 6; int OldStudents = 21; int TotalStudents; TotalStudents = NewStudents + OldStudents ;

Slide 18 TotalStudents = NewStudents + OldStudents; OldStudents = TotalStudents;

int Value1 = 10; int Value2 = 20; int Hold = Value1; Value1 = Value2; Value2 = Hold;

Slide 20 Don’t confuse with the (mathematics and English) equal sign =, x = x + 5, x  x + 5

Slide 21 Standard Input/Output Don’t reinvent the wheel! The Standard library is part of the language Standard input/output library: #include cin - the standard input stream Input operator “ >> ” extracts data from input “stream” (the keyboard by default) skips over white spaces extracts only characters of the right form and performs automatic conversion to the type specified

Slide 22 cout - the standard output stream Output operator “ << ” inserts data into the output “stream” (the screen by default) Example: int id, score; cout << "Enter student ID and score: "; cin >> id >> score; cout << "Student ID: " << id << " score: " << score << endl;

Slide 23 //simple program written by the instructor // compute the area of a circle from a given radius #include using namespace std; int main(){ // declaration double Pi = ; // variable declarations double radius; double area; // assignment statements cout << "Enter circle radius: "; cin >> radius; area = Pi * radius * radius; cout << "Area : " << area << endl; return 0; }

Slide 24 Summary l Variables: name and type l 3 basic types: char, int, double l don’t mix up types!!! l Assignment

Slide 25 General form of a C++ program //Program description is first #include directives go next using namespace std; int main(){ constant declarations go here variable declarations go here assignment statements go here Variable declarations Assignment statements return 0; }

Slide 26 Comments Comments (appear in green in Visual C++) Comments are explanatory notes; they are not part of the program. Comments are done in two ways: // A double slash starts a single line comment /* A slash followed by an asterisk marks the start of a multiple line comment. It ends with an asterisk followed by a slash */

Slide 27 Include directive Compiler Directive: #include It refers to a header file of library functions or variables. The compiler reads in the contents of the file before compiling the program. The included file is compiled with the program. There are two forms of #include : #include // for standard files #include "my_lib.h" // for user-defined files

Slide 28 Libraries #include loads the code from the standard libraries #include //I/O library #include // math functions #include // contains random funct using namespace std; indicates that the new C++ libraries should be used. (If this line is left out, then the old iostream library is loaded: #include )

Slide 29 #include a user-defined library: svg.h Scalable Vector Graphics A language for describing 2D graphics in XML that can be viewed by Web browsers Draw lines, rectangles, circles, and texts …

Slide 30 #include using namespace std; #include “svg.h” int main(){ // constant declaration cout << “hi!” << endl; svgout << “text green Arial Hello Again!”; svgout << “line blue”; return 0; }

Slide 31 C++ is a Free-Format Language Extra blanks or tabs are ignored x=3; Blank lines are ignored just like comments Code can be indented in any way More than one statement can be on one line int x, y; x=3; y = 10;int z = x+y; A single statement can be continued over several lines int x = 2; cout << feet << " feet and " << inches << " inches" << endl;

Slide 32 Good Programming Style Place each statement on a line by itself (except long cout statements) x = m/n; Use blank lines to separate sections of code Use the same indentation for all statements in the same block of code {…}. (“Format selection” will automatically fix indentation) int main(){ int x; x = 5; return 0; }

Slide 33 Good Programming Style Use meaningful identifier names double area, sum, radius; Document each variable when it is declared double area; // area of the circle double distance; // distance from top to bottom Document each segment of code // Convert inches to feet feet = inches / in2feet; Document the beginning of the program with a header that tells the purpose of the program // Convert inches to feet and inches

Slide 34 Part II: more technical details Data representation Operator precedence (abusive) Type conversion

Slide 35 How the numbers are represented? Computer uses binary numbers Example: 101 = 1*2^2+0*2^1+1*2^0 A binary digit is a ‘bit’ 8 bits are a ‘byte’, smallest unit We prefer decimal numbers Example: 423 = 4*10^2+2*10^1+3*10^0 Every thing in Computer is finite, unlike in Math!!!

Slide 36 Integer type: int Binary number, hexadecimal, decimal numbers Positive and negative numbers Int has 4 bytes on a 32-bit machine Depends on the compiler, standard ANSI From -2^31 to 2^31-1 Short, int, long, long long Size of short <= size of int <= size of long <= size of long long Signed, unsigned int temperature = 32; Now 64!

Slide 37 Floating-number type: double Scientific notation has two components, 5.16E-02 Mantissa: 5.16 Exponent: -2 IEEE 754 floating-point standard 32 bits float: 1 bit sign, 8 bits exponent, 23 bits mantissa Size of float <= size of double double height = 170.5; float height = 170.5;

Slide 38 Other types int integer (32-bit integer on the PC) (example: 1) short 16-bit integer (allows ±32,767) long 32-bit integer (allows ±2,147,483,647) float floating point number (allows about 7 digits of precision: ) double double precision float (allows about 15 digits of precision: ) char a single character (example: ‘y’) The most important ones: char, int, double!!!

Slide 39 Character type: char A character is internally represented by a ‘number’, one byte can have 256 integers, so 256 characters ASCII encoding Input/Output char a, b, c, d; cin >> a >> b >> c >> d; // user types: 1X3Y // a <- '1', b<-'X', c<-'3', d<-'Y' cout <<a<< " " <<b<< " " <<c<< " " <<d<< endl; // output: 1 X 3 Y char a = ‘a’;

Slide 40 The ASCII Character Set 7-bit encoding for 128 possible characters Some of the 32 non-printing control characters 0 NUL character (end of string character) 7 Bell character (makes beep) 8 Backspace character (\b) 9Tab character (\t) 10 Newline character (\n) space (32) is the first printable ACSII character '0' - '9' have code values 48 through (decimal)  * (binary) for ‘0’ 'A' - 'Z' have code values 65 through 90 'a' - 'z' have code values 97 through 122 See Appendix D in book for full ASCII list

Slide 41 Character string type: string string toto = “we are cool!”; Define operators to assemble ‘char’ into ‘string’ We use a library (don’t need to reinvent the weels, like input/output) #include

Slide 42 Arithmetic Operators Integers Addition + Subtraction - Multiplication * Division / Mod % Note No exponentiation operator Real numbers Addition + Subtraction - Multiplication * Division /

Slide 43 Mod Produces the remainder of the division Examples 5 % 2 evaluates to 1 12 % 4 evaluates to 0 4 % 5 evaluates to 4

Slide 44 It is less standard for ‘negative integers’ -1 % 3 ? 3 % -1 ?

Slide 45 Integer Division Integer division produces an integer result It rounds down the result Examples 3 / 2 evaluates to 1 4 / 6 evaluates to 0 10 / 3 evaluates to 3

Slide 46 Rules for Division C++ treats integers different than doubles. 100 is an int , , and 100. are doubles. The general rule for division of int and double types is: double/double -> double (normal) double/int -> double (normal) int/double -> double (normal) int/int -> int (special case: any decimal places discarded)

Slide 47 Example : 220. / double/double -> double result is / 100 double/int -> double result is / int/double -> double result is / 100 int/int -> int result is 2 Summary: division is normal unless both the numerator and denominator are int, then the result is an int (the decimal places are discarded).

Slide 48 Operators and Precedence Which of the following is it equivalent to mx + b ? (m * x) + b m * (x + b) Operator precedence tells how to evaluate expressions Standard precedence order ( ) Evaluated first, if nested innermost done first * / % Evaluated second. If there are several, then evaluate from left-to-right + - Evaluate third. If there are several, then evaluate from left-to-right

Slide 49 Examples * 3 / * 4 / * 5 % * 3 / 4 (1 + 3) * ((2 + 4 * 6) * 3) / 2 + 2

Slide 50 Implicit type conversion: Forcing a Type Change You can change the type of an expression with a cast operation Syntax: variable1 = type(variable2); variable1 = type(expression); variable1 = (type) variable2; variable1 = (type) expression; Example: int x=1, y=2; double result1 = x/y;// result1 is 0.0 double result2 = double(x)/y;// result2 is 0.5 double result3 = x/double(y);// result3 is 0.5 double result4 = double(x)/double(y);// result4 is 0.5 double result5 = double(x/y);// result5 is 0.0

Slide 51 Implicit type conversion A floating-point expression assigned to an integer object is rounded down An integer expression assigned to a floating-point object is converted to a floating-point value Example 1: double y = 2.7; int i = 15; int j = 10; i = y; // i is now 2 cout << i << endl; y = j; // y is now 10.0 cout << y << endl;

Slide 52 Example : int m, n; double x, y; m = 3; n = 2.5; // 2.5 converted to 2 and assigned to n x = m/n; // 3/2=1 converted to 1.0 and assigned to x n = x+m/2; // m/2=1 : integer division // x+m/2 : double addition because x is double // convert result of m/2 to double (i.e. 1.0) // x+m/2=2.0 // convert result of x+m/2 to int (i.e. 2) //because n is int

Slide 53 Constant Declarations Constants represent permanent values. Their values can only be set in the declaration: const double pi = ; They can make a program more readable and maintainable Constant declaration syntax: const = ; Examples: const double US2HK = 7.8; const double HK2Yuan = 1.07; const double US2Yuan = US2HK* HK2Yuan;