Copyright 2001 Oxford Consulting, Ltd1 January 2001 - 1 - Building Blocks Overview In this lesson We will study the basic building blocks of a C++ program.

Slides:



Advertisements
Similar presentations
Variables in C Amir Haider Lecturer.
Advertisements

Data Types in Java Data is the information that a program has to work with. Data is of different types. The type of a piece of data tells Java what can.
1 9/10/07CS150 Introduction to Computer Science 1 Data Types Section 2.7 – 2.12 CS 150 Introduction to Computer Science I.
© 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.
1 9/20/06CS150 Introduction to Computer Science 1 Review: Exam 1.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 2: Introduction to C++ Starting Out with C++ Early Objects Sixth.
1 Chapter 2 C++ Syntax and Semantics, and the Program Development Process Dale/Weems/Headington.
Data types and variables
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 27, 2005.
Chapter 2 Data Types, Declarations, and Displays
Chapter 2: Introduction to C++.
Basic Elements of C++ Chapter 2.
Chapter 2 Data Types, Declarations, and Displays.
Objectives You should be able to describe: Data Types
 2003 Prentice Hall, Inc. All rights reserved. 1 Introduction to C++ Programming Outline Introduction to C++ Programming A Simple Program: Printing a.
CSC 125 Introduction to C++ Programming Chapter 2 Introduction to C++
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 2: Introduction to C++ Starting Out with C++ Early Objects Seventh.
 Value, Variable and Data Type  Type Conversion  Arithmetic Expression Evaluation  Scope of variable.
Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)
Operator Precedence First the contents of all parentheses are evaluated beginning with the innermost set of parenthesis. Second all multiplications, divisions,
Copyright 2006 Addison-Wesley Brief Version of Starting Out with C++ Chapter 2 Introduction to C++
Numeric Types, Expressions, and Output ROBERT REAVES.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-1 Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
CPS120: Introduction to Computer Science
1 C++ Syntax and Semantics, and the Program Development Process.
Week 1 Algorithmization and Programming Languages.
C++ Programming: Basic Elements of C++.
Knowledge Base C++ #include using std namespace; int main(){} return 0 ; cout
Copyright © 2012 Pearson Education, Inc. Chapter 2: Introduction to C++
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++
1 Chapter 2 C++ Syntax and Semantics, and the Program Development Process.
A first program 1. #include 2. using namespace std; 3. int main() { 4. cout
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 2: Introduction to C++ Starting Out with C++ Early Objects Sixth.
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.
Introducing C++ Programming Lecture 3 Dr. Hebbat Allah A. Elwishy Computer & IS Assistant Professor
Chapter 2 Variables.
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 2: Introduction to C++ Starting Out with C++ Early Objects.
Computing and Statistical Data Analysis Lecture 2 Glen Cowan RHUL Physics Computing and Statistical Data Analysis Variables, types: int, float, double,
COIT29222 Structured Programming 1 COIT29222-Structured Programming Lecture Week 02  Reading: Textbook(4 th Ed.), Chapter 2 Textbook (6 th Ed.), Chapters.
1 Chapter 2 C++ Syntax and Semantics, and the Program Development Process Programming in C++
CHAPTER 2 PROBLEM SOLVING USING C++ 1 C++ Programming PEG200/Saidatul Rahah.
C++ for Engineers and Scientists Second Edition
Variables in C Topics  Naming Variables  Declaring Variables  Using Variables  The Assignment Statement Reading  Sections
CS 106 Introduction to Computer Science I 09 / 10 / 2007 Instructor: Michael Eckmann.
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++
Java-02 Basic Concepts Review concepts and examine how java handles them.
CS0007: Introduction to Computer Programming Primitive Data Types and Arithmetic Operations.
1Object-Oriented Program Development Using C++ Built-in Data Types Data type –Range of values –Set of operations on those values Literal: refers to acceptable.
Chapter 2 Variables and Constants. Objectives Explain the different integer variable types used in C++. Declare, name, and initialize variables. Use character.
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
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 2: Introduction to C++
Bill Tucker Austin Community College COSC 1315
Chapter # 2 Part 2 Programs And data
Chapter Topics The Basics of a C++ Program Data Types
Chapter 2: Introduction to C++
BASIC ELEMENTS OF A COMPUTER PROGRAM
Basic Elements of C++.
Multiple variables can be created in one declaration
Chapter 2: Introduction to C++
Basic Elements of C++ Chapter 2.
2.1 Parts of a C++ Program.
Introduction to C++ Programming
Chapter 2 Variables.
Chapter # 2 Part 2 Programs And data
Expressions and Assignment
Chapter 2: Introduction to C++.
Primitive Types and Expressions
Presentation transcript:

Copyright 2001 Oxford Consulting, Ltd1 January Building Blocks Overview In this lesson We will study the basic building blocks of a C++ program Explore data types that are part of the C++ language Look at basic arithmetic operators Begin our study of functions We will write some functions To use data the user can enter into our program Return computed results

Copyright 2001 Oxford Consulting, Ltd1 January Building Blocks Fundamental Data Identifiers in C++ The name of object or function in C++ is called an identifier Gives us means to refer to an entity in program Such an entity may be a  Variable  Function

Copyright 2001 Oxford Consulting, Ltd1 January Building Blocks Identifiers Any combination of symbols can be used as an identifier, but…. The C++ standard establishes some restrictions  An identifier is case-sensitive  The first character of an identifier must be an alphabetic character or an underscore  Identifiers cannot be a C++ keyword  Identifiers have no length limit  An identifier is case-sensitive  The first character of an identifier must be an alphabetic character or an underscore  Identifiers cannot be a C++ keyword  Identifiers have no length limit

Copyright 2001 Oxford Consulting, Ltd1 January Building Blocks Identifiers Simple Variables A variable is an object we use to hold data; it’s also an identifier It has a name The name let’s us refer to it in our program It has a type Tells us how big the variable is Types are kind of like barrels We have a number of different types or sizes of barrels 1, 2, 5, 10, 50 gallon containers Should be immediately obvious Putting contents of a 50 gal barrel into a 1 gal barrel is problem

Copyright 2001 Oxford Consulting, Ltd1 January Building Blocks Identifiers Intrinsic Types Look around real world and we see we have a number of different units we measure by…. –Inches, feet, yards, miles –Centimeters, meters, kilometers –Gram, kilograms, etc. These are standards; They are intrinsic units of measure

Copyright 2001 Oxford Consulting, Ltd1 January Building Blocks Identifiers Intrinsic Types C++ does same thing…just not with barrels We have number of standard numeric types to hold stuff These are predefined variables of different sizes Such numeric types are called the intrinsic types, The intrinsic types are classified into two groups Integer Types Floating Point Types

Copyright 2001 Oxford Consulting, Ltd1 January Building Blocks Identifiers Integer Types Integer types are whole numbers ….They have no fractional part 25, -6, 100, 83, -972…. The C++ language standard defines the following integer types char short int long bool char short int long bool

Copyright 2001 Oxford Consulting, Ltd1 January Building Blocks Identifiers Integer Types May be signed or unsigned … By default all are signed except bool A signed integer can be either positive or negative –Unsigned integer can only be positive Signed Integers signed int aNumber = -25; or int aNumber = -25; Unsigned Integers unsigned int aNumber = 15;

Copyright 2001 Oxford Consulting, Ltd1 January Building Blocks Identifiers char Integer Type We represent characters by assigning a value to a char char x = ‘A’;// Preferred char y = 65;// Assigning numeric ASCII value We denote a char type by enclosing a character in single quotes This line of code will display the letter M on the screen. cout << 'M' << endl;

Copyright 2001 Oxford Consulting, Ltd1 January Building Blocks When I Say 0…. There is difference between 0 and '0' 0 is integer zero…that is, all bits are 0 A char integer with a value of zero is often referred to as a null character On the other hand the ASCII '0' has a value of 48

Copyright 2001 Oxford Consulting, Ltd1 January Building Blocks Identifiers bool Integer Type bool integer type can contain only two values….. zero (false) or one (true) To express conditions for success or failure of some test We might write bool pass = true; bool fail = false;

Copyright 2001 Oxford Consulting, Ltd1 January Building Blocks How Big is Big…The Size of Integer Types Each of the integer types requires different amount of memory to store its value The smaller the size of the variable …..Fewer bits allocated to store it …..Smaller the value it can hold Sizes of integer types varies by computer and operating system

