CSEC1003 - Secure Coding Lecture 02 Variables and Operators PDF

Summary

This document is a lecture on C++ variables and operators. It covers the fundamentals of C++ programming, including different types of variables, integer and floating point types, and common operations. The lecture is titled "CSEC1003 - Secure Coding Lecture 02 Variables and Operators." and notes were taken at De Montfort University, Leicester .

Full Transcript

CSEC1003 - Secure Coding Lecture 02 Variables and Operators 1 Agenda What is Programming? What happens when we Run a Program? Variables Data Types Operators Strings Constants Reserved Words  A computer p...

CSEC1003 - Secure Coding Lecture 02 Variables and Operators 1 Agenda What is Programming? What happens when we Run a Program? Variables Data Types Operators Strings Constants Reserved Words  A computer program is a sequence of instructions which perform a task  We call these sets of instructions algorithms  A written or verbal set of a logical sequence of instructions  Typically algorithms are made up of three structural components:  Sequence  Step 1 happens before step 2 which happens before step 3  Selection  Sometimes a choice has to be made between two or more options  This can lead to the algorithm having branches  Iteration  The repeating of an instruction or a sequence of instructions  Can stop after a set number or on a certain condition  You can use these in combination to solve nearly all  Algorithm design example:  A company wishes to calculate how much pay to give each employee each week  Employees are employed on different hourly of pay  They receive this rate for all hours up to 37.5 hours a week  Any additional hours are paid at time and a half  What would the algorithm look like?  Algorithm design example:  A company wishes to calculate how much pay to give each employee each week  Employees are employed on different hourly of pay  They receive this rate for all hours up to 37.5 hours a week  Any additional hours are paid at time and a half  What would the algorithm look like?  Look up the employees hourly rate of pay  Determine the number of hours worked by the employee that week  If the hours worked is less than or equal to 37.5  Pay due is hourly rate multiplied by the number of hours worked  If the hours worked is more than 37.5  Regular pay due is hourly rate multiplied by 37.5  Overtime pay due is the difference between the hours worked above 37.5 multiplied by hourly rate multiplied by 1.5  Pay due is regular pay plus overtime pay  So we:  Identify a problem  Write an algorithm to solve that problem  Code the algorithm up  Compile it  Run  What happens when we run the program?  The compiled program is loaded into the computer memory – the RAM  The code is executed using the fetch-execute cycle on the CPU  Memory called the heap then holds program managed memory  Memory called the stack handles OS managed memory, growing and shrinking as the program runs  We know computers have memory - RAM  Variables are required when we (programmer) wants to store data in a computers memory  We give all our variables names which refer to the values in memory  In C++ all variables have a type  Type is a critical concept to understand  Different types can hold different types of data  You can perform different operations of different types of data  Today we are looking the key types available in C++  As you will see later in the year we can create our own types  We have to decide:  What variables we need  What types those variables should have  Say we are building a student records program we might want:  Pnumber  First Name  Last Name  Telephone number  Course  Year one grade  Each of these would be a variable  We need to decide what kind of data they will hold:  Numbers – integers or real  Text – one character or a string of characters  Logical – true or false   Integers – whole numbers (no decimal places)  Five types:  char – holds a single character (encode in ASCII)  int – holds an integer  short – holds a small integer  long – holds a long integer  bool – holds a Boolean value 0 or 1 (0 means false, 1 means true)  We can set each of these (except bool) to allow or not allow negative numbers  Signed numbers can be negative  Unsigned numbers cannot be negative  Each type uses a different amount of memory and can hold a different range of values depending on the computer  From Type Dale and Weens Size in 1 : Min value Max value bytes bool 1 0 1 char 1 -128 127 unsigned char 1 0 255 short 2 -32768 32767 unsigned short 2 0 65535 int 4 -2147483648 24147483647 unsigned int 4 0 4294967295 long 8 - 92233720368547758 9223372036854775 07 808 unsigned 1. long Programming 8 Solving with C++, Nell and Problem 0 Dale and Chip 18446744073709551 Weens 615  Declaring  We must declare (the computer about) any variables before we use them: bool booleanVariable; // A boolean called booleanVariable char charVariable; // A character called charVariable Unsigned char uCharVariable; // An unsigned character called uCharVariable short shortVariable; // A short integer called shortVariable Unsigned short uShortVariable; // An unsigned short integer called uShortVariable int intVariable; // An integer called intVariable Unsigned int uIntVariable; // An unsigned integer called uIntVariable int longVariable; // A long integer called longVariable Unsigned int uLongVariable; // An unsigned long integer called ulongVariable  Floating point – real numbers (with decimal places)  Three types:  Float  double  long double  Ranges from Dale and Weens: Type Size in Min value Max value 3.4 × 10−38 3.4 × 10+38 bytes float 4 double 8 1.7 × 10−308 1.7 × 10+308 long double 10 3.4 × 10−4932 3.4 × 10+4932  Floating point representation are always an approximation  They are plenty good enough for everything we will do float floatVariable; // A single precision floating point number called floatVariable double doubleVariable; // A double precision floating point number called doubleVariable long double longDoubleVariable; // A long double precision floating point number called longDoubleVariable  Assignment = (single equals)  Assigns a value to a variable  With all operators the variable must be declared first  The values that can be assigned depend on the types int age; // A persons age float height; // A persons height in metres char gender; // A person gender M or F bool footballFan; // Is the person a football fan age = 34; height = 1.82; gender = 'M'; footballFan = true;  Arithmetic  Unary operators  Only take one variable  + (plus sign)  - (minus sign)  When placed in front of a numeric variable they set a positive or negative value  Positive does not have to be written explicitly float heading; // Direction of an aeroplane in degrees int airspeed; // Speed pf an aeroplane in knots heading = -110.5; airspeed = +550; // Could write: airspeed = 500;  Arithmetic  Binary operators  Only take two variables, one either side of the symbol  + addition (plus sign)  - subtraction (minus sign)  * multiplication (asterisk)  / division (forward slash)  For floating point number we get a decimal part  For integers we do not get decimal part  If you divide by zero your program will crash  % modulus (percent)  Remainder from integer division  Addition, subtraction and multiplication: int salary; int doubleSalary; int tripleSalary; int quadrupleSalary; salary = 22000; tripleSalary = salary * 3; // 66000 doubleSalary = tripleSalary - salary; // 44000 quadrupleSalary = doubleSalary + doubleSalary; // 88000  Floating point division: float speed; float time; float distance; speed = 25.65; time = 3.8; speed = distance / time; // 6.75  Division and modulus: int numberOfApples; int numberOfPeople; int numberOfApplesEach; int numberOfApplesLeft; numberOfApples = 11; numberOfPeople = 3; numberOfApplesEach = numberOfApples / numberOfPeople; // 3 numberOfApplesLeft = numberOfApples % numberOfPeople; // 2  Increment and decrement:  Add or take away one from a variable int count; count = 0; count = count + 1; // 1 count++; // 2 count--; // 1  These are called postfix (they are written after the variable name)  We look at prefix (before the variable name when we look at loops)  Compound arithmetic expressions  More than one operation in one line  Operators have precedence (like BIDMAS)  Highest: unary +, unary –  Middle: * / %  Lowest : + -  So average speed: float initialSpeed = 25.0; float finalSpeed = 75.0; float averageSpeed1 = initialSpeed + finalSpeed / 2; // ? float averageSpeed2 = (initialSpeed + finalSpeed) / 2; // ?  Compound arithmetic expressions  More than one operation in one line  Operators have precedence (like BIDMAS)  Highest: unary +, unary –  Middle: * / %  Lowest : + -  So average speed: float initialSpeed = 25.0; float finalSpeed = 75.0; float averageSpeed1 = initialSpeed + finalSpeed / 2; // 62.5 float averageSpeed2 = (initialSpeed + finalSpeed) / 2; // 50  Mixing integer and floating numbers  BE VERY CAREFUL!  Type coercion  Floating point types can only hold floating point types  Integer types can only hold integer types  The compiler will change the type and may not tell you! int angle = angle * 0.5; // float angle = 45; 0// 45.0 int sum = 12.0; // 12 int count = 32.0; // 32 float average = sum / count; // 0  Mixing integer and floating numbers  BE VERY CAREFUL!  Type casting  You can change the type of integers and variables at run time  This is called casting  Will forget this and it will cause you problems float angle1 = 45; // 45.0 int angle2 = angle1 * 4; // 180 int angle3 = int(angle1) * 4; // 180 int sum = 12.0; // 12 int count = 32.0; // 32 float average = float(sum) / float(count); // 0.375  Enums  Useful when you wish to hold one value from a set of choices  Traffic Light:  Red  Amber  Green  An enum allows you to set these options  Must be declared before you use them enum taffic_light {red,amber, green}; traffic_light signal = green;  Each option is represented by a unique integer value in the compiler  A string of characters – a piece of text  We will cover strings in much more detail later in the year  Things you need to know now: #include // For cin, cout #include // For string type using namespace std; // To remove the std:: qualifier int main() { string firstName; // First name string lastName; // Last name string welcomeMsg; // A simple message int age; // Age welcomeMsg = "Hello and welcome to my program"; cout lastName; cout

Use Quizgecko on...
Browser
Browser