Exposure C++ Chapter V Variables and Constants The Limitation of Constants // PROG0501.CPP // This program demonstrates using four constants. #include.

Slides:



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

 2005 Pearson Education, Inc. All rights reserved Introduction.
Variables Pepper. Variable A variable –box –holds a certain type of value –value inside the box can change Example –A = 2B+1 –Slope = change in y / change.
Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types.
Chapter 3 Assignment and Interactive Input. 2 Objectives You should be able to describe: Assignment Operators Mathematical Library Functions Interactive.
1 Lecture-4 Chapter 2 C++ Syntax and Semantics, and the Program Development Process Dale/Weems/Headington.
Computer Science 1620 Other Data Types. Quick Review: checklist for performing user input: 1) Be sure variable is declared 2) Prompt the user for input.
Data types and variables
Libraries Programs that other people write that help you. #include // enables C++ #include // enables human-readable text #include // enables math functions.
Chapter 2 Data Types, Declarations, and Displays
Introduction to C Programming
Chapter 3: Introduction to C Programming Language C development environment A simple program example Characters and tokens Structure of a C program –comment.
Basic Elements of C++ Chapter 2.
Exposure C++ Chapter IV Introduction to C++ Programs.
CHAPTER 4: INTRODUCTION TO COMPUTER ORGANIZATION AND PROGRAMMING DESIGN Lec. Ghader Kurdi.
Chapter 2 Data Types, Declarations, and Displays.
Objectives You should be able to describe: Data Types
Operaciones y Variables
C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved Slides by Evan Gallagher Fundamental Data Types 09/09/13.
Introduction to Python
PYTHON: PART 2 Catherine and Annie. VARIABLES  That last program was a little simple. You probably want something a little more challenging.  Let’s.
Exposure C++ Chapter VII Program Input and Output.
The Java Programming Language
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.
Chapter 3 Processing and Interactive Input. 2 Assignment  The general syntax for an assignment statement is variable = operand; The operand to the right.
CNG 140 C Programming Lecture Notes 2 Processing and Interactive Input Spring 2007.
A First Book of ANSI C Fourth Edition Chapter 3 Processing and Interactive Input.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
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.
CPS120: Introduction to Computer Science
Summary of what we learned yesterday Basics of C++ Format of a program Syntax of literals, keywords, symbols, variables Simple data types and arithmetic.
Chapter 2. C++ Program Structure C++ program is a collection of subprograms Subprograms in C++ are called FUNCTIONS Each function performs a specific.
Knowledge Base C++ #include using std namespace; int main(){} return 0 ; cout
1 INTRODUCTION TO PROBLEM SOLVING AND PROGRAMMING.
Java Data Types Assignment and Simple Arithmetic.
6/3/2016 CSI Chapter 02 1 Introduction of Flow of Control There are times when you need to vary the way your program executes based on given input.
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 
C++ Basics C++ is a high-level, general purpose, object-oriented programming language.
Exposure C++ Chapter VI Data Type Operations C++ Integer Operations Symbols +Addition -Subtraction *Multiplication /Integer division %Modulus or Remainder.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
© 2004 Pearson Addison-Wesley. All rights reserved ComS 207: Programming I Instructor: Alexander Stoytchev
CHAPTER # 2 Part 2 PROGRAMS AND DATA 1 st semster King Saud University College of Applied studies and Community Service CSC1101 By: Asma Alosaimi.
Chapter 2: Introduction to C++. Language Elements Keywords Programmer-defined symbols (identifiers) Operators Punctuation Syntax Lines and Statements.
Chapter 4 Literals, Variables and Constants. #Page2 4.1 Literals Any numeric literal starting with 0x specifies that the following is a hexadecimal value.
Introduction to Python Dr. José M. Reyes Álamo. 2 Three Rules of Programming Rule 1: Think before you program Rule 2: A program is a human-readable set.
Variables and Constants Objectives F To understand Identifiers, Variables, and Constants.
9/29/99B-1 CSE / ENGR 142 Programming I Variables, Values, and Types © 1998 UW CSE.
PROGRAM ESSENTIALS. TOKENS  SMALLEST UNITS OF A PROGRAM LANGUAGE  Special Symbols  Mathematical Operators  Punctuation  Word Symbols  Key Words.
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.
CS201 Introduction to Sabancı University 1 Chapter 2 Writing and Understanding C++ l Writing programs in any language requires understanding.
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.
1 C Syntax and Semantics Dr. Sherif Mohamed Tawfik Lecture Two.
Bill Tucker Austin Community College COSC 1315
Chapter # 2 Part 2 Programs And data
Basic concepts of C++ Presented by Prof. Satyajit De
Chapter 4 – C Program Control
Chapter Topics The Basics of a C++ Program Data Types
Chapter 3 Assignment and Interactive Input.
Basic Elements of C++.
Variables and Primative Types
Basic Elements of C++ Chapter 2.
Variables In programming, we often need to have places to store data. These receptacles are called variables. They are called that because they can change.
Introduction to C++ Programming
Chapter 2: Java Fundamentals
Chapter # 2 Part 2 Programs And data
CS150 Introduction to Computer Science 1
Fundamental Programming
COMS 261 Computer Science I
Presentation transcript:

