Working with Variables and Constants
1. Target of a program is to
1. store the data they use or create so that it will be used in further execution.
2. Variables and constants offer various ways to represent, store, and manipulate that data.
Today, you will learn
• How to declare and define variables and constants
• How to assign values to variables and manipulate those values
• How to write the value of a variable to the screen
What is a Variable?
It is a place/location on computer where we can store the data or information the user provides from which we can retrieve the value.
Variables are used for the temporary storage of Data. When you exit from the computer the info will be automatically lost.
Typically, the values from variables are permanently stored either to a database or to a file on disk.
Storing Data in Memory :
Each memory location—is numbered sequentially. These numbers are known as memory addresses. A variable reserves one or more cubbyholes in which you can store a value.Your variable’s name (for example, myVariable) is a label on one of these memory location so that you can find it easily without knowing its actual memory address.
Each memory location is one byte in size. If the type of variable you create is four bytes in size, it needs four bytes of memory, or four memory locations. The type of the variable (for example,integer) tells the compiler how much memory (how many memory locations) to set aside for the variable.
There was a time when it was imperative that programmers understood bits and bytes;after all, these are the fundamental units of storage. Computer programs have gotten better at abstracting away these details, but it is still helpful to understand how data is stored.
Size of Integers :
On any one computer, each variable type takes up a single, unchanging amount of room. That is, an integer might be two bytes on one machine and four on another, but on either computer it is always the same, day in and day out.Single characters—including letters, numbers, and symbols—are stored in a variable of type char. A char variable is most often one byte long
Size of an integer can be determined by the processor and the compiler we basically use.
Please Run this code to know more about how much the variable type sizes have fixed onto the memory of your PC :
1: #include <iostream>
2:
3: int main()
4: {
5: using std::cout;
6:
7: cout << “The size of an int is:\t\t”
8: << sizeof(int) << “ bytes.\n”;
9: cout << “The size of a short int is:\t”
10: << sizeof(short) << “ bytes.\n”;
11: cout << “The size of a long int is:\t”
12: << sizeof(long) << “ bytes.\n”;
13: cout << “The size of a char is:\t\t”
14: << sizeof(char) << “ bytes.\n”;
15: cout << “The size of a float is:\t\t”
16: << sizeof(float) << “ bytes.\n”;
17: cout << “The size of a double is:\t”
18: << sizeof(double) << “ bytes.\n”;
19: cout << “The size of a bool is:\t”
20:cout << sizeof(bool) << “ bytes.\n”;
21:
22: return 0;
23: }
Output : It varies from a PC to other.
Signed and Unsigned :
Unsigned default are positive numbers and signed numbers can either be positive or negative. Signed number will hold the information regarding either the number is positive or negative.
The result is that the largest number you can store in an unsigned integer is twice as big as the largest positive number you can store in a signed integer.
For example, if a short integer is stored in two bytes, then an unsigned short integer can handle numbers from 0 to 65,535. Alternatively, for a signed short, half the numbers that can be stored are negative; thus, a signed short can only represent positive numbers up to 32,767. The signed short can also, however, represent negative numbers giving it a total range from –32,768 to 32,767.
Variable Types
Type Size Values
bool 1 byte true or false
unsigned short int 2 bytes 0 to 65,535
short int 2 bytes –32,768 to 32,767
unsigned long int 4 bytes 0 to 4,294,967,295
long int 4 bytes –2,147,483,648 to 2,147,483,647
int (16 bit) 2 bytes –32,768 to 32,767
int (32 bit) 4 bytes –2,147,483,648 to 2,147,483,647
unsigned int (16 bit) 2 bytes 0 to 65,535
unsigned int (32 bit) 4 bytes 0 to 4,294,967,295
char 1 byte 256 character values
float 4 bytes 1.2e–38 to 3.4e38
double 8 bytes 2.2e–308 to 1.8e308
Defining a Variable :
You create or define a variable by stating its type, followed by one or more spaces, followed by the variable name and a semicolon.
Case Sensitivity :
C++ is case sensitive. In other words, uppercase and lowercase letters are considered to be different. A variable named age is different from Age, which is different from AGE.
Naming Conventions :
If My Name is the character to be used then specify it as My_Name or MyName not as My Name because the compailer considers as the two characters namely My , Name.
Keywords that are generally used:
asm else new this
auto enum operator throw
bool explicit private true
break export protected try
case extern public typedef
catch false register typeid
char float reinterpret_cast typename
class for return union
const friend short unsigned
const_cast goto signed using
continue if sizeof virtual
default inline static void
delete int static_cast volatile
do long struct wchar_t
double mutable switch while
dynamic_cast namespace template
In addition, the following words are reserved:
And bitor not_eq xor
and_eq compl or xor_eq
bitand not or_eq
DON’T use C++ keywords as variable names.
DON’T make assumptions about how many bytes are used to store a variable.
DON’T use unsigned variables for negative numbers.
Creating More Than One Variable at a Time :
You can create more than one variable of the same type in one statement by writing the type and then the variable names, separated by commas.
For example:
unsigned int myAge, myWeight; // two unsigned int variables
long int area, width, length; // three long integers
As you can see, myAge and myWeight are each declared as unsigned integer variables. The second line declares three individual long variables named area, width, and length. The type (long) is assigned to all the variables, so you cannot mix types in one definition statement.
Just as you can define more than one variable at a time, you can initialize more than one variable at creation. For example, the following creates two variables of type long and initializes them:
long width = 5, length = 7;
int mymarks=32,hisMarks=34,averageMarks;
Now the value for averageMarks variable will be average of myMarks and the averageMarks.
#include <iostream>
int main()
{
using std::cout;
using std::endl;
unsigned short int Width = 5, Length;
Length = 10;// create an unsigned short and initialize with result
// of multiplying Width by Length
unsigned short int Area = (Width * Length);
cout << “Width:” << Width << endl;
cout << “Length: “ << Length << endl;
cout << “Area: “ << Area << endl;
return 0;
}
Output :
Width:5
Length: 10
Area: 50
Creating Aliases with typedef :
It can become tedious, repetitious, and, most important, error-prone to keep writing unsigned short int. C++ enables you to create an alias for this phrase by using the keyword typedef, which stands for type definition. In effect, you are creating a synonym, and it is important to distinguish this from creating a new type (which you will do on Day 6, “Understanding Object-Oriented Programming”). typedef is used by writing the keyword typedef, followed by the existing type, then the new name, and ending with a semicolon. For example,
typedef unsigned short int USHORT;
creates the new name USHORT that you can use anywhere you might have written unsigned short int. Listing 3.3 is a replay of Listing 3.2, using the type definition USHORT rather than unsigned short int.
A Demonstration of typedef :
1: // Demonstrates typedef keyword
2: #include <iostream>
3:
4: typedef unsigned short int USHORT; //typedef defined
5:
6: int main()
7: {
8:
9: using std::cout;
10: using std::endl;
11:
12: USHORT Width = 5;
13: USHORT Length;
14: Length = 10;
15: USHORT Area = Width * Length;
16: cout << “Width:” << Width << endl;
17: cout << “Length: “ << Length << endl;
18: cout << “Area: “ << Area <<endl;
19: return 0;
20: }
Output: t will be same as of the previous Program's output.
Wrapping Around an unsigned Integer :
If the size of the given unsigned Integer by an user has exceeded the limit then it wraps aroung and start over.
For Example : unsigned short int a=65535;//output=65535
a++; //output=0
a++;//output=1
***********************
Wrapping around Signed Integer :
If the size of the given signed Integer by an user has exceeded the limit then it wraps aroung and start over negative value.
For Example : unsigned short int a=32767;//output=32767
a++; //output= -327668
a++;//output= -32767
***********************
Working with Characters:
Character variables (type char) are typically 1 byte, enough to hold 256 values. A char can be interpreted as a small number (0–255) or as a member of the ASCII set. The ASCII character set and its ISO equivalent are a way to encode all the letters, numerals, and punctuation marks.In the ASCII code, the lowercase letter “a” is assigned the value 97. All the lower- and uppercase letters, all the numerals, and all the punctuation marks are assigned values between 1 and 128.
Printing Characters Based on Numbers :
1: #include <iostream>
2: int main()
3: {
4: for (int i = 32; i<128; i++)
5: std::cout << (char) i;
6: return 0;
7: }
Output:
!”#$%&’()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmno pqrstuvwxyz{|}~?
Explanation:
This simple program prints the character values for the integers 32 through 127. This listing uses an integer variable, i, on line 4 to accomplish this task. On line 5, the number in the variable i is forced to display as a character.
*******************
1: #include <iostream>
2: int main()
2: {
4: for (unsigned char i = 32; i<128; i++)
5: std::cout << i;
6: return 0;
7: }
Explanation: An unsigned character is used on line 4. Because a character variable is being used instead of a numeric variable, the cout on line 5 knows to display the character value.
*********************
Special Printing Characters :
The escape character (\) changes the meaning of the character that follows it. For example, normally the character n means the letter n, but when it is preceded by the escape character, it means new line.
The Escape Characters
Character What It Means
\a Bell (alert)
\b Backspace
\f Form feed
\n New line
\r Carriage return
\t Tab
\v Vertical tab
\’ Single quote
\” Double quote
\? Question mark
\\ Backslash
\000 Octal notation
\xhhh Hexadecimal notation
***********************************
Constants :
Litereal Constants : int myWeight = 39;
Symbolic Constants :
If your program has an integer variable named students and another named classes, you could compute how many students you have, given a known number of classes, if you knew each class consisted of 15 students:
students = classes * 15;
In this example, 15 is a literal constant. Your code would be easier to read, and easier to maintain, if you substituted a symbolic constant for this value:
students = classes * studentsPerClas
If you later decided to change the number of students in each class, you could do so where you define the constant studentsPerClass without having to make a change every place you used that value.
Defining Constants with #define : #define studentsPerCollege=20;
Defining Constants with const : const unsigned short int studentsPerCollege = 15;
****************************
Enumerated Constants :
Enumerated constants enable you to create new types and then to define variables of those types whose values are restricted to a set of possible values.
Deminstration of Enumerated Constants :
1: #include <iostream>
2: int main()
3: {
4: enum Days { Sunday, Monday, Tuesday,
5: Wednesday, Thursday, Friday, Saturday };
6:
7: Days today;
8: today = Monday;
9:
10: if (today == Sunday || today == Saturday)
11: std::cout << “\nGotta’ love the weekends!\n”;
12: else
13: std::cout << “\nBack to School.\n”;
14:
15: return 0;
16: }
Output : Back to School.
************************
Same Program Using Constant Integers
1: #include <iostream>
2: int main()
3: {
4: const int Sunday = 0;
5: const int Monday = 1;
6: const int Tuesday = 2;
7: const int Wednesday = 3;
8: const int Thursday = 4;
9: const int Friday = 5;
10: const int Saturday = 6;
11:
12: int today;
13: today = Monday;
14:
15: if (today == Sunday || today == Saturday)
16: std::cout << “\nGotta’ love the weekends!\n”;
17: else
18: std::cout << “\nBack to work.\n”;
19:
20: return 0;
21: }
Output: Back to work.
Link : DAY 4
WEEK 1 (Day 4)
On Day 4, “Creating Statements and Expressions”
Comments