Download presentation
Presentation is loading. Please wait.
Published byJulian Weaver Modified over 9 years ago
1
Variables, Data Types and Constants Yared Semu Addis Ababa Institute of Technology Mar 31, 2012
2
Last Time…. Basic (C++) program Construction We greeted the world with our first C++ program – “Hello World!”
3
1 //A Simple C++ Program #include using namespace std; int main() { cout<<“Programming is great fun!”; return 0; } CommentsDirectiveNamespace Statement Functions Return Control to OS
4
Question Modify the previous program so that it outputs the following lines? Hint: Use either endl (end current line manipulator ) or the escape sequence character(\n – new line) Programming is great fun! I love to Program!
5
Escape Sequences
6
Basic Elements Five kind of tokens in C++ –Comments –Keywords (Reserved words) –Identifiers –Literals –Operators
7
Comments Typical Uses –Identify program and who wrote it –Record when program was written –Add description of modifications –Explain programs to other programmers
8
Keywords Words with special meaning to the compiler Have a predefined meaning that cannot be changed All the reserved words are in lower-case letter
9
C++ Keyword set
10
Identifiers An identifier is a programmer-defined name that represents some element of a program. –Element : function name, variable (data object) Your identifiers must not be any of the C++ keywords. –Keywords : have specific purposes.
11
Naming Conventions 1.You can use UPPERCASE and lowercase letters (a-z, A-Z) The digits from 0 to 9 The underscore symbol 2.You can’t use a C++ keyword as an identifier. 3.An identifier can’t begin with a number 4.C++ is case sensitive YARED Yared yAaReD
12
Exercise Which of the following identifiers are legal? home1 min_Age cla!s Y.S _4 days-in-year first_1 for Cout
13
Literals Explicit (constant) value that is used by a program Literals can be digits, letters or others that represent constant value to be stored in variables –Assigned to variables –Used in expressions –Passed to methods E.g. –Pi = 3.14; // Assigned to variables –C= a * 60; // Used in expressions
14
Variables Why do we need variables? Mental Exercise!
15
Variable Analogy Retain the number 5 in your memory Memorize the number 2 at the same time You have now stored two different values in your memory Add 1 to the 1 st number Now you should be retaining the numbers 6 and 2 in your memory Subtract this two values You should obtain 4
16
If you were to do it on Paper ….. The same process expressed in C++ instruction set looks like a = 5; b = 2; c = a + 1; result = c – b; Variable = Portion of memory to which we can store a value and from which we can later retrieve that value.
17
Variables A Variable is a named storage location in the computer’s memory used for data storage. A variable is a portion of the computer’s memory,in which we can store a value and from which we can later retrieve that value Variable Definition Variable Initialization Variable Assignment
18
All variables have two important attributes: –A type – Once defined, the type a C++ variable cannot be changed –A value – can be changed by assigning a new value. Example:int a = 5;
19
Variable Definition Variable Definition Syntax: Note that: You must declare a variable before using it Variable declaration can be placed anywhere in the program Readability Purpose: beginning of the main function. type: Specifies two things type variable_name;
20
More on Variable Definition A declaration (definition) of a variable is a statement that defines a variable. A comma separated list of one or more identifiers. float base_price, last_selling_price, averageSellingPrice; float base_price, last_selling_price, averageSellingPrice;
21
Variable Initialization Let say we have a integer variable named number. Definition: Q. What is the content of the variable number? To make use of the variable we have in our programs, we need to give them value. >> Direct Initialization >> Copy Initialization int number;
22
Variable Assignment The = sign is an operator that copies the value of its right into the variable named on its left. int number = 5; or number = 5;
23
Good Programming Practice Place a space after each comma (, ) to make programs more readable.
24
Good Programming Practice Some programmers prefer to declare each variable on a separate line. This format allows for easy insertion of a descriptive comment next to each declaration.
25
Portability Tip C++ allows identifiers of any length, but your C++ implementation may impose some restrictions on the length of identifiers. Use identifiers of 31 characters or fewer to ensure portability.
26
Good Programming Practice Choosing meaningful identifiers helps make a program self- documenting—a person can understand the program simply by reading it rather than having to refer to manuals or comments.
27
Good Programming Practice Avoid identifiers that begin with underscores and double underscores, because C++ compilers may use names like that for their own purposes internally. This will prevent names you choose from being confused with names the compilers choose.
28
Exercise. List all the variables and constants that appear in the following program. // This program uses variables and constants #include using namespace std; int main() { int little; int big; little = 2; big = 2000; cout << "The little number is " << little << endl; cout << "The big number is " << big << endl; return 0; }
29
Data Types Broadly C++ provides two data types Numeric Integral Numbers short int long Fractional Numbers float double Character or sequence of characters char Boolean Values bool
30
Integer Data Types, Sizes and Ranges
31
Type: int Represent integers or whole numbers –Signed – (Positive and negative Numbers) –Unsigned – (Only Postive) –Short –Long
32
Type: double, float Used to represent real numbers Avoid leading zeros, trailing zeros are ignored
33
Type: char Used to represent character data –A single character which includes a space –1 byte, enough to hold 256 values –Must be enclosed in single quotes E.g ‘d’
34
Input with cin The keyword cin represents a standard input stream. The input stream represents data coming from the keyboard. The >> is the extraction operator or get from keyboard operator.
35
Exercise Write a program that accepts a character from the user and echo it to the screen. [Demo]
36
Area of a Rectangle //Calculates the area of a rectangle int main() { int length, width; cout >”; cin>>length; cout >”; cin>>width; int area = length * width; cout<<“Area: ”<<area<<endl; return 0; } Output Window Enter the length of the rectangle: 10 Enter the width of the rectangle: 20 Area: 200
37
Working Examples: Temperature Conversion //Temperature Conversion Program int main() { int ftemp; //Temprature in Fahrenheit cout<<“Enter the temperature in Fahrenheit: ”; int ctemp = (ftemp-32)*5/9; cout<<“Equivalent in Celsius: ”<<ctemp<<endl; return 0; } Output Window Enter the temperature in Fahrenheit:23 Equivalent in Celsius: 4
38
Predict the output_01 #include using namespace std; int main() { cout<<“I am the incredible”; cout<<“computing machine”; cout<<“\n and I will \namze \n”; cout<<“you.\n”; return 0; }
39
Addition: 01 Write a program that accept two numbers from the user and displays the output back to the user. –Hint: First write the simple algorithm using a flowchart.
40
Swap: 02 Write a program that swaps the values of two variables and displays their former and current values. The values of the variables are to be entered from the keyboard.
41
Circle : 03 Write a program that calculates and displays the area and the circumference of a circle based on its radius entered from the keyboard. [Using Constants] const qualifier #define directive
42
Implement an Pseudocode: 04 Write a program that implements the following algorithm. Start Read the total hours the employee has worked, TotalHours Read the hourly rate of pay for the employee, HourlyRate GrossSalary = TotalHours * HourlyRate Tax = GrossSalary * 0.1 NetSalary = GrossSalary - Tax Display NetSalary Stop
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.