Exposure C++ Chapter V Variables and Constants

The Limitation of Constants // PROG0501.CPP // This program demonstrates using four constants. #include void main() { cout << 2500 << endl; cout << << endl; cout << 'M' << endl; cout << "Howdy Neighbors" << endl; }

Defining and Assigning Variables Variable Definition Syntax datatype Variable Identifier // optional. but desired comment int Number; char Choice;

// PROG0502.CPP // This program introduces integer, character and real number // variables. This program also demonstrates the use of an // assignment operator. #include void main() { int Var1; // integer variable char Var2; // character variable float Var3; // real number (floating point) variable Var1 = 5000; // integer assignment Var2 = 'A'; // character assignment Var3 = ; // real number assignment cout << Var1 << endl; cout << Var2 << endl; cout << Var3 << endl; } PROG0502.CPP OUTPUT 5000 A

// PROG0503.CPP // This program demonstrates that C++ is case sensitive. #include void main() { int Var1; // integer variable char Var2; // character variable float Var3; // real number (floating point) variable Var1 = 5000; // integer assignment Var2 = 'A'; // character assignment Var3 = ; // real number assignment cout << var1 << endl; cout << var2 << endl; cout << var3 << endl; } DOES NOT COMPILE AND GIVES ERROR MESSAGES LIKE: Compiling PROG0503.CPP Error PROG0503.CPP 18: Undefined symbol 'var1' Error PROG0503.CPP 18: Undefined symbol 'var2' Error PROG0503.CPP 18: Undefined symbol 'var3'

Important Warning About Case Sensitivity C++ is case sensitive This means that GrossPay and grosspay are two completely different identifiers to a C++ compiler.

The Assignment Operator The two previous program examples included the program statements below. At first glance it may appear like an equation because the equality = sign is used. The program statement Var1 = 5000; certainly looks like an equation. It is tempting to "Var1 equals 5000". Saying equals will not really confuse people who understand C++ programming, but it is more correct to say something like: Var1 gets 5000 Var1 becomes is assigned to Var1 Var1 = 5000;// integer assignment Var2 = 'A';// character assignment Var3 = ;// real number assignment

// PROG0504.CPP // This program demonstrates that the assignment operator can be // used for evaluating mathematical expressions. The program also // shows program output that mixes constants with variables. #include void main() { int N1 = 10, N2 = 20, N3 = 30; cout << N1 << " " << N2 << " " << N3 << endl; N1 = ; N2 = ; N3 = ; cout << endl; cout << N1 << " " << N2 << " " << N3 << endl; N1 = N ; N2 = N ; N3 = N1 + N2; cout << endl; cout << N1 << " " << N2 << " " << N3 << endl; } PROG0504.CPP OUTPUT

Assignment Operator Syntax Variable = Expression Rate = 8.765; Sum = X + 13; Total = N1 + N2 + N3;

Wrong Assignment Operator Syntax Do not switch the left and right side of an assignment operator. The following examples will not work: = Rate; X + 13 = Sum; N1 + N2 + N3 = Total;

// PROG0505.CPP // This program demonstrates that the assignment // operator is not an equal sign. // An assignment statement is not an equation. #include void main() { int Number = 1000; cout << Number << endl; cout << endl; Number = Number + 100; cout << Number << endl; Number = Number + Number; cout << endl; cout << Number << endl; } PROG0505.CPP OUTPUT

