1 More C++ Basics Chapter 3 Lecture CSIS 10A. 2 Agenda Review  C++ Standard Numeric Types Arithmetic–way more than you want! Character (char) data type.

Slides:



Advertisements
Similar presentations
Lecture Computer Science I - Martin Hardwick The Programming Process rUse an editor to create a program file (source file). l contains the text of.
Advertisements

Variables in C Amir Haider Lecturer.
L2:CSC © Dr. Basheer M. Nasef Lecture #2 By Dr. Basheer M. Nasef.
C++ Basics Variables, Identifiers, Assignments, Input/Output.
1 Demo Reading Assignments Important terms & concepts Fundamental Data Types Identifier Naming Arithmetic Operations Sample Programs CSE Lecture.
CSE202: Lecture 2The Ohio State University1 Variables and C++ Data Types.
Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types.
C Programming Basics Lecture 5 Engineering H192 Winter 2005 Lecture 05
1 9/20/06CS150 Introduction to Computer Science 1 Review: Exam 1.
COMPSCI 125 Spring 2005 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 3: Numeric Data *Variables *Numeric data.
Chapter 3 Numerical Data. Topics Variables Numeric data types Assignment Expressions.
Chapter 2 Data Types, Declarations, and Displays
Basic Elements of C++ Chapter 2.
KEAN UNIVERSITY Visual C++ Dr. K. Shahrabi. Developer studio Is a self-contain environment for creating, compiling, linking and testing windows program.
CSC 125 Introduction to C++ Programming Chapter 2 Introduction to C++
CS 192 Lecture 3 Winter 2003 December 5, 2003 Dr. Shafay Shamail.
© Janice Regan, CMPT 128, Jan CMPT 128: Introduction to Computing Science for Engineering Students Data representation and Data Types Variables.
COMPUTER PROGRAMMING. Data Types “Hello world” program Does it do a useful work? Writing several lines of code. Compiling the program. Executing the program.
Input & Output: Console
Copyright 2006 Addison-Wesley Brief Version of Starting Out with C++ Chapter 2 Introduction to C++
C Tokens Identifiers Keywords Constants Operators Special symbols.
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.
Basic Notions Review what is a variable? value? address? memory location? what is an identifier? variable name? keyword? what is a legal identifier? what.
1 C++ Programming Basics Chapter 2 Lecture CSIS 10A.
Data & Data Types & Simple Math Operation 1 Data and Data Type Standard I/O Simple Math operation.
C++ Programming, Namiq Sultan1 Chapter 2 Introduction to C++ Namiq Sultan University of Duhok Department of Electrical and Computer Engineerin Reference:
C++ Programming: Basic Elements of C++.
Chapter 7 Additional Control Structures. Chapter 7 Topics l Switch Statement for Multi-Way Branching l Do-While Statement for Looping l For Statement.
Chapter 2 Overview of C++. 2 Overview  2.1 Language Elements  2.2 Reserved Words & Identifiers  2.3 Data Types & Declarations  2.4 Input/Output 
CSC 107 – Programming For Science. The Week’s Goal.
COMPUTER PROGRAMMING. variable What is variable? a portion of memory to store a determined value. Each variable needs an identifier that distinguishes.
Computer Science 1620 boolean. Types so far: Integer char, short, int, long Floating Point float, double, long double String sequence of chars.
Engineering H192 - Computer Programming The Ohio State University Gateway Engineering Education Coalition Lect 5P. 1Winter Quarter C Programming Basics.
Computing with C# and the.NET Framework Chapter 2 C# Programming Basics ©2003, 2011 Art Gittleman.
Variables and Data Types.  Variable: Portion of memory for storing a determined value.  Could be numerical, could be character or sequence of characters.
Engineering H192 - Computer Programming Gateway Engineering Education Coalition Lect 5P. 1Winter Quarter C Programming Basics Lecture 5.
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.
Java Language Basics By Keywords Keywords of Java are given below – abstract continue for new switch assert *** default goto * package.
Chapter 2 Variables.
Types of C Variables:  The following are some types of C variables on the basis of constants values it has. For example: ○ An integer variable can hold.
C++ Programming Lecture 3 C++ Basics – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
1 09/27/04CS150 Introduction to Computer Science 1 Let ’ s all Repeat Together.
Lecture 5 Computer programming -1-. Input \ Output statement 1- Input (cin) : Use to input data from keyboard. Example : cin >> age; 2- Output (cout):
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.
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.
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.
C++ Lesson 1.
Asst.Prof.Dr. Tayfun ÖZGÜR
Variables, Identifiers, Assignments, Input/Output
Chapter 2 Variables.
Chapter Topics The Basics of a C++ Program Data Types
Data types Data types Basic types
BASIC ELEMENTS OF A COMPUTER PROGRAM
Basic Elements of C++.
Computing with C# and the .NET Framework
Chapter 3: Understanding C# Language Fundamentals
Reserved Words.
Basic Elements of C++ Chapter 2.
Character Set The character set of C represents alphabet, digit or any symbol used to represent information. Types Character Set Uppercase Alphabets A,
Chapter 7 Additional Control Structures
Chapter 2 Variables.
Variables, Identifiers, Assignments, Input/Output
Prof. Bhushan Trivedi Director GLS Institute of Computer Technology
2. Second Step for Learning C++ Programming • Data Type • Char • Float
Chapter 2 Variables.
Variables in C Topics Naming Variables Declaring Variables
Presentation transcript:

