Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200 1 Chapter 2 Elementary Programming.

Slides:



Advertisements
Similar presentations
L2:CSC © Dr. Basheer M. Nasef Lecture #2 By Dr. Basheer M. Nasef.
Advertisements

Chapter 2 Elementary Programming
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 2 1 Chapter 2 Primitive.
Chapter 2 Primitive Data Types and Operations F Introduce Programming with an Example F Identifiers, Variables, and Constants F Primitive Data Types –byte,
Primitive Data Types and Operations. Introducing Programming with an Example public class ComputeArea { /** Main method */ public static void main(String[]
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 2 Primitive Data.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 2 1 Chapter 2 Primitive.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 2 Primitive Data.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 2 Primitive Data.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 2 Elementary Programming.
Chapter 2: Introduction to C++.
1 Chapter 2: Elementary Programming Shahriar Hossain.
Introduction to Java Programming, 4E Y. Daniel Liang.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 2 Elementary Programming.
Basic Elements of C++ Chapter 2.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 2 Elementary Programming.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 Chapter 2 Elementary Programming.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 Chapter 2 Elementary Programming.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 Chapter 2 Elementary Programming.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 2 Elementary Programming.
 2003 Prentice Hall, Inc. All rights reserved. 1 Introduction to C++ Programming Outline Introduction to C++ Programming A Simple Program: Printing a.
Java Building Elements Lecture 2 Instructors: Fu-Chiung Cheng ( 鄭福炯 ) Associate Professor Computer Science & Engineering Tatung University
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 2 Elementary Programming.
Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)
Chapter 2 Elementary Programming 1. Introducing Programming with an Example Listing 2.1 Computing the Area of a Circle This program computes the area.
Primitive Data Types and Operations Identifiers, Variables, and Constants Primitive Data Types Byte, short, int, long, float, double, char, boolean Casting.
Chapter 2 Primitive Data Types and Operations F Introduce Programming with an Example  The MyInput class F Identifiers, Variables, and Constants F Primitive.
1 Chapter 2 Primitive Data Types and Operations F Introduce Programming with an Example  The MyInput class F Identifiers, Variables, and Constants F Primitive.
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. 1 Chapter 2 Elementary Programming.
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
1 Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 2 Primitive Data Types and Operations.
VARIABLES Introduction to Computer Science 1- COMP 1005, 1405 Instructor : Behnam Hajian
© Copyright 2013 by Pearson Education, Inc. All Rights Reserved.1 Chapter 4 Mathematical Functions, Characters, and Strings.
1 Do you have a CS account? Primitive types –“ building blocks ” for more complicated types Java is strongly typed –All variables in a Java program must.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-1 Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
Chapter 2 Elementary Programming
C++ Programming: Basic Elements of C++.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 2 Primitive Data.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 2 Elementary Programming.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 3 Selections.
A Simple Java Program //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { public static void main(String[]
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 2 Primitive Data Types and Operations.
PROGRAM ESSENTIALS. TOKENS  SMALLEST UNITS OF A PROGRAM LANGUAGE  Special Symbols  Mathematical Operators  Punctuation  Word Symbols  Key Words.
Tokens in C  Keywords  These are reserved words of the C language. For example int, float, if, else, for, while etc.  Identifiers  An Identifier is.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Elementary Programming.
1 1 Chapter 2 Elementary Programming. 2 2 Motivations In the preceding chapter, you learned how to create, compile, and run a Java program. Starting from.
Primitive Data Types and Operations F Introduce Programming with an Example F Identifiers, Variables, and Constants F Primitive Data Types –byte, short,
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 2 Primitive Data Types and Operations.
1.  Algorithm: 1. Read in the radius 2. Compute the area using the following formula: area = radius x radius x PI 3. Display the area 2.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Topic 2: Input / Output Formatting Lecturer:
Chapter 2 Elementary Programming
TK1913 C++ Programming Basic Elements of C++.
Topic 2 Elementary Programming
Elementary Programming
Chapter 2 Elementary Programming
Lecture 3: Operators, Expressions and Type Conversion
Computing Fundamentals
Chapter 2 Elementary Programming
Basic Elements of C++ Chapter 2.
Chapter 2 Elementary Programming
Chapter 2 Elementary Programming
Chapter 2 Elementary Programming
مساق: خوارزميات ومبادئ البرمجة الفصل الدراسي الثاني 2016/2015
Numerical Data Types.
Chapter 2 Elementary Programming
Chapter 2 Elementary Programming
Chapter 2 Primitive Data Types and Operations
Presentation transcript:

Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 2 Elementary Programming

Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Motivations In the preceding chapter, you learned how to create, compile, and run a program. Starting from this chapter, you will learn how to solve practical problems programmatically. Through these problems, you will learn primitive data types and related subjects, such as variables, constants, data types, operators, expressions, and input and output.

Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Objectives F To write C++ programs to perform simple calculations (§2.2). F To read input from the keyboard (§2.3). F To use identifiers to name elements in the program (§2.4). F To use variables to store data (§§ ). F To program with assignment statements and assignment expressions (§2.6). F To name constants using the const keyword and #define directive (§2.7). F To declare variables using numeric data types (§2.8). F To use operators to write numeric expressions (§2.8). F To convert numbers to a different type using casting (§2.9). F To represent character using the char type (§2.10). F To become familiar with C++ documentation, programming style, and naming conventions (§2.12). F To distinguish syntax errors, runtime errors, and logic errors (§2.13). F To debug logic errors (§2.14). (note cool Visual Studio debugger!)

Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Introducing Programming with an Example Listing 2.1 Computing the Area of a Circle This program computes the area of the circle. ComputeArea Run

Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Trace a Program Execution #include using namespace std; int main() { double radius; double area; // Step 1: Read in radius radius = 20; // Step 2: Compute area area = radius * radius * ; // Step 3: Display the area cout << "The area is "; cout << area << endl; } no value radius allocate memory for radius animation Note: a memory location has a name, a type, and a value. Note: default value is whatever way the bits happen to be “flipped”: there is a value, it is just random.

Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Trace a Program Execution no value radius memory animation #include using namespace std; int main() { double radius; double area; // Step 1: Read in radius radius = 20; // Step 2: Compute area area = radius * radius * ; // Step 3: Display the area cout << "The area is "; cout << area << std::endl; } no value area allocate memory for area

Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Trace a Program Execution 20 radius no value area assign 20 to radius animation #include using namespace std; int main() { double radius; double area; // Step 1: Read in radius radius = 20; // Step 2: Compute area area = radius * radius * ; // Step 3: Display the area cout << "The area is "; cout << area << std::endl; } Note: “=“ is not “equals” but an “assignment” i.e., “take the value of the expression on the right and stick it in the memory location on the left.” Think <=

Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Trace a Program Execution 20 radius memory area compute area and assign it to variable area animation #include using namespace std; int main() { double radius; double area; // Step 1: Read in radius radius = 20; // Step 2: Compute area area = radius * radius * ; // Step 3: Display the area cout << "The area is "; cout << area << std::endl; }

Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Trace a Program Execution 20 radius memory area print a message to the console animation #include using namespace std; int main() { double radius; double area; // Step 1: Read in radius radius = 20; // Step 2: Compute area area = radius * radius * ; // Step 3: Display the area cout << "The area is "; cout << area << std::endl; }

Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Reading Input from the Keyboard You can use the cin object to read input from the keyboard. ComputeArea1 Run #include using namespace std; int main() { double radius = 0; //does not cost anything to initialize to zero cout <<“enter a radius: “; cin >> radius; double area = radius * radius # ; cout << “the area is “ << area << endl;system (“pause”); return 0; }

Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Reading Multiple Input in One Statement ComputeAverage Run #include using namespace std; int main() { double num1, num2, num3;; cout <<“enter three numbers: “; cin >> num1 >> num2 >> num3; double average = num1 + num2 + num3/3 //what is wrong with this line? cout << “the average is “ << average<< endl; system (“pause”); return 0; }

Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Identifiers F An identifier is a sequence of characters that consists of letters, digits, and underscores (_). F An identifier must start with a letter or an underscore. It cannot start with a digit. F An identifier cannot be a reserved word. (See Appendix A, “C++ Keywords,” for a list of reserved words.),-- creates lots of syntax errors ! F An identifier can be of any length, but your C++ compiler may impose some restriction. Use identifiers of 31 characters or fewer to ensure portability.

Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Identifiers F InnerCap naming method vs underlines –Screen space can become important F Use good names with rich meanings: –Names are important –Magic – if you know something’s true name, you can control it. –Interest rate vs MonthlyInterestRate vs MonthlyDecimalInterestRate F Consistent abbreviations: –Num, no, nm, number – pick one and stick w/ it 13

Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Variables // Compute the first area radius = 1.0; area = radius * radius * ; cout << area; // Compute the second area radius = 2.0; area = radius * radius * ; cout << area;

Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Declaring Variables int x; // Declare x to be an // integer variable; double radius; // Declare radius to // be a double variable; char a; // Declare a to be a // character variable;

Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Assignment Statements x = 1; // Assign 1 to x; radius = 1.0; // Assign 1.0 to radius; a = 'A'; // Assign 'A' to a; /* note ‘A’ vs “A” */

Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Declaring and Initializing in One Step F int x = 1; F double d = 1.4; Always initialize variables if you are not going to assign a value shortly.

Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Named Constants const datatype CONSTANTNAME = VALUE; const double PI = ; const int SIZE = 3; Why use const or #define: Don’t bake in constants, particularly in multiple locations. Things change. Constant with good name makes code easier to read.

Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Numerical Data Types

Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved sizeof Function You can use the sizeof function to find the size of a type. For example, the following statement displays the size of int, long, and double on your machine. cout << sizeof(int) << " " << sizeof(long) << " " << sizeof(double);

Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Synonymous Types short int is synonymous to short. unsigned short int is synonymous to unsigned short. unsigned int is synonymous to unsigned. long int is synonymous to long. unsigned long int is synonymous to unsigned long. For example, short int i = 2; is same as short i = 2; (I would stick with “short int” and “unsigned short int” to avoid mistakes)

Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Numeric Literals A literal is a constant value that appears directly in a program. For example, 34, , and 5.0 are literals in the following statements: int i = 34; long k = ; double d = 5.0; Style note: a given literal constant should appear only once in a program – constants are not constant!

Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved why called floating-point? The float and double types are used to represent numbers with a decimal point. Why are they called floating-point numbers? These numbers are stored into scientific notation. When a number such as e+1 is converted into scientific notation such as , its decimal point is moved (i.e., floated) to a new position. Precision limits to floating point – how stored and example

Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Numeric Operators Remainder often called modulus or MOD

Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Integer Division +, -, *, /, and % 5 / 2 yields an integer / 2 yields a double value % 2 yields 1 (the remainder of the division)

Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Remainder Operator Remainder is very useful in programming. For example, an even number % 2 is always 0 and an odd number % 2 is always 1. So you can use this property to determine whether a number is even or odd. Suppose today is Saturday and you and your friends are going to meet in 10 days. What day is in 10 days? You can find that day is Tuesday using the following expression:

Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Example: Displaying Time Write a program that obtains hours and minutes from seconds. DisplayTime Run

Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Overflow When a variable is assigned a value that is too large to be stored, it causes overflow. For example, executing the following statement causes overflow, because the largest value that can be stored in a variable of the short type is is too large. short value = ;

Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Arithmetic Expressions is translated to (3+4*x)/5 – 10*(y-5)*(a+b+c)/x + 9*(4/x + (9+x)/y)

Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Example: Converting Temperatures Write a program that converts a Fahrenheit degree to Celsius using the formula: FahrenheitToCelsius Run Derive formula

Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Shorthand Assignment Operators OperatorExampleEquivalent +=i += 8i = i + 8 -=f -= 8.0f = f *=i *= 8i = i * 8 /=i /= 8i = i / 8 %=i %= 8i = i % 8

Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Increment and Decrement Operators OperatorNameDescription ++varpreincrementThe expression (++var) increments var by 1 and evaluates to the new value in var after the increment. var++postincrementThe expression (var++) evaluates to the original value in var and increments var by 1. --varpredecrementThe expression (--var) decrements var by 1 and evaluates to the new value in var after the decrement. var--postdecrement The expression (var--) evaluates to the original value in var and decrements var by 1. These are ok as stand alone statements, but don’t use them inside an assignment statement. Consider the following: i = i++ + i <- different compliers will do different things – just don’t go there. The way to fix a bug is to not make it in the first place. Develop coding styles that minimize the number of bugs you create.

Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Increment and Decrement Operators, cont. Don’t do this!!!!!!!!!!!!!

Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Numeric Type Conversion Consider the following statements: short i = 100; long k = i * 3 + 4; double d = i * k / 2;

Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Type Casting Implicit casting double d = 3; (type widening) Explicit casting //this is better int i = static_cast (3.0); (type narrowing) int i = (int)3.9; (Fraction part is truncated)

Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved NOTE Casting does not change the variable being cast. For example, d is not changed after casting in the following code: double d = 4.5; int i = static_cast (d); // d is not changed

Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved NOTE The GNU and Visual C++ compilers will give a warning when you narrow a type unless you use static_cast to make the conversion explicit.

Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Character Data Type char letter = 'A'; (ASCII) char numChar = '4'; (ASCII) NOTE: The increment and decrement operators can also be used on char variables to get the next or preceding character. For example, the following statements display character b. char ch = 'a'; Ch++; cout << ch;

Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Read Characters To read a character from the keyboard, use cout << "Enter a character: "; char ch; cin >> ch;

Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Escape Sequences for Special Characters

Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Appendix B: ASCII Character Set ASCII Character Set is a subset of the Unicode from \u0000 to \u007f

Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved ASCII Character Set, cont. ASCII Character Set is a subset of the Unicode from \u0000 to \u007f

Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Casting between char and Numeric Types int i = ' a ' ; // Same as int i = (int) ' a ' ; char c = 97; // Same as char c = (char)97;

Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Numeric Operators on Characters The char type is treated as if it is an integer of the byte size. All numeric operators can be applied to char operands. A char operand is automatically cast into a number if the other operand is a number or a character. For example, the following statements int i = '2' + '3'; // (int)'2' is 50 and (int)'3' is 51 cout << "i is " << i << endl; // i is decimal 101 int j = 2 + 'a'; // (int)'a' is 97 cout << "j is " << j << endl; cout << j << " is the ASCII code for character " << static_cast (j) << endl; Display i is 101 j is is the ASCII code for character c

Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Note It is worthwhile to note that the ASCII for lowercase letters are consecutive integers starting from the code for 'a', then for 'b', 'c',..., and 'z'. The same is true for the uppercase letters. Furthermore, the ASCII code for 'a' is greater than the code for 'A'. So 'a' - 'A' is the same as 'b' - 'B'. For a lowercase letter ch, its corresponding uppercase letter is static_cast ('A' + (ch - 'a')).

Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Problem: Computing Loan Payments ComputeLoanRun This program lets the user enter the interest rate, number of years, and loan amount and computes monthly payment and total payment.

Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Problem: Displaying Current Time Write a program that displays current time in GMT in the format hour:minute:second such as 1:45:19. The time(0) function in the ctime header file returns the current time in seconds elapsed since the time 00:00:00 on January 1, 1970 GMT, as shown in Figure 2.1. This time is known as the Unix epoch because 1970 was the year when the Unix operating system was formally introduced. ShowCurrentTime Run

Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Programming Style and Documentation F Appropriate Comments F Naming Conventions F Proper Indentation and Spacing Lines F Block Styles F Don’t bake in constants