The program examples you have seen so far have been logical. Logical in the sense that only integer values were assigned to int variables, characters to char variables, and real numbers to float variables. You might, without realizing it, assign values to the wrong variables. Will the compiler catch such a mistake? If the compiler does not catch it, what is going to happen? These are good questions and program PROG0506.CPP is designed precisely to answer these questions. This next program example does some pretty bizarre stuff. You will see a letter character assigned to an int variable, a number assigned to a char variable, and a variety of other peculiar assignments that all seem to violate proper assignment practice. Make sure to follow the assignment advise on the next page. Mixing Data Types

When in doubt assign like data types, such as: int X, Y; char Letter1, Letter2; X = 10; Y = X; X = X + Y; Letter1 = 'A'; Letter2 = Letter1; Only mix data type assignments when this serves a specific purpose, and you know the result of the assignment. Assignment Advice

// PROG0506.CPP // This program demonstrates that it is possible to mix data types. #include void main() { int IntVar; char CharVar; float FloatVar; IntVar = 'A'; CharVar = 65; FloatVar = 25; cout << "IntVar = 'A' " << IntVar << endl; cout << "CharVar = 65 " << CharVar << endl; cout << "FloatVar = 25 " << FloatVar << endl; IntVar = ; CharVar = 'A' + 5; FloatVar = 'B'; cout << endl; cout << "IntVar = " << IntVar << endl; cout << "CharVar = 'A' + 5 " << CharVar << endl; cout << "FloatVar = 'B' " << FloatVar << endl; } PROG0506.CPP OUTPUT IntVar = 'A' 65 CharVar = 65 A FloatVar = IntVar = CharVar = 'A' + 5 F FloatVar = 'B' 66

Save Advice Always save your programs before you try to compile/execute. Sooner or later you will find that the computer "locks up" and requires rebooting. Rebooting a computer means the loss of data that is stored temporarily in computer memory, RAM. The programs you write are data that is stored temporarily in memory. Unless you acquire a habit to store your program permanently on a hard drive, diskette or network, you run the risk of losing many hours or computer work.

Initialized Variables In some of the previous programs you have seen program statements like: X = X + 4; This type of statement assumes an initial value for X. The CPU finds the value for X, adds 4 to this value and returns the sum to the memory location of X. Clean and simple, right? True, but what if there is no initial value for X? What will the CPU do?

// PROG0507.CPP // This program demonstrates how to define and initialize a // variable in the same statement. #include void main() { int IntVar1 = 25; int IntVar2 = 50; char CharVar1 = '#'; char CharVar2 = '$'; cout << IntVar1 << " " << IntVar2 << endl; cout << CharVar1 << " " << CharVar2 << endl; IntVar1 = IntVar ; IntVar2 = IntVar ; CharVar1 = '1'; CharVar2 = '2'; cout << endl << endl; cout << IntVar1 << " " << IntVar2 << endl; cout << CharVar1 << " " << CharVar2 << endl; } PROG0507.CPP OUTPUT # $

Program Sequence How does the computer know what to execute, and when to do the execution of program statements? The answer is sequence. The program is executed in the precise sequence of the program statements created by the programmer.

// PROG0508.CPP // This program demonstrates that program execution is // controlled by program statement sequence. #include void main() { int IntNumber; float FloatNumber; cout << "IntNumber = " << IntNumber << endl; IntNumber = 2500; cout << "IntNumber = " << IntNumber << endl; IntNumber = 5000; cout << "FloatNumber = " << FloatNumber << endl; FloatNumber = ; cout << "FloatNumber = " << FloatNumber << endl; FloatNumber = ; } PROG0508.CPP ACTUAL OUTPUT IntNumber = 2418 IntNumber = 2500 FloatNumber = e-11 FloatNumber =

There certainly is something wrong with the output of PROG0508.CPP. Perhaps you had expected a program output more along the following lines. PROG0508.CPP EXPECTED OUTPUT IntNumber = 2500 IntNumber = 5000 FloatNumber = FloatNumber =

The problem is best explained by focusing on the following first five program statements extracted from the program: int IntNumber; float FloatNumber1; clrscr(); cout << "IntNumber = " << IntNumber << endl; IntNumber = 2500;