1 More C++ Basics Chapter 3 Lecture CSIS 10A

2 Agenda Review  C++ Standard Numeric Types Arithmetic–way more than you want! Character (char) data type For Loop Syntax, Run-time and Logical Errors

3 Review: Standard Program Structure To solve most problems, your main() program will generally look like this (conceptually) 1.Declare variables for input, result and intermediate data 2.Ask for data (cout) 3.Input data (cin) 4.Calculate result 5.Output result (cout)

4 An interactive C++ program: //circle.cpp Calculate area of a circle // given a radius value #include using namespace std; int main() {int area, radius; cout << "enter a radius: "; cin >> radius; area = radius * radius * 3.14; cout << "the area is " << area << endl; return 0; }

5 A small problem… Run circle.cpp: But according to our code, it should be 3.14 What happened? enter a radius: 1 the area is 3 Press any key to continue...

6 We used the wrong data type! Go back, change: int area, radius; To: float area, radius; Now it works…the lesson? 1) Data types are important! 2) Testing is important!

7 Agenda Review C++ Standard Numeric Types  Arithmetic–way more than you want! Character (char) data type For Loop Syntax, Run-time and Logical Errors

8 Basic C++ Data Types int – Represents integers float – Represents real (floating point) numbers char – Represents characters (single letters)

9 Integers only store whole numbers int a=4; // puts 4 in a int a= ; // puts 4 in a INTS are great for loop counters, representing inventory, numbers of “things”

10 Trivia—other integer types uses range of values short (2 bytes)….-32,767 to long …….….(4 bytes)…-2 bill to +2 billion int ………….(depends)…long (sometimes short) unsigned short (2 bytes)…0 to unsigned long...(4 bytes) …0 to 4 billion

11 Beware Integer wraparound // wrap.cpp int a, b, c; a = ; b = 2 * a; c = 3 * a; cout << "b is " << b << endl; cout << "c is " << c << endl; b is c is

12 FLOATING-POINT Types float is used to represent numbers with a fractional part such as or 6.45 etc… or really big numbers that won’t fit inside ints uses range precision float (4 bytes)…… to ……..6 digits double…...(8 bytes)…… to …...15 digits long double (10 bytes) to …19 digits

13 What does floating point mean? Consider a number like “Float” the point so that all the digits are on its right (here the point is shifted 3 digits to the left) = x 10 3 E-notation: the letter ‘e’= “x10 to the power of” You can actually enter or display data using ‘e’: same as e3 same as e2

14 Fine…. How is this stored in a float variable ?? The mantissa and the exponent 3 are stored separately (in a variable) For a 32 bit float type : 23 bit mantissa + 8 bit exponent + 1 sign bit For a 64 bit double type : 52 bit mantissa + 11 bit exponent + 1 sign bit

15 Implications for Accuracy (round-off error) A float only stores about 6 digits of mantissa float PI= ; PI really contains float x= , y= ; x=x+y; DOES NOT CHANGE X!!! (no room) Use a double if you need more precision double PI= ; About 16 digits of mantissa double x= , y= ; x=x+y; DOES CHANGE X!!! (now there’s room)

16 Q1) Practice your Scientific Notation (answers at end of slides) = ____________ x 10 ____.03413= ____________ e ____ 6.78 x 10 7 = ____________ 5.32e-5 = ____________

