Programmer-defined Data Types

Programmer-defined Data Types

#include <iostream> //for input output (IO) key words

using namespace std; // grant access to IO defs

Int main() // required in every C++ program

{

Int age; //hold student age

Cout << "Enter age: "; //prompt user for age

Cin >> age; // save value of age (20)

Cout >> "your age is " << age; // your age is 20

Return 0; //stop

}

 

 

 

String - character sequences like "hello", "C++ is easy"

  • Not just letters, its characters

  • 'A', '2', one character value goes in single quotes

  • Single quotes and double quotes are constraints, you need a string header file

    • If you want to use strings you have to have the header file string

      • Header files define things ex) #include <iostream>

 

String firstName

  • We can make the following assignments

firstName = "Cory";

fristName = "Susan"

 

You can also declare string constants:

const string BOOK_TITLE = "PROGRAMMING IN C++";

const int MAX_HOURS = 40; //can not change the value

 

Int age;

Age = 10 //can be changed

 

String Concentration

We can concentrate (join) two strings using the operator +

 

String bookTitle;

String phrase1 = "programming and ";

String phrase2 = "problem Solving";

 

Then the instruction using concatenation

bookTitle = phrase1 + phrase2

 

Assigns "Programming and Problem Solving" to bookTitle.

  • So If working with string files + does not mean addition

 

Arithmetic Expressions

  • Calculating the values of numeric data types is done with expressions

  • Simple expressions using +, - and * include:

    • 4 + 2, grossPay - Tax, price*1.15

    • Both constants and variables can be used

  • Division / is special since the result depends on the data type of the two operands

    • Floating - point division: 7.0/2.0 gives 3.5

    • Integer division: 7/2 gives 3

    • What if we want the reminder of integer division?

      • Th modulus operator % is used for this purpose

      • Modulus: 7%2 gives 1.

 

3.4-6.1=-2.7

8/2=4

8.0/2.0=4.0

8/7=1

8/9=0

8%7=1

8%9=8

8%8=0

 

Stress = pressure/temp;

  • What are the data types

  • If one is a float then the output will be float

 

Precedence Rules

Consider the following instruction:

Avgheight = shortest+tallest/2.0

How does the computer know to evaluate the expression?

The expression is evaluated based on the precedence of the operations

Highest precedence: unary -

Middle precedence: */%

Lowest precedence: +-

 

How is the above instruction evaluated?

avgHeight=shortest+(tallest/2.0);

But that’s not what we wanted

  • Rewrite using ()

avgHeight = (shortest+tallest)/2.0

What if the arithmetic operators have the same precedence?

  • Then you group left to right

Answer = 1-2+3

What is the value of the answer?

  • Since - and + have same precedence, we we group the precedence as:

Answer = (1-2)+3

Thus, answer is 2 and not -4.