CS221 C++ Basics. C++ Data Types structured array struct union class address pointer reference simple integral char short int long bool floating float.

Slides:



Advertisements
Similar presentations
Dale/Weems/Headington
Advertisements

Dale/Weems/Headington
1 Lecture 6 Chapter 3 Numeric Types, Expressions, and Output Dale/Weems/Headington.
1 Lecture-4 Chapter 2 C++ Syntax and Semantics, and the Program Development Process Dale/Weems/Headington.
1 Chapter 3 Arithmetic Expressions. 2 Chapter 3 Topics l Overview of Java Data Types l Numeric Data Types l Declarations for Numeric Expressions l Simple.
Lecture 18:Topic: I/O Formatting and Files Dale/Weems/Headington
1 Chapter 2 C++ Syntax and Semantics, and the Program Development Process Dale/Weems/Headington.
1 Chapter 3 Topics Constants of Type int and float l Evaluating Arithmetic Expressions l Implicit Type Coercion and Explicit Type Conversion l Calling.
How to Program in C++ CHAPTER 3: INPUT & OUTPUT INSTRUCTOR: MOHAMMAD MOJADDAM.
1 Lecture 7 Chapter 3 Numeric Types, Expressions, and Output Dale/Weems/Headington.
Chapter 3: Input/Output
Data Types, Expressions and Functions (part I)
Basic Elements of C++ Chapter 2.
Expressions and Interactivity Chapter 3. 2 The cin Object Standard input object Like cout, requires iostream file Used to read input from keyboard Often.
C++ Vs. Java Who will win?. Look Ma, no classes! C++ was conceived as an object-oriented extension to C C was (is) purely procedural language –Functions.
Chapter 2 C++ Syntax and Semantics, and the Program Development Process Dale/Weems.
Elements of a C++ program 1. Review Algorithms describe how to solve a problem Structured English (pseudo-code) Programs form that can be translated into.
1 Chapter 4 Program Input and the Software Design Process.
1 Numeric Types, Expressions, and Output. 2 Chapter 3 Topics  Constants of Type int and float  Evaluating Arithmetic Expressions  Declaration for Numeric.
Numeric Types, Expressions, and Output 1. Chapter 3 Topics Constants of Type int and float Evaluating Arithmetic Expressions Implicit Type Coercion and.
1 Chapter 3 Numeric Types, Expressions, and Output Dale/Weems.
1 Chapter 3 Numeric Types, Expressions, and Output Dale/Weems.
1 Chapter 3 Numeric Types, Expressions, and Output CS185/09 - Introduction to Programming Caldwell College.
1 Chapter 4 Program Input and the Software Design Process Dale/Weems/Headington.
IXA 1234: C++ PROGRAMMING CHAPTER 2: PROGRAM STRUCTURE.
1 Programs Composed of Several Functions Syntax Templates Legal C++ Identifiers Assigning Values to Variables Declaring Named Constants String Concatenation.
1 Chapter 3 Numeric Types, Expressions, and Output Dale/Weems/Headington.
Chapter 2 Overview of C++. A Sample Program // This is my first program. It calculates and outputs // how many fingers I have. #include using namespace.
Lecture no 3 Control statements.
1 C++ Syntax and Semantics, and the Program Development Process.
1 Chapter 2 C++ Syntax and Semantics, and the Program Development Process Dale/Weems/Headington.
1 Chapter 2 C++ Syntax and Semantics, and the Program Development Process Dale/Weems.
C++ Programming: Basic Elements of C++.
1 Chapter 3 Numeric Types, Expressions, and Output Dale/Weems/Headington.
1 Chapter 2 C++ Syntax and Semantics, and the Program Development Process Dale/Weems.
Chapter 2 C++ Syntax and Semantics, and the Program Development Process.
1 Chapter 3 Numeric Types, Expressions, and Output.
Chapter 3 Arithmetic Expressions, Function Calls, and Output
Input/Output Sujana Jyothi C++ Workshop Day 2. C++ I/O Basics 2 I/O - Input/Output is one of the first aspects of programming that needs to be mastered:
1 Chapter 3 Numeric Types, Expressions, and Output Dale/Weems/Headington.
1 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating float double long.
1 Chapter 2 C++ Syntax and Semantics, and the Program Development Process.
1 Chapter 4 Program Input and the Software Design Process Dale/Weems.
1 Chapter 4 Program Input and the Software Design Process Dale/Weems/Headington.
CHAPTER 2 C++ SYNTAX & SEMANTICS #include using namespace std; int main() { cout
1 Chapter 3 Numeric Types, Expressions, and Output Dale/Weems/Headington.
Chapter 4 Program Input and the Software Design Process.
1 What is a Named Constant? A named constant is a location in memory that we can refer to by an identifier, and in which a data value that cannot be changed.
1 Chapter 2 C++ Syntax and Semantics, and the Program Development Process Programming in C++
Chapter 3: Input/Output. Objectives In this chapter, you will: – Learn what a stream is and examine input and output streams – Explore how to read data.
1 Manipulators manipulators are used only in input and output statements endl, fixed, showpoint, setw, and setprecision are manipulators that can be used.
More about strings in C++. String member functions The next three slides present information about functions that are members of the C++ string class.
C++ Data Types Check sample values of? ‘4’
Chapter 3 Numeric Types, Expressions, and Output.
1 Chapter 4 Program Input and the Software Design Process.
Chapter 2 C++ Syntax and Semantics, and the Program Development Process Topics – Programs Composed of Several Functions – Syntax Templates – Legal C++
1 A Simple “Hello World” Example #include // input-output library using namespace std; int main() // function main { cout
1 Chapter 3 Numeric Types, Expressions, and Output Dale/Weems/Headington.
Chapter 3: Input/Output. Objectives In this chapter, you will: – Learn what a stream is and examine input and output streams – Explore how to read data.
Chapter 4 Program Input and the Software Design Process
Chapter 3 Numeric Types, Expressions, and Output
TK1913 C++ Programming Basic Elements of C++.
Chapter Topics The Basics of a C++ Program Data Types
Chapter 2 Topics Programs Composed of Several Functions
Lecture 2B Expressions Richard Gesick
Input and Output Chapter 3.
Input/Output Handouts: Quiz 2, Unit 3 practice sheets.
Chapter 4 Program Input and the Software Design Process
Chapter 2: Introduction to C++.
Dale/Weems/Headington Program Input and the Software Design Process
Presentation transcript:

CS221 C++ Basics

C++ Data Types structured array struct union class address pointer reference simple integral char short int long bool floating float double long double

C++ Simple Data Types simple types integralfloating char short int long bool float double long double unsigned

Standard Data Types in C++ Textbook pages Integral Types represent whole numbers and their negatives declared as int, short, or long Floating Types represent real numbers with a decimal point declared as float, or double Character Types represent single characters declared as char

What is a Variable? A variable is a location in memory that can be referred to by an identifier and in which a data value that can be changed is stored Declaring a variable means specifying both its name and its data type Textbook pages 36-38

What is a Constant? A named constant is a value that is assigned a data value that cannot be changed Valid constant declarations textbook pages const string STARS = “****” ; const float NORMAL_TEMP = 98.6; const char BLANK = ‘ ’ ; const int VOTING_AGE = 18; const float MAX_HOURS = 40.0;

What Does a Variable Declaration Do? A declaration tells the compiler to allocate enough memory to hold a value of this data type and to associate the identifier with this location int ageOfDog; float taxRate; char middleInitial ; 4 bytes for taxRateY2K1 byte for middleInitial

What is an Identifier? An identifier is the name used for a data object(a variable or a constant), or for a function, in a C++ program Beware: C++ is a case-sensitive language Using meaningful identifiers is a good programming practice Textbook pages 32-33

Identifiers An identifier must start with a letter or underscore, and be followed by zero or more letters (A-Z, a-z), digits(0-9), or underscores VALID age_of_dogtaxRateY2K PrintHeading ageOfHorse NOT VALID (Why?) age# 2000TaxRate Age-Of-Cat

Giving Values to a Variable Directly store a value using the assignment operator Input a value using the extraction operator

Assignment Operator Syntax 11 Variable = Expression Expression is evaluated Result is stored in variable Done first Done second

Extraction Operator(>>) Textbook pages Variable cin is predefined to denote an input stream from the standard input device (the keyboard) The extraction operator >> called “get from” takes 2 operands; the left operand is a stream expression, such as cin--the right operand is a variable of simple type Operator >> attempts to extract the next item from the input stream and to store its value in the right operand variable 12

What is an Expression in C++? An expression is a valid arrangement of variables, constants, and operators In C++ each expression can be evaluated to compute a value of a given type The value of the expression is 14

Operators can be binaryinvolving 2 operands x + 1 unaryinvolving 1 operand x ++ Textbook pages 73-77

Some C++ Operators Precedence OperatorDescription Higher ( )Function call Quantity +Positive - Negative *Multiplication / Division % Modulus( remainder) +Addition - Subtraction Lower = Assignment

Precedence Higher Precedence determines which operator is applied first in an expression having several operators

7 * % 3 * (7 * 10) - 5 % 3 * % 3 * (5 % 3) * * ( 2 * 4) ( ) Evaluate the Expression

Parentheses Parentheses can be used to change the usual order Parts in() are evaluated first Evaluate ( 7 *(10 - 5) % 3) * (7 * 5 % 3 ) * ( 35 % 3) * *

Modulus Operator The modulus operator % can only be used with integer type operands and always has an integer type result Its result is the integer type remainder of an integer division Example 11 % 4 has value 3 because ) 4 11 R = ?

Increment Operator 8 int age; age = 8; age++; age 9

Decrement Operator 100 int dogs; dogs = 100; dogs--; dogs 99 dogs

PLUS/MINUS EQUALS Operator 100 int dogs; dogs = 100; dogs=dogs + 5; //or dogs+=5; dogs=dogs - 5; //or dogs-=4; dogs 105 dogs 101 Combines plus/minus with assignment!!

More About Floating Point Values Floating point numbers have an integer part and a fractional part, with a decimal point in between. Either the integer part or the fractional part, but not both, may be missing Examples Alternatively, floating point values can have an exponent, as in scientific notation--the number preceding the letter E doesn’t need to include a decimal point Examples 1.84E1 5E2 8E E3

Scientific Notation 2.7E4 means 2.7 x 10 4 = = E-4 means 2.7 x = =

Pitfall : Integer Division The result of the division operator depends on the type of its operands If one or both operands has a floating point type, the result is a floating point type. Otherwise, the result is an integer type Examples 11 / 4 has value / 4.0 has value / 4.0 has value 2.75

Variable = Expression First, Expression on right is evaluated Then the resulting value is stored in the memory location of Variable on left NOTE: An automatic type coercion occurs after evaluation but before the value is stored if the types differ for Expression and Variable Recall Assignment Operator Syntax

What value is stored? float a; float b; a = 8.5; b = 9.37; a = b; a b a b a b ? ?

What is stored? ? float someFloat; someFloat someFloat = 12; // Causes implicit type conversion someFloat 12.0

What is stored? ? int someInt; someInt someInt = 4.8; // Causes implicit type conversion someInt 4

Type Casting is Explicit Conversion of Type int(4.8) has value4 float(5)has value5.0 float(7/4)has value1.0 float(7) / float(4)has value1.75 Textbook pages 79-81

Some Expressions int age; ExampleValue age = age / / float(4 / 8)0.0 float(4) / 80.5 cout << “How old are you?” cout cin >> agecin cout << agecout

Functions Every C++ program must have a function called main Program execution always begins with function main Any other functions are subprograms and must be called Textbook pages 26-28

Function Calls One function calls another by using the name of the called function together with () containing an argument list A function call temporarily transfers control from the calling function to the called function

More About Functions It is not considered good practice for the body block of function main to be long Function calls are used to do subtasks Every C++ function has a return type If the return type is not void, the function returns a value to the calling block

Where are functions? Functions are subprograms located in libraries, or written by programmers for their use in a particular program

HEADER FILE FUNCTION EXAMPLE VALUE OF CALL fabs(x) fabs(-6.4) 6.4 pow(x,y) pow(2.0,3.0) 8.0 sqrt(x) sqrt(100.0) 10.0 setprecision(n) setprecision(3) log(x) log(2.0) sqrt(x) sqrt(2.0) abs(i) abs(-6) 6

Write C++ Expressions for The square root of b 2 - 4ac sqrt(b * b * a * c) The square root of the average of myAge and yourAge sqrt((myAge + yourAge) / 2.0)

Function Call A function call temporarily transfers control to the called function’s code When the function’s code has finished executing, control is transferred back to the calling block

FunctionName ( Argument List ) The argument list is a way for functions to communicate with each other by passing information The argument list can contain zero, one, or more arguments, separated by commas, depending on the function Function Call Syntax

A void function call stands alone #include void DisplayMessage(int n); // Declares function int main() { DisplayMessage(15); // Function call cout << “Good Bye“ << endl; return 0; }

A void function does NOT return a value // Header and body here void DisplayMessage(int n) { cout << “I have liked math for “ << n << “ years” << endl; }

Two Kinds of Functions Always returns a single value to its caller and is called from within an expression Never returns a value to its caller and is called as a separate statement Value-Returning Void 42

C++ Data Type String A string is a sequence of characters enclosed in double quotes Sample string values “Hello” “Year 2000” “1234” The empty string(null string)contains no characters and is written as “” Textbook pages 34-35

String Class #include // include the string library …. string name; cin >> name; cout << “Your name is: “; cout << name;

length or size Function length returns an unsigned integer value that equals the number of characters currently in the string Function size returns the same value as function length int length; length = name.length();

String Functions Besides length, there are many other functions to manipulate strings. See: string/string/ You will be shown examples for any string functions you will need for programs Textbook pages 94-97

> They can be chained: int age; string firstname, major; cout >> “Enter your age: “; cin >> age; cout << “You are “ << age << “ years old”<< endl; // endl “ends the line” next output will be on line below cout << “enter your first name and major: “ << endl; cin>> firstname >> major;

Output Statements SYNTAX These examples yield the same output cout << “The answer is “; cout << 3 * 4; cout << “The answer is “ << 3 * 4; cout << Expression << Expression...;

49 Example string message; cin >> message; cout << message; However... String Input in C++ Input of a string is possible using the extraction operator >>

50 String Input Using >> string firstName; string lastName; cin >> firstName >> lastName; Suppose input stream looks like this: Joe Hernandez 23 (squares represent spaces) What are the string values?

51 Results Using >> string firstName; string lastName; cin >> firstName >> lastName; Result “Joe” “Hernandez” firstName lastName

52 >> Operator with Strings Using the extraction operator(>>) to read input characters into a string variable The >> operator skips any leading whitespace characters such as blanks and newlines It then reads successive characters into the string, and stops at the first trailing whitespace character(which is not consumed, but remains waiting in the input stream)

Extraction Operator >> >> “skips over” (actually reads but does not store anywhere) leading white space characters as it reads your data from the input stream(either keyboard or disk file) >> does not read or store any trailing white space or newlines 53

Whitespace Characters Include... blanks tabs end-of-line(newline) characters The newline character is created by hitting Enter or Return at the keyboard, or by using the manipulator endl or “\n” in a string: Cout << “next output printed below this line\n”; \n means insert a new line character here 54

Interactive I/O In an interactive program the user enters information while the program is executing Before the user enters data, a prompt should be provided to explain what type of information should be entered The amount of information needed in the prompt depends on the complexity of the data being entered, and the sophistication of the person entering the data 55

Prompting for Interactive I/O // Pattern: cout(prompt) cin(read value) cout << “Enter part number : “ << endl; cin >> partNumber; cout << “Enter quantity ordered : “ << endl; cin >> quantity; cout << “Enter unit price : “ << endl; cin >> unitPrice; // Calculate and print results totalPrice = quantity * unitPrice; cout << “Part # “ << partNumber << endl; cout << “Quantity: “ << quantity << endl; cout << “Unit Cost: $ “ << setprecision(2) << unitPrice << endl; cout << “Total Cost: $ “ << totalPrice << endl; 56

Presentation of Output To present output in a pleasing manner (for example decimal numbers that always have a certain number of digits to the right of the decimal point) C++ has manipulators The following slides discuss techniques used to present data You may be required to use them in your programs, but They will not be quiz questions

Using Manipulators Fixed and Showpoint use the following statement once at the beginning of your code specify that output sent to the cout stream will be in decimal format, not scientific notation Also specifies that a decimal point be included cout << fixed << showpoint; Textbook pages 86-90

setprecision(n) Requires #include and appears in an expression using insertion operator(<<) If fixed has already been specified, argument n determines the number of places displayed after the decimal point for floating point values Remains in effect until explicitly changed by another call to setprecision

What is exact output? #include // For setprecision() #include using namespace std; int main() { float myNumber = ; cout << fixed << showpoint; // Use decimal format // Print decimal points cout << “Number is ” << setprecision(3) << myNumber << endl; return 0; }

OUTPUT Number is Value is rounded if necessary to be displayed with exactly 3 places after the decimal point

Manipulator setw “Set width” lets us control how many character positions the next data item should occupy when it is output setw is only for formatting numbers and strings, not char type data

setw(n) Requires #include and appears in an expression using insertion operator(<<) Argument n is called the fieldwidth specification, and determines the number of character positions in which to display a right-justified number or string(not char data); the number of positions used is expanded if n is too narrow “Set width” affects only the very next item displayed and is useful to align columns of output

What is exact output? #include // For setw() #include using namespace std; int main() { int myNumber = 123; int yourNumber = 5; cout << setw(10) << “Mine” << setw(10) << “Yours” << endl << setw(10) << myNumber << setw(10) << yourNumber << endl; return 0; }

Output Mine Yours Each is displayed right-justified and each is located in a total of 10 positions position

What is exact output? #include // For setw() and setprecision() #include using namespace std; int main() { float myNumber = 123.4; float yourNumber = ; cout << fixed << showpoint; // Use decimal format; print decimal points cout << “Numbers are: ” << setprecision(4) << endl << setw(10) << myNumber << endl << setw(10) << yourNumber << endl; return 0; }

OUTPUT Numbers are: Each is displayed right-justified and rounded if necessary and each is located in a total of 10 positions with 4 places after the decimal point

float x = 312.0; float y = 4.827; cout << fixed << showpoint; OUTPUT cout << setprecision(2) << setw(10) << x << endl ’’’’ << setw(10) << y << endl; ’’’’’’ 4.83 cout << setprecision(1) << setw(10) << x << endl ’’’’’ << setw(10) << y << endl; ’’’’’’’ 4.8 cout << setprecision(5) << setw(7) << x << endl << setw(7) << y << endl; More Examples x y

HEADER MANIPULATOR ARGUMENT EFFECT FILE TYPE showpoint none displays decimal point fixed none suppresses scientific notation setprecision(n) int sets precision to n digits setw(n) int sets fieldwidth to n positions endl none terminates output line

char first; char middle; char last; cin >> first ; cin >> middle ; cin >> last ; NOTE: A reading marker is still pointing to the trailing newline character in the input stream firstmiddlelast At keyboard you type: A [ space]B [ space ] C [ Enter] firstmiddlelast ‘A’‘B’‘C’ 70

At keyboard you type: [ space ] 25 [ space ] J [ space]2 [ En ter ] int age; char initial; float bill; cin >> age; cin >> initial; cin >> bill; NOTE: A reading marker is still pointing to the trailing newline character in the input stream ageinitialbill ageinitialbill 25‘J’2.0 71

Keyboard and Screen I/O #include cin (of type istream) cout (of type ostream) KeyboardScreen executing program input data output data 72

STATEMENTS CONTENTS MARKER POSITION int i; 25 A\n char ch; 16.9\n float x; cin >> i; 25 A\n 16.9\n cin >> ch; 25 A\n 16.9\n cin >> x; 25 A\n 16.9\n Another example using >> ichx 25 ‘A’ ichx i x i x ‘A’ NOTE: shows the location of the reading marker 73

The get() function can be used to read a single character. It is a method of istream objects, so the dot operator is used. Textbook pages get() obtains the very next character from the input stream without skipping any leading white space characters Another Way to Read char Data

char first; char middle; char last; cin.get(first); cin.get(middle); cin.get(last); NOTE: The reading marker is now pointing to the space after the ‘B’ in the input stream firstmiddlelast At keyboard you type: A [ space]B [ space ] C [ Enter] firstmiddlelast ‘A’‘ ’‘B’ 75

Use function ignore() to skip characters The ignore() function is used to skip(read and discard) characters in the input stream. It is also a method of istream objects.Textbook pgs The call cin.ignore(howMany, whatChar); will skip over up to howMany characters or until whatChar has been read, whichever comes first

An Example Using cin.ignore() abc abc abc abc NOTE: shows the location of the reading marker STATEMENTS CONTENTS MARKER POSITION int a; \n int b; \n int c; cin >> a >> b; \n \n cin.ignore(100, ‘\n’); \n \n cin >> c; \n \n 77

Another Example Using cin.ignore() ich ich i i 16‘A’ NOTE: shows the location of the reading marker STATEMENTS CONTENTS MARKER POSITION int i; A 22 B 16 C 19\n char ch; cin >> ch; A 22 B 16 C 19\n cin.ignore(100, ‘B’); A 22 B 16 C 19\n cin >> i; A 22 B 16 C 19\n 78

79 getline() Function Because the extraction operator stops reading at the first trailing whitespace, >> cannot be used to input a string with blanks in it Use the getline function with 2 arguments to overcome this obstacle (not an istream method) First argument is an input stream variable, and second argument is a string variable Example textbook page 118 string message; getline(cin, message);

80 getline(inFileStream, str) getline does not skip leading whitespace characters such as blanks and newlines getline reads successive characters(including blanks) into the string, and stops when it reaches the newline character ‘\n’ The newline is consumed by getline, but is not stored into the string variable

81 String Input Using getline string firstName; string lastName; getline(cin, firstName); getline(cin, lastName); Suppose input stream looks like this: Joe Hernandez 23 What are the string values?

82 Results Using getline “ Joe Hernandez 23” ? firstName lastName string firstName; string lastName; getline(cin, firstName); getline(cin, lastName);