17 Displaying Floating Point data cout << 4.5 << endl; cout << << endl; cout << << endl; cout << << endl; cout << << endl; cout << << endl; cout << << endl; Output e e e-05 This is an integer, no ‘.’

18 Formating Floating Point Output cout<<fixed<<showpoint<<setprecision(2); cout << 4.5 << endl; cout << << endl; cout << << endl; cout << << endl; cout << << endl; cout << << endl; cout << << endl; You can use this on problem 8 Output For this to work, #include

19 Constants are “variables” -- that never change Use the keyword “const” in front of declaration You MUST provide initial value at declaration const double PI= ; const double METERS_PER_YARD = ; const int MAX=1000; Now you can say: area = PI * radius * radius; Don’t over do it: const int SECONDS_PER_MINUTE = 60; You can use a constant for problem 7

20 Agenda Review C++ Standard Numeric Types Arithmetic–way more than you want!  Character (char) data type For Loop Syntax, Run-time and Logical Errors

21 Arithmetic in C++ Basic operations + - * / Math formulas need to be converted into C++ syntax: FORMULA Equivalent C++ A =  r 2 area=3.14*radius*radius; F = (v -a) force=(v-a)/(v+a); (v+a)

22 More C++ Math Formulas

23 Arithmetic -- Order of Precedence * and / are done first, then + and – Equal levels are done left to right Example: 3 * = * 4 = / = = = 11 Parentheses have highest precedence (use if you want different order) (6 + 4) / (2 + 3) = 2

24 Q2) Practice Arithmetic Precedence Evaluate the following 1+2 * = _______ / 2 * 3 = _______ * (3 + 4) = _______ (7 + 5) / (2 * 3)= _______

25 Mixed-type Expressions Expressions involving int and float will give a result of type float (the most inclusive type) Suppose you have int n; float x; Then n + x  results in float n * 4  results in int n  results in double (4.0 is double) (default for floating pt literals)

26 Mixed-type Assignments Assigning int to float is perfectly safe Assigning float to int may lose fractional part Suppose you have int n; float x; Then 1.x = 15;  stores 15 in x 2.n = 4.5;  stores 4 in n -- Compiler Warning! To satisfy the compiler for (2.) simply explain your intentions: n = int(4.5);

27 Q3) Can you guess what is stored in these variables? int m, n; double x,y; m = 3.0; n = 12.7; x = m; x = x m = m + 1; y = x + 1; mnxy ????

28 Integer Division CAUTION—this is a common C++ error When both sides are int, the result MUST be int 9 / 2 = 4 9 / 10 = 0 Sometimes this is what we want (convert inches to inches and feet) Usually causes programming errors When one side is float, the answer is float 9 / 2.0 = / 10 = 0.9

29 Q4) Can you guess what is stored in these variables? int m, n; double x,y; m = 10 / 3; n = 30 / 7; x = n * m; y = 3 / 4 * x; y = x * 3 / 4; y = (x + 3) / 4; mnxy ????

30 One more thing…type-casting If you want to perform floating point division on a pair of integer variables, you can…but you have to temporarily convert one of them to float first: int m=3, n=4; float y; y = float(m) / n; ( y = 0.75) WRONG y = float(m/n); ( y = 0)

31 Break Time! Download Lab2MoreBasics.cpp Work on problems 1-4, 7,8 Call me over if you have questions

32 Remainder % operator The expression 10 / 3 gives the quotient, 3 We use 10 % 3 to get the remainder, 1 4 / 3 = 112 % 6 = 0 4 % 3 = 1 13 % 6 = ____ 2 / 3 = 014 % 6 = ____ 2 % 3 = 223 % 7 = _____ Only use % on integers

33 What good is % operator? You can use it to subdivide something into hierarchical units: int feet, inches; cout << "Enter inches: "; cin >> inches; feet = inches / 12; inches = inches % 12; cout << feet << " ft. " << inches << " in."; This is used in things like time, weight, length, change, etc. Use this slide on Problem 9 Enter inches: 75 6 ft. 3 in.

34 Arithmetic Assignment Operators Numeric operators +, -, *, /, % can be combined with the assignment operator = Saves time and typing Only when you want to store result in one of operands a += b  a = a + b a -= b  a = a - b a *= b  a = a * b a /= b  a = a / b a %= b  a = a % b