The first three program statement cause no problem. With the very next statement the value of IntNumber is supposed to be displayed. The CPU once again has no problem with that instruction. There exists a memory location for IntNumber and the CPU takes a peek in the memory to determine the value, and then displays the value. Now there will be a value in the memory location for IntNumber. Every BIT in memory has the value of 0 or 1 and combinations of 16 bits are used to store an integer. My computer happened to find 2418, which is surprisingly close to 2500, but the value could be anything. You will probably get a different value on your computer. At this point many students object. You may be one of these students. You object on the ground that the program clearly shows the value 2500 being assigned to IntNumber. You are right, but the problem is that the assignment occurs after the output statement. You see, incorrect program sequence is the problem here.

// PROG0509.CPP // This is another example that demonstrates why you must use // correct program sequence. This program does not compile. #include void main() { cout << "IntNumber = " << IntNumber << endl; IntNumber = 2500; cout << "IntNumber = " << IntNumber << endl; IntNumber = 5000; cout << "FloatNumber = " << FloatNumber << endl; FloatNumber = ; cout << "FloatNumber = " << FloatNumber << endl; FloatNumber = ; int IntNumber; float FloatNumber; } PROG0509.CPP OUTPUT There is no program output. The program will not compile. Some messages indicating that IntNumber and FloatNumber are undefined will be your only output.

Identifier Rule All identifiers must be known to C++ before they can be used. C++ checks identifiers three ways: 1. Is the identifier a reserved word? 2. Is the identifier a library function? 3. Is the identifier defined in the program

String Variables apstring Inclusion You must use the statement #include "APSTRING.H" to have access to the special apstring data type. The format "APSTRING.H" is used. Your teacher may use a different include approach, such as "apstring.cpp"

The quotes will appear strange to use. All program examples have used program statements for library functions that use angle brackets, like: #include Now you are expected to use library functions with slightly different syntax, like: #include "apstring.h" or #include "APSTRING.H" What is going on?

When To Use And When To Use " " Use when the file you are including is one of the built- in C++ files that were automatically installed when C++ was installed. These files are located in some obscure directory. The use of tell the compiler to look for the file in that directory. Use "quotes" when the file you are including is one that you have created or has been given to you. These files are located in the same place as your main.CPP file. This would be either on your disk, or in what ever directory you happen to be working. The use of "quotes" tell the compiler to look for the file in the default directory.

// PROG0510.CPP // This program introduces the string variable with apstring. #include #include "APSTRING.H" void main() { apstring Name1; // 1st string variable; apstring Name2; // 2nd string variable; Name1 = "Suzie Snodgrass"; Name2 = "Seymour Schmittlap"; cout << "Name1 = " << Name1 << endl; cout << "Name2 = " << Name2 << endl; } PROG0510.CPP OUTPUT Name1 = Suzie Snodgrass Name2 = Seymour Snodgrass

// PROG0511.CPP // This program demonstrates how to initialize a string variable. // The program also shows incorrect value swapping. #include #include "APSTRING.H" void main() { apstring Name1 = "Kathy"; // 1st initialized string variable; apstring Name2 = "Tommy"; // 2nd initialized string variable; cout << "Name1 = " << Name1 << endl; cout << "Name2 = " << Name2 << endl; Name1 = Name2; Name2 = Name1; cout << endl; cout << "Name1 = " << Name1 << endl; cout << "Name2 = " << Name2 << endl; } PROG0511.CPP OUTPUT Name1 = Kathy Name2 = Tommy Name1 = Tommy Name2 = Tommy

This is the result, in memory, after the two program statements: apstring Name1 = "Kathy"; apstring Name2 = "Tommy"; The next assignment statement is crucial. It helps to explain what is happening. Name1 gets the value from Name2. The result is that now both string variables contain the exact same value. Name1 = Name2; The final program statement does not alter anything. It appears that values are swapped, but swapping is not possible, since the value of “Kathy” was lost. Name2 = Name1; Name1 Kathy Name2 Tommy Name1 Tommy Name2 Tommy

