variables, data types and constants yared semu addis ababa institute of technology mar 31, 2012

Post on 11-Jan-2016

217 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Variables, Data Types and Constants

Yared SemuAddis Ababa Institute of Technology

Mar 31, 2012

Last Time….

• Basic (C++) program Construction

• We greeted the world with our first C++ program

– “Hello World!”

1//A Simple C++ Program

#include <iostream>using namespace std;

int main(){

cout<<“Programming is great fun!”;return 0;

}

Comments

Directive

Namespace

Statement

Functions

Return Control to OS

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!

Escape Sequences

Basic Elements

• Five kind of tokens in C++–Comments–Keywords (Reserved words)– Identifiers–Literals–Operators

Comments

• Typical Uses– Identify program and who wrote it– Record when program was written– Add description of modifications– Explain programs to other programmers

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

C++ Keyword set

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.

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 number4. C++ is case sensitive

YARED Yared yAaReD

Exercise

• Which of the following identifiers are legal?home1min_Agecla!sY.S_4days-in-yearfirst_1forCout

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

Variables

• Why do we need variables?

• Mental Exercise!

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 1st number• Now you should be retaining the

numbers 6 and 2 in your memory• Subtract this two values• You should obtain 4

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.

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 DefinitionVariable InitializationVariable Assignment

• 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;

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;

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;

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;

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;

Good Programming Practice

Place a space after each comma (,) to make programs more readable.

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.

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.

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.

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.

Exercise. List all the variables and constants that appear in the following program.

// This program uses variables and constants#include <iostream>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;

}

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

Integer Data Types, Sizes and Ranges

Type: int

• Represent integers or whole numbers

– Signed – (Positive and negative Numbers)

– Unsigned – (Only Postive)– Short – Long

Type: double, float

• Used to represent real numbers• Avoid leading zeros, trailing zeros are

ignored

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’

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.

Exercise

Write a program that accepts a character from the user and echo it to the screen.

[Demo]

Area of a Rectangle//Calculates the area of a rectangle

int main(){

int length, width;

cout<<“Enter the length of the rectangle>>”;cin>>length;cout<<“Enter the width of the rectangle>>”;cin>>width;

int area = length * width;

cout<<“Area: ”<<area<<endl;

return 0;

}

Output Window

Enter the length of the rectangle: 10Enter the width of the rectangle: 20Area: 200

Working Examples: Temperature Conversion

//Temperature Conversion Programint 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 WindowEnter the temperature in Fahrenheit:23Equivalent in Celsius: 4

Predict the output_01

#include <iostream>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;}

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.

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.

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

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

top related