35 Q5) Arithmetic Assign Operator Table START: int x=0; ShorthandSame asResult x+=5; x*=2; x/=5; x-=2; x+=10; x*=3; x%=8 x/=5; x=x+5; x=x*2; x=x/5; x=x-2;

36 Agenda Review C++ Standard Numeric Types Arithmetic–way more than you want! Character (char) data type  For Loop Syntax, Run-time and Logical Errors

37 CHARACTER types (see Lab3-1) char……………... (1 byte) unsigned char…….(1 byte) A char stores a single letter What is actually stored is the binary sequence corresponding to a letter’s ASCII code You can either store a letter, or the numeric code for the letter in a char

38 Check this out…. #include void main() {both a and c contain 65 or ‘A’ char a = 65, c = 'A'; cout << “ c = “ << c << endl; cout << “ a = “ << a << endl; } Output….. c = A a = A (in other words, ‘A’ is same as 65)

39 Decimal ASCII Table

40 Character Input Read 2 chars char grade1, grade2; cin>>grade1>>grade2; cout<<“Grade 1 is ”<<grade1<<endl; cout<<“Grade 2 is ”<<grade2<<endl; NOTE white space ignored: type AB, A B, A (enter) B  same result Another interesting topic, character escape and control sequences, p 53/54

41 Agenda Review C++ Standard Numeric Types Arithmetic–way more than you want! Character (char) data type For Loop  Syntax, Run-time and Logical Errors

42 Bored with single execution programs? Add a for loop to repeat your code several times: for (int k=1; k<=final_value; k=k+1) { statements to repeat }

43 Example Looped code Add a for loop to repeat your code several times: int main() { for (int k=1; k<=3; k=k+1) { cout<<“Testing”<<k<<endl; } Testing 1 Testing 2 Testing 3 Or k++ for short

44 Example Application (for challenge) Calculate pay for 3 employees: int hrs; double rate; for (int emp=1; emp<=3; emp++) { cout<<“Enter hours & rate: ”; cin>> hrs>> rate; cout<<“Pay = $”<< hrs * rate <<endl; } See p57 to let user determine the number of iterations

45 Agenda Review C++ Standard Numeric Types Arithmetic–way more than you want! Character (char) data type For Loop Syntax, Run-time and Logical Errors 

46 Types of Errors Syntax: an error in your C++ language/grammar (covered last week) confuses compiler (The dog his paw) forgetting a ; misspelling a variable name datha=3.14; Runtime: when you do something illegal during program execution temp=0.0; rate=1.0/temp; // dividing a number by zero –crash! Logical (or Semantic): When you say something illogical A paw ate his dog. ( Good grammar, illogical meaning) avg = b + c / 2;

47 Tracking them down Syntax— double click on error message, it takes you to line of code Look at or above that line for possible errors Runtime & Logical You detect them by checking output against test plan Pinpoint them by displaying variables during intermediate steps (cout) OR Use debugger to step through program, put watch on variables

48 LIST OF KEYWORDS….. asm auto bool break case catch char class const const_cast continue default delete do double dynamic_ cast else enum explicit export extern false float for friend goto if inline int long mutable namespace new operator private protected public register reinterpret _cast return short signed sizeof static static_cast struct switch template this throw true try typedef typeid typename union unsigned using virtual void volatile wchar_t while

49 That’s a wrap ! What we learned today: Data Types Rules of Arithmetic For loops How to debug your program

50 A1) Answers to Scientific Notation = x = e x 10 7 = e-5 =

51 A2) Arithmetic Precedence Evaluate the following 1+2 * = / 2 * 3 = * (3 + 4) = 15 (7 + 5) / (2 * 3)= 2

52 A3) Answer: int m, n; double x,y; m = 3.0; n = 12.7; x = m; x = x m = m + 1; y = x + 1; mnxy ????

53 A4) Integer Division int m, n; double x,y; m = 10 / 3; n = 30 / 7; x = n * m; y = 3 / 4 * x; y = x * 3 / 4; y = (x + 3) / 4; mnxy ????

54 A5) Arithmetic Assign Operator Table START: int x=0; ShorthandSame asResult x+=5; x*=2; x/=5; x-=2; x+=10; x*=3; x%=8 x/=5; x=x+5; x=x*2; x=x/5; x=x-2; x=x+10; x=x*3; x=x%8; x=x/5;