Copyright 2001 Oxford Consulting, Ltd1 January Building Blocks How Big is Big…The Size of Integer Types #include using namespace std; int main(void) { // checking sizes cout << "A char is " << sizeof(char) << " byte" << endl; cout << "A short is " << sizeof(short) << " bytes " << endl; cout << "A int is " << sizeof(int) << " bytes" << endl; cout << "A long is " << sizeof(long) << " bytes" << endl; cout << "A bool is " << sizeof(bool) << " byte" << endl; return 0; } #include using namespace std; int main(void) { // checking sizes cout << "A char is " << sizeof(char) << " byte" << endl; cout << "A short is " << sizeof(short) << " bytes " << endl; cout << "A int is " << sizeof(int) << " bytes" << endl; cout << "A long is " << sizeof(long) << " bytes" << endl; cout << "A bool is " << sizeof(bool) << " byte" << endl; return 0; } A char is 1 byte A short is 2 bytes A int is 4 bytes A long is 4 bytes

Copyright 2001 Oxford Consulting, Ltd1 January Building Blocks How Big is Big…The Size of Integer Types #include using namespace std; int main(void) { cout << CHAR_MAX << endl; //displays char maximum cout << CHAR_MIN << endl; //displays char minimum cout << SHRT_MAX << endl; //displays short maximum cout << SHRT_MIN << endl; //displays short minimum cout << INT_MAX << endl //displays int maximum cout << INT_MIN << endl;//displays int minimum cout << LONG_MAX << endl; //displays long maximum cout << LONG_MIN << endl; //displays long minimum return 0; } #include using namespace std; int main(void) { cout << CHAR_MAX << endl; //displays char maximum cout << CHAR_MIN << endl; //displays char minimum cout << SHRT_MAX << endl; //displays short maximum cout << SHRT_MIN << endl; //displays short minimum cout << INT_MAX << endl //displays int maximum cout << INT_MIN << endl;//displays int minimum cout << LONG_MAX << endl; //displays long maximum cout << LONG_MIN << endl; //displays long minimum return 0; }

Copyright 2001 Oxford Consulting, Ltd1 January Building Blocks Floating Point Types With an integer type, the size of number we can express is determined by number of bits in integer Early PCs had integers containing 16 bits which meant that the largest integer number that could be expressed was 65,536 Clearly we need to represent large numbers in a computer…....Have to keep track of national debt after all To do so we use different data type called floating point type

Copyright 2001 Oxford Consulting, Ltd1 January Building Blocks Floating Point Types Consider the number 3500…. We can easily rewrite this as 0.35 x Next we rewrite as 10*10*10*10 or 10 4 Thus the original number becomes 0.35 x 10 4 We call the 0.35 the fractional part or mantissa and The 10 4 the exponent part When number expressed in such a format, we say we’re using a floating-point format

Copyright 2001 Oxford Consulting, Ltd1 January Building Blocks Floating Point Types C++ language standard specifies two floating-point types float double Each of these types contains the same maximum exponent Double has more significant figures to the right of the decimal point –There is even a long double -

Copyright 2001 Oxford Consulting, Ltd1 January Building Blocks Floating Point Types Floating-point constants by default are of size double. If we write float pi = ; We get truncation warning We can avoid the warning by directing the compiler to create as a float and not a double. float pi = f; or float pi = F;

Copyright 2001 Oxford Consulting, Ltd1 January Building Blocks The const Qualifier Consider the two declarations and initializing values…. int legalPaperLength = 17; int standardPaperLength = 11; Now let these two variables be assigned alternate values… legalPaperLength = 14; standardPaperLength = 10;

Copyright 2001 Oxford Consulting, Ltd1 January Building Blocks The const Qualifier C++ language gives us the ability to make the contents of a variable constant We use the const qualifier when we define the variable Thus, when we declare the variables and we write const int legalPaperLength = 17; const int standardPaperLength = 11; If we now try…..problem legalPaperLength = 14; standardPaperLength = 10;

Copyright 2001 Oxford Consulting, Ltd1 January Building Blocks Functions Let’s now take first look at the other kind of C++ identifier Function A C++ program is simply collection of functions Some functions are pre-defined We call these library functions Most functions User defined

Copyright 2001 Oxford Consulting, Ltd1 January Building Blocks Functions As we write larger programs...  Will need to write more functions  More sophisticated functions  We write such functions to decompose program into more manageable pieces

Copyright 2001 Oxford Consulting, Ltd1 January Building Blocks Functions We create a function by defining it Defining a function involves providing Function header Function Body

Copyright 2001 Oxford Consulting, Ltd1 January Building Blocks Functions Function Header Specifies  Function name  Return type  Parenthesized parameter list

Copyright 2001 Oxford Consulting, Ltd1 January Building Blocks Functions Function Header Function Name  Each function has a Name that is used to identify the function  The name should be descriptive of what the function does

Copyright 2001 Oxford Consulting, Ltd1 January Building Blocks Functions Function Header Argument or Parameter List  Arguments enclosed in parentheses  Appear after the function name  Separated by commas  Parentheses and the arguments Called the argument list Signature of the function  Number, type, and order of arguments Called the signature

Copyright 2001 Oxford Consulting, Ltd1 January Building Blocks Functions Function Header Return Type Return data from a function using a C++ return statement  When a value is returned from a function using the return statement the function is said to have a return value  Kind of data returned called the return type.

Copyright 2001 Oxford Consulting, Ltd1 January Building Blocks Functions Function Body  Series of C++ instructions  Enclosed in curly braces  These express the function body This is where the real work gets done Thus we have…

Copyright 2001 Oxford Consulting, Ltd1 January Building Blocks Functions returnType functionName ( arg 0, arg 1 …arg n-1 ) { body } int multiply(int first, int second) { // this is the function body } Function Body

Copyright 2001 Oxford Consulting, Ltd1 January Building Blocks Functions Using a Function  Using a function is called Executing Evaluating Invoking Calling  A function is executed By performing a function call  The function performing the function call Is the calling function  The function being executed Is the called function

Copyright 2001 Oxford Consulting, Ltd1 January Building Blocks Functions In C++ all functions created equal….. …..Any function can call any other function Recall the simple program int main(void) { // statements to execute go here return 0; }

Copyright 2001 Oxford Consulting, Ltd1 January Building Blocks Functions Let’s consider the multiply function we described above We can write the function body such that It is able to multiply the first and second argument Return the product We might ask...  How do we call the function?  How do we pass in the numbers to be multiplied?  How do we use the product that is returned?

Copyright 2001 Oxford Consulting, Ltd1 January Building Blocks Functions #include using namespace std; int multiply(length, width); // function prototype int main() { // declare some variables intlength = 10; intwidth = 20; intarea; area = multiply(length, width); // the function call cout << area << endl; // displays 200 return 0; } #include using namespace std; int multiply(length, width); // function prototype int main() { // declare some variables intlength = 10; intwidth = 20; intarea; area = multiply(length, width); // the function call cout << area << endl; // displays 200 return 0; } int multiply(int first, int second) { intanswer; answer = first * second; return answer; } int multiply(int first, int second) { intanswer; answer = first * second; return answer; }

Copyright 2001 Oxford Consulting, Ltd1 January Building Blocks Functions Function Prototypes If we look back at the example program…. We see line near top of the program #include using namespace std; int multiply(length, width); The line that looks like the function header is important Called function prototype Functions need to be known before they can be used

Copyright 2001 Oxford Consulting, Ltd1 January Building Blocks Functions You might ask why we need this ???? Doesn’t the function header provide same information Let’s see what’s going on here….. When compiler encounters a function It needs to know how to process it It needs the information contained in header To keep compiler happy It’s sufficient to declare the function If declaration not present we get a compile error We declare a function by listing return type function name (parameters)

Copyright 2001 Oxford Consulting, Ltd1 January Building Blocks Functions Nesting Functions When one function used inside a second function It’s called nesting Now, a good question How deeply can we nest functions???? Accompanying figure shows Functions nested 4 deep myF0() myF1() myF2() myF3()

Copyright 2001 Oxford Consulting, Ltd1 January Building Blocks Functions How deeply can we nest functions???? Our question has a relative answer….. We know the compiler Makes copies of the variables it uses for arguments Destroys the copies when the function completes Seems reasonable that all copies hang around (on the stack) Until the most deeply nested function call completes When we run out of the stack memory our program will crash Amount of stack memory varies with operating systems Usually adjustable if needed

Copyright 2001 Oxford Consulting, Ltd1 January Building Blocks Functions Return Value In our study of functions we’ve observed the prototype specifies return type We now ask question, Do all functions have return value????? The answer is no void displayAnswer(int answer) { cout << "The answer is: " << answer << endl; return; // this return is optional but is included // for clarity and completeness } void displayAnswer(int answer) { cout << "The answer is: " << answer << endl; return; // this return is optional but is included // for clarity and completeness }

Copyright 2001 Oxford Consulting, Ltd1 January Building Blocks Functions Now we use displayAnswer() in our example C++ program: #include using namespace std; int multiply(length, width); int main() { // declare some variables intlength = 10; intwidth = 20; intarea; area = multiply(length, width); // the function call displayAnswer(area) // displays: The answer is 200 return 0; } #include using namespace std; int multiply(length, width); int main() { // declare some variables intlength = 10; intwidth = 20; intarea; area = multiply(length, width); // the function call displayAnswer(area) // displays: The answer is 200 return 0; }

Copyright 2001 Oxford Consulting, Ltd1 January Building Blocks Functions Library Functions In addition to our own functions…. ….Many functions we will use are in libraries A library is pre-compiled code and usually comes with your compiler To use a library function we include the proper header file The header file contains the function prototype This satisfies the compiler

Copyright 2001 Oxford Consulting, Ltd1 January Building Blocks Arithmetic Operators C++ uses operators to perform arithmetic operations on variables. Operators are the same for both integer and floating-point Basic C++ operators are: +add -subtract /divide *multiply …and they work as you would expect

Copyright 2001 Oxford Consulting, Ltd1 January Building Blocks Arithmetic Operators Operator Precedence Let’s declare some variables…. e variables int a = 20; int b = 25; int c; Then write c = a * 2/b + 15; However, if we include these four lines of code in a program Then compile and run it…. We will print the number 16 will appear Why did that happen? Variable c is a times 2 divided by b plus 15 Which is really 40 divided by 40 We expect the variable c to be 1 Variable c is a times 2 divided by b plus 15 Which is really 40 divided by 40 We expect the variable c to be 1

Copyright 2001 Oxford Consulting, Ltd1 January Building Blocks Arithmetic Operators Operator Precedence The answer lies in a concept we call operator precedence Operators in C++ are evaluated in a specific order Based upon precedence ….. For this example the compiler will  Perform division before addition  Perform multiplication before division

Copyright 2001 Oxford Consulting, Ltd1 January Building Blocks Arithmetic Operators Operator Precedence In the light of precedence 1. a is multiplied by 2 Because multiplication comes before division or addition This is 20 times 2 which is Next 40 is divided by b Because division comes before addition This is 40 divided by 25 which is Finally, 15 is added to 1 To give 16

Copyright 2001 Oxford Consulting, Ltd1 January Building Blocks Arithmetic Operators Operator Precedence If we wish evaluation to proceed in different order, we can over ride the precedence using parentheses To force b plus 15 to be done before the division…. ….We enclose those terms in parentheses c = a * 2/ (b + 15); Doing this changes evaluation order because the grouping parentheses operator comes before any arithmetic operator

Copyright 2001 Oxford Consulting, Ltd1 January Building Blocks Arithmetic Operators Operator Associativity Now we ask…. If precedence determines which operator is applied first, What happens when all of the operators in a line of code Have the same precedence????? a + b – c Does the compiler evaluate a + b or b – c first? The answer is associativity subtraction According to the C++ Operator Precedence and Associativity table The associatively of addition and subtraction is Left to Right

Copyright 2001 Oxford Consulting, Ltd1 January Building Blocks Arithmetic Operators Integer Division For our example the answer will be 1. Why????? Integers do not have fractional parts Because the two operands are integers…. The compiler expresses result (1.6) as an integer Which is 1 since 0.6 can't be expressed as integer int x = 40; int y = 25; x = x / y; cout << x << endl int x = 40; int y = 25; x = x / y; cout << x << endl

Copyright 2001 Oxford Consulting, Ltd1 January Building Blocks Arithmetic Operators The Modulus Operator % We’ve seen integer division gives us  Whole number part  Remainder part …and the remainder part disappears If we want the remainder portion we must use an operator Called the modulus operator Written as percent sign % Also called remainder operator

Copyright 2001 Oxford Consulting, Ltd1 January Building Blocks Arithmetic Operators The Modulus Operator % Let’s apply the mod operator to the following integer int number = 15; cout << number % 3 << endl;// prints 0 …3 divides 15 // 5 times with 0 remainder cout << number % 5 << endl;// prints 0 …5 divides 15 // 3 times with 0 remainder cout << number % 10; << endl;// prints 5 …10 divides 15 // 1 time with 5 remainder cout << number % 2; << endl;// prints 1 …2 divides 15 7 // times with 1 remainder