// PROG0512.CPP // This program demonstrates the correct swapping of two variable // values by using an extra variable. #include #include "APSTRING.H" void main() { apstring Animal1; apstring Animal2; apstring Temp; Animal1 = "Tiger"; Animal2 = "Giraffe"; cout << "Animal1 = " << Animal1 << endl; cout << "Animal2 = " << Animal2 << endl; Temp = Animal1; Animal1 = Animal2; Animal2 = Temp; cout << endl; cout << "Animal1 = " << Animal1 << endl; cout << "Animal2 = " << Animal2 << endl; } PROG0512.CPP OUTPUT Animal1 = Tiger Animal2 = Giraffe Animal1 = Giraffe Animal2 = Tiger

Swapping Correctly with a Temporary Placeholder Animal1 = "Tiger"; Animal2 = "Giraffe"; We know from previous experience that the value in Animal1 is likely to be endangered. The next assignment statement preserves the value. Temp = Animal1; Animal1 Tiger Animal2 Giraffe Temp Unknown Animal1 Tiger Animal2 Giraffe Temp Tiger

With Tiger safely tugged away in Temp, we can copy the Giraffe value to Animal1 without losing anything. Animal1 = Animal2; We now observe that both Animal1 and Animal2 store Giraffe. However, this time Tiger is lurking in Temp ready to jump into action. Animal2 = Temp; Animal1 Giraffe Animal2 Giraffe Temp Tiger Animal1 Giraffe Animal2 Tiger Temp Tiger

// PROG0513.CPP // This program demonstrates that string variables can be // defined and initialized two different ways. #include #include "APSTRING.H" void main() { apstring String1 = "First String"; apstring String2("Second String"); cout << "String 1 = " << String1 << endl; cout << "String 2 = " << String2 << endl; } PROG0513.CPP OUTPUT String1 = First String String2 = Second String

// PROG0514.CPP // This program demonstrates how to use the // reserved word const. #include #include "APSTRING.H" const int MAX = 5000; const float PI = ; const char START = 'A'; const apstring GREETING = "Good Morning"; void main() { cout << "MAX: " << MAX << endl; cout << "PI: " << PI << endl; cout << "START: " << START << endl; cout << "GREETING: " << GREETING << endl; } PROG0514.CPP OUTPUT MAX: 5000 PI: START: A GREETING: Good Morning

Syntax for Using const const data-type identifier = constant value const int MAX = 5000; It is a common convention, not a requirement, to use all capital letters for a const identifier.

// PROG0515.CPP // This program demonstrates that it is important to provide the // data type in a const statement. #include #include "APSTRING.H" const MAX = 5000; const PI = ; const START = 'A'; //const GREETING = "Good Morning"; void main() { cout << "MAX: " << MAX << endl; cout << "PI: " << PI << endl; cout << "START: " << START << endl; // cout << "GREETING: " << GREETING << endl; } PROG0515.CPP OUTPUT MAX: 5000 PI: 3 START: 65

// PROG0516.CPP // This program demonstrates that it is not possible to modify a constant object. #include #include "APSTRING.H" const int MAX = 5000; const float PI = ; const char START = 'A'; const apstring GREETING = "Good Morning"; void main() { MAX = 10000; PI = START = 'Q'; GREETING = "Good Afternoon"; cout << "MAX: " << MAX << endl; cout << "PI: " << PI << endl; cout << "START: " << START << endl; cout << "GREETING: " << GREETING << endl; } This program will not compile Error PROG0516.CPP: Cannot modify a const object

Literal Constants and Symbolic Constants Examples of literal constants are 2500, and Joe Smith. Number = 2500; PayRate = 12.75; Name = "Joe Smith"; Examples of symbolic constants are Nbr, PR, and Word. const int Nbr = 10000; const float PR = 9.25; const apstring Word = "QWERTY"; Symbolic constants cannot be modified.

// PROG0517.CPP // This program demonstrates that a constant value can be assigned to a variable. #include #include "APSTRING.H" const int MAX = 5000; const float PI = ; const char START = 'A'; const apstring GREETING = "Good Morning"; void main() { int IntVar; float FloatVar; char CharVar; apstring StringVar; IntVar = MAX; FloatVar = PI; CharVar = START; StringVar = GREETING; cout << "IntVar: " << IntVar << endl; cout << "FloatVar: " << FloatVar << endl; cout << "CharVar: " << CharVar << endl; cout << "StringVar: " << StringVar << endl; } PROG0517.CPP OUTPUT IntVar: 5000 FloatVar: CharVar: A StringVar: Good Morning