Friday, December 25, 2015

Chapter 2 - Variables and Data Types


 LET’S LEARN

INTRODUCTION

C++ VOCABULARY AND GRAMMAR

1. C++ Character Set

2. C++ Tokens

(a) Identifiers

(b) Keywords

(c) Data Types

         How are Variables connected to Data Types ?

         What is a Data Type ?

            (i) Primitive Data Type

            (ii) User Defined Data Type

            (iii) Derived Data Type

          SYMBOLIC CONSTANTS


INTRODUCTION

Data is the known or assumed facts that collectively lead to creation of information. Hence, Data is the basic unit of any information. When data is processed, we get useful information. So, Information is processed data.

Programming languages are used by developers to input data, process it, and provide useful output as information. The task of processing data is accomplished by executing a sequence of precise instructions called a program. Hence, Program is a set of instructions given to the computer in order to perform a specific task.

 

Program instructions are based upon predefined symbols and words that the operating system can understand according to some strictly followed guidelines known as syntax rules (grammatical rules).

 

Both raw-data (e.g. 14, 18) and processed-data (e.g. 14+18) have to be placed in memory location for being processed, stored or retrieved. Memory locations where data can be temporarily placed for being processed are called variables. The value of a variable can be changed and is identified by its name. Memory locations where static data (whose value cannot be changed) are placed for being processed, are called constants. 


The type (category) of value placed in a variable is known as data type. Different data types include characters, strings, numerals, decimals etc.





C++ VOCABULARY AND GRAMMAR

 

C++ programming language has its own vocabulary and grammar classified as Character Sets and Tokens. The C++ compiler understands instructions written in C++ programming language, translates it into machine readable form and then executes it as the required functionality.

1. C++ Character Set

Character Set includes the characters and symbols that a C++ program can understand and are grouped to form the commands, expressions, words, statements and tokens for the C++ coding language.

The characters that can be used in C++ are grouped into the following four categories:

Letters        Digits          • White spaces       Special characters

 

Letters

Letters are alphabetical characters represented by “A … Z” or “a … z”. C++ is case sensitive (upper case & lower case letters are considered different).

 

Digits

Digits are numeric characters represented by 0 to 9. They are used to represent numeric values and to assign numeric data to the C++ tokens.

 

White Spaces

White spaces are used to separate words, but are prohibited between characters of keywords and identifiers. It includes blank space, horizontal tab, carriage return and New line Form feed. The compiler ignores white spaces unless they are part of a string constant.

Special Characters

Special characters are used in C++ to create Arithmetic statements ( +  -  * / ), Relational statements ( <   <=   >  >=   == ) , Assignment statements ( = ), Logical statements (  &&   ||  !  ) etc.




 







 

Words are a collection of reserved keywords and standard identifiers. Eg: int, cout

Keywords are predefined words that are used to identify operations and data descriptions. They cannot be redefined. Eg: return, int, switch

Standard identifiers are predefined words that belong to the C++ standard library and have special meaning for the C++ compiler. It can be redefined. Eg: cout, main

Try below given code (just for reference):

int cout=1; int main=2;

std::cout<<"cout = "<<cout;

std::cout<<"\nmain = "<<main;

Statements are one or more program instructions given to the C++ compiler. Each statement ends with a semicolon. It includes variable declarations and expressions.

Eg: std::cout<< "Hello Good Day";

Operators are characters/signs that represent mathematical or logical operations. Eg: + - / % > =

Operands are data values or data holders (variables) that can be operated upon or manipulated. Eg: 10 + 2 = y; Here 10, 2, y are operands and + = are operators. Remember that y is a variable.

Expression is a sequence of operands and operators that specifies a computation process. Eg : a=42,  2+2 , a=b+c, a<b etc.

Commands are basic units of instructions given to the C++ compiler. Eg: #include, cout,  int, char, for, while

 


2. C++ Tokens

Tokens are the smallest individual units of C++ program. It is similar to independent words and punctuations found in a passage of text. There are 3 types of tokens: Identifiers, Keywords and Data Types.

Types of Tokens

(a) Identifiers

An identifier is a sequence of one or more letters, digits or underscore character that are used to represent variables, constants and functions in a program. Neither spaces nor punctuation marks or symbols can be part of an identifier. It cannot start with a decimal number. C++ identifies uppercase & lowercase alphabets as separate characters. Use of two sequential underscores ( __ ) is reserved for C++ implementation & standard libraries. Identifiers should not match any keyword used by the C++ language because this will confuse the compiler during translation process.

Variable : Storage location in memory where values can keep changing.

Constant: Storage location in memory having fixed value.

Function: A group of instructional statements that perform a defined task.

 (b) Keywords

Keywords are predefined words that are used to identify operations and data descriptions. They cannot be redefined and hence, they cannot be used as names for the program variables or other user-defined program elements. Eg: return, int, switch

List of common Keywords:



How are Variables connected to Data Types ?

A computer program needs to memorize/store certain values for input/output operations, calculations, processing and storage. These values (data) are stored in computer’s memory, based on the allocated memory space that is predefined for different datatypes within the C++ memory-management-system. The memory allocation in our computer systems are basically organized in Bytes.

 

In C++ the minimum amount of memory that we can manage is a byte. A byte can store relatively small amount of data such as one single character or a small integer (generally an integer between 0 and 255). Eg: char, short int.

 

However, the computer can handle large data by grouping several bytes. Groups of bytes manage memory allocations for accommodating larger and different types of values. For Eg:


int allocates 2 Bytes,

long int allocates 4 Bytes,

double allocates 8 Bytes.


Declaring & Initializing Variables: In order to use a variable in C++, we must first declare it, specifying which data type it would store. The declared variable can then be assigned with an initial value.

Variable declaration is the process of declaring memory space for storing value of a specific data type.

Variable initialization is the process of assigning appropriate values to an already declared variable.

 

Syntax for declaring a  Variable

 

 datatype variablename1, variablename2, ... ;

 

Example:   int age, mark ;


 Syntax  for initializing a Variable with Value

 

datatype variablename = initial value;

 

Example:   int age =18, mark = 75;


Variables can be declared at any place in the program. A variable of specific data type can be converted into another data type. This process is called type castingDynamic initializing of variables is also possible.

Type Casting is the process of converting one variable type into another.

Example: (float) a/b, where a and b are integers.

Dynamic initialization is the method of initializing a variable by an expression instead of a constant.  This type of initialization is done at run-time.

Example:  float fAverage = fSum + 5 ;


What is a Data Type ?

The type (category) of value placed in a variable is known as data type. Different types of data that can be stored in computer memory include characters, strings, numerals, decimals etc.

Different Data Types in C++

(i)                Primitive (Basic or Built-in)

(ii)              User-defined

(iii)            Derived

 

(i) Primitive Data Type

They are built-in data types of the C++ programming language. Here is a list of the basic data types in C++, as well as the range of values it can accommodate.




 






The size and range of basic data types depend on the architecture of the computer system being used to compile and execute the C++ program. The values shown in the chart corresponds to most 32-bit systems.

 

(ii) User Defined Data Type

 

It is any built-in data type or collection of data types, which can be named/renamed by the user. User-defined data types include typedef, struct, union, enum and class.

 

An example (typedef): In order to store integer numbers (1, 2, 3…), we use the data-type int and declare it in C++ program as int a, b; which means a, b are variables that can store integer values. Now look at this declaration statement:

 

typedef int NUMBERS;

 

This means that you can now use the term NUMBERS instead of int. So, the declaration:

int a, b;

can now also be written as

NUMBERS a, b;

 

As per above typedef definition, NUMBERS will represent data type ‘int’ thereby declaring ‘a‘ and ‘b’ as integers.

 

Note: Can you guess the datatype of string ? (refer to Program 4 below)

 

(iii) Derived Data Type

Derived data types is made up of simpler data types and hence contain multiple primitive data types. Arrays, Functions and Pointers are examples of derived data types. (You will learn more on arrays, functions, pointers in upcoming chapters)

 


Array is a collection of consecutive memory locations that store values of same data type and are identified by a common name.

 

Function is a group of instructional statements that together perform a specific task.

 

Pointer is used to store the memory address of another variable.

 

SYMBOLIC CONSTANTS

Symbolic constant is used to give an explanatory name to any constant value. Its advantage is that, if you want to change the value of a symbolic constant, you just need to make the edit at one location instead of making changes at all places in the program where it’s used. Symbolic constants can be declared by any of the following methods:

(a) #define, #undef (preprocessor macro definitions)

(b) const keyword

(c) enum keyword

 For Example: #define  iMax 20

           or,       const int iMax = 20;

           or,       enum { iMax = 20 };

           hence, iMax + 10 = 30

           iMax can be used instead of 20. iMax is a constant.

 

Program 3: Write a program to accept First Name of a person and wish that person by his/her name. Use data type “char”.

  

 

#include <iostream>

int main()

{

        char a[20];

        std::cout << "Type your First Name (then Press enter key): ";

        std::cin >>a;

        std::cout << a << " Have a Nice Day";

}

 

Output


Program 4: Above program can be modified using getline() of the “string” class. (We will learn in detail about the string class in chapter 6)


 

#include <iostream>

#include <string>

using namespace std;

int main()

 

{

        string s;

        cout << "Type your First Name (then Press enter key): ";

        getline(cin,s);

        cout << s << " Have a Nice Day";

 

}

OUTPUT


 

 

Program 5: Accept 2 numbers and find their sum, product and quotient.

(In this program, “Typecast” feature prints exact quotient value. Try to find reason for values of variables e, p, q. Can you guess the use of “\n” )


 

#include <iostream>

int main()

{

  int a, b, c, d, e;

  float p, q;

  std::cout << "Enter 2 numbers: ";

  std::cin >> a >> b;

  c=a+b;

  d=a*b;

  e=a/b;

   p=a/b;

  q=(float)a/b; // example of Typecast

  std::cout << a << " + " << b << " = "<< c << "\n";

  std::cout << a << " * " << b << " = "<< d << "\n";

  std::cout << a << " / " << b << " = "<< e << "\n";

  std::cout << a << " / " << b << " = "<< p << "\n";

  std::cout << a << " / " << b << " = "<< q;

}

 

Output



 




Program 6: Print the answer to this question “Which month and year is it?” Use preprocessor directives to define a month and year.

 

 

#include <iostream>

int main()

{

  #define month "December"

  #define year 2020

  std::cout << "This is "<<month<<" of "<<year;

}

 

Output


2 comments:

  1. very interesting to know the whole process digitally and physically. thanks for well explaining it. great read.

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete