## C++ Types, Variables and Arithmetic

BEFORE: C++ Declaration of variables

In C++ every name and every expression has a type that determines the operations that may be performed on it. For example, the declaration:

…..

{

int inch;

…..

…..

}

…..

…..

specifies that inch is of type int; that is, inch is an integer variable.

C++ offers a variety of fundamental types, which correspond directly to hardware facilities.

For example:

bool // Boolean, possible values are true and false

char // character, for example, ’a’, ’z’, and ’9’

int // integer, for example, 1, 42, and 1066

double // double-precision floating-point number, for example, 3.14 and 299793.0

Each of the fundamental types has a fixed size that determines the range of values that can be stored in them (for integers) or the precision and range of those values (for floating point numbers). A char variable is of the natural size to hold a character on a given machine (typically an 8-bit byte), and the sizes of other types are quoted in multiples of the size of a char. The size of a type is implementation defined (i.e., it can vary among different machines) and can be obtained by the sizeof operator; for example sizeof(char) equals 1 and sizeof(int) is often 4. We can represent sizes graphically: The arithmetic operators can be used for appropriate combinations of these types:

x+y // plus

+x // unar y plus

x−y // minus

−x // unar y minus

x∗y // multiply

x/y // divide

x%y // remainder (modulus) for integers

So can the comparison operators:

x==y // equal

x!=y // not equal

x<y // less than

x>y // greater than

x<=y // less than or equal

x>=y // greater than or equal

In assignments and in arithmetic operations, C++ performs all meaningful conversions between the basic types so that they can be mixed freely, as follows:

….

….

void some_function() // function that doesn’t return a value

{

double d = 2.2; // initialize floating-point number

int i = 7; // initialize integer

d = d+i; // assign sum to d

i = d∗i; // assign product to i (truncating the double to an int)

}

…..

…..

Note that = is the assignment operator and == tests equality.

C++ offers a variety of notations for expressing initialization, such as the = used above, and a universal form based on curly brace delimited initializer lists, as follows:

double d1 = 2.3;

double d2 {2.3};

complex z = 1; // a complex number with double-precision floating-point scalars

complex z2 {d1,d2};

complex z3 = {1,2}; // the = is optional with { … }

vector v {1,2,3,4,5,6}; // a vector of ints

A constant cannot be left uninitialized and a variable should only be left uninitialized in extremely rare circumstances. Don’t introduce a name until you have a suitable value for it.

When defining a variable, you don’t actually need to state its type explicitly when it can be deduced from the initializer:

auto b = true; // a bool

auto ch = ’x’; // a char

auto i = 123; // an int

auto d = 1.2; // a double

auto z = sqrt(y); // z has the type of whatever sqrt(y) returns

With auto, we use the = syntax because there is no type conversion involved that might cause problems.

In addition to the conventional arithmetic and logical operators, C++ offers more specific operations for modifying a variable:

x+=y // x = x+y

++x // increment: x = x+1

x−=y // x = x-y

−−x // decrement: x = x-1

x∗=y // scaling: x = x*y

x/=y // scaling: x = x/y

x%=y // x = x%y

These operators are concise, convenient, and very frequently used.

C++ supports two notions of immutability:

const: meaning roughly ‘‘I promise not to change this value’’. This is used primarily to specify interfaces, so that data can be passed to functions without fear of it being modified. The compiler enforces the promise made by const.

constexpr: meaning roughly ‘‘to be evaluated at compile time’’. This is used primarily to specify constants, to allow placement of data in memory where it is unlikely to be corrupted, and for performance.

For example:

doub le sum(const vector&); // sum will not modify its argument

const int dmv = 17; // dmv is a named constant

conste xpr double max1 = 1.4∗square(dmv); // OK if square(17) is a constant expression

const double max2 = 1.4∗square(dmv); // OK, may be evaluated at run time

v ector v { 1.2, 3.4, 4.5 }; // v is not a constant

const double s1 = sum(v); // OK: evaluated at run time

conste xpr double s2 = sum(v); // error : sum(v) not constant expression

Next example will illustrate what we have discussed so far:

double square(double x) //eleva al cuadrado un número tipo double-precision //                                                       //floating point

{

return x * x;

}

void print_square(double x)

{

std::cout << “the square of” << x << “is” << square(x) << ‘\n’;

}

int main()

{

print_square(1.234); //imprime el cuadrado de 1.234

print_square(5.555); // imprime el cuadrado de 5.555

}

Output: The std:: specifies that the name cout is to be found in the standard-library namespace. Without std:: operator, the statement ” cout << “the square of” << x << “is” << square(x) << ‘\n’;” has no sense.

A ‘‘return type’’ void indicates that a function does not return a value.

`Numeric Data.`

C++ contains intrinsic data types to store numeric values in your application code. It’s important to remember that these values are binary-based and not as flexible as their base 10 counterparts. For example, in mathematical terms of a base 10 integer, the definition is a value that is negative infinity to positive infinity whole numbers. Modern computers still cannot represent numbers these large. Take as an example the int type in the Numeric Data Types table. The range does not exceed 3 billion in either direction.

Note: I recommend Visual Studio IDE (Interface Development Environment) , and after Introducción a C++ en Visual Studio.

BEFORE: C++ Declaration of variables

Source:

Review by: Larry Francis Obando – Technical Specialist – Educational Content Writer.

Escuela de Ingeniería Eléctrica de la Universidad Central de Venezuela, Caracas.

Escuela de Ingeniería Electrónica de la Universidad Simón Bolívar, Valle de Sartenejas.

Escuela de Turismo de la Universidad Simón Bolívar, Núcleo Litoral.

Contact: Caracas, Quito, Guayaquil, Cuenca – Telf. 00593998524011

WhatsApp: +593998524011

email: dademuchconnection@gmail.com

Anuncios

## C++ Statements&Declaration of Variables.

`Statements`

A C++ program is comprised of various components such as functions, methods, classes, etc. The instructions that form part of a C++ program typically reside inside of functions or methods. These functions are comprised of C++ statements. You will find yourself using various types of statements in your C++ code as listed here:

• declarations – these are used to declare variables and constants that will be used in your application
• assignments – these are used to assign values to variables in your application code
• preprocessor directives – covered in the topic on Code Formatting
• comments – used to document your code
• function declarations – covered in the topic on Code Formatting
• executable statements – these are used to perform operations and execute instructions. Examples would be cout << “Hello World!”; which outputs Hello World! to the console.

In C, all variables must be declare before they are used in executable statements. Their actual use appears elsewhere in the scope, sometimes far away. So, we should go back at the beginning of the program if we want to see its type or its initialization.

C++ allows the declaration of a variable anywhere in the scope. This means that a variable can be declared right at the place of its first use. This makes the program much easier to write or read, so that reducing the errors is more efficient.

`Declaration`

A declaration is a statement that introduces a name into the program. It specifies a type for the named entity:

• A type defines a set of possible values and a set of operations (for an object).
• An object is some memory that holds a value of some type.
• A value is a set of bits interpreted according to a type.
• A variable is a named object.

We first look at the definition of scope and dynamic initialization of the variables.

`Scope Resolution Operator.`

C++ is a block-structured language. The same variable name can be used to have different meanings in different blocks. The scope of the variable extends from the point of its declaration till the end of the block containing the declaration. A variable declared inside a block is said to be local to that block. Consider the following segment of a program:

…..

{

int x = 20;

…..

…..

}

…..

…..

{

int x = 10;

…..

…..

}

The two declaration of x to two different memory locations containing different values. Statements in the second block cannot to the variable x declared in the first block. Another style is as follows: Block two is contained in the block one. The declaration inner inner block hides a declaration of the same variable in an outer block, therefore, each declaration of x causes it to refer a different data object. Within the inner block, the variable x will refer to the data object declared therein.

In C, the global version of a variable cannot be accessed from within the inner block. C++ resolves this problem by introducing a new operator :: called the scope resolution operator. This can be to uncover a hidden variable. It takes the following form: This operator allows access to the global version of a variable. To illustrate the concepts presented so far, let’s see an example:

#include “stadfx.h”

#include <iostream>

using namespace std;

int m = 10; //global m

int main()

{

int m=20; //local m

{

int k = m;

int m = 30;//local m to inner block

cout << “We are in a inner block \n”;

cout << “k = ” << k << “\n”;

cout << “m = ” << m << “\n”;

cout << “::m = ” << :: m << “\n”;

}

cout << “\n We are in a outer block \n”;

cout << “m = ” << m << “\n”;

cout << “::m = ” << ::m << “\n”

return 0;

}

Output: A major application of the scope resolution operator is in the classes to identify the class to which a member function belongs. This will be dealt in detail later where the classes are introduced.

In the previous example the operator int determines the type of the data as integer. This lead us to the definition of data types in C++.

`Basic Data Types`

Data types in C++ can be classified under various categories as shown in Figure 3.1: Both C and C++ compilers support all the built-in data type (also called basic data types), which seize and range is shown as follows: The type void has two normal uses: 1) to specify the return type of a function when it is not returning any value, and 2) to indicate an empty argument list to a function. Example:

void functl(void);

We will explain more about every type of data as we come into more complex examples.

Note: I recommend Visual Studio IDE (Interface Development Environment) , and after Introducción a C++ en Visual Studio.

Source:

Review by: Larry Francis Obando – Technical Specialist – Educational Content Writer.

Escuela de Ingeniería Eléctrica de la Universidad Central de Venezuela, Caracas.

Escuela de Ingeniería Electrónica de la Universidad Simón Bolívar, Valle de Sartenejas.

Escuela de Turismo de la Universidad Simón Bolívar, Núcleo Litoral.

Contact: Caracas, Quito, Guayaquil, Cuenca – Telf. 00593998524011

WhatsApp: +593998524011

email: dademuchconnection@gmail.com

## C++ Principles of object-oriented programming

Jueves 29 , 05:17 am

Today’s literature review:

1. BalaguruswamyObjectOrientedProgrammingWithC++Fourth
1. 1.3 A look at Procedure-Oriented Programming
2. 1.4 Object-Oriented Programming Paradigm(OOP)
3. 1.5 Basic concepts
4. 2.3 A simple program “Hello world”

Object-Oriented Programming (OOP) is an approach that provides a way of modularizing programs by creating partitioned memory area for both data and functions that can be used as templates for creating copies of such modules on demand. Thus, an object is considered to be a partitioned area of computer memory that stores data and set of operations that can access that data. Since the memory partitions are independent, the objects can be used in a variety of different programs without modification…(Balagurusamy, 2008).

1.3 Characteristics exhibited by procedure-oriented programming (POP) are:

• The emphasis is on doing things (algorithms)
• Large programs are divided into small programs called functions.
• Most of the functions shared global data.
• Data move openly around the system from function to function.
• Functions transform data from one type to another,
• The technique employs top-down approach in program design.

1.4 Object-Oriented Programming (OOP) treats data as a critical element in the program development and does not allow it to flow freely around a system. It ties data more closely to the functions that operate on it, and protects it from accidental modifications from outside functions. OOP allows decomposition into a number of entities called objects and then builds data and function around these objects. The organization of dta and functions in object-oriented programming is shown in Figure 1.6 Object-Oriented Programming (OOP) is an approach that provides a way of modularizing programs by creating partitioned memory area for both data and functions that can be used as templates for creating copies of such modules on demand. Thus, an object is considered to be a partitioned area of computer memory that stores data and set of operations that can access that data. Since the memory partitions are independent, the objects can be used in a variety of different programs without modification.

An object-oriented program consists of a set of objects that communicate with each other. The process of programming in a object-oriented language, therefore, involves the following basic steps:

• Creating classes that define objects and their behaviour,
• Creating objects from class definitions and,
• Establishing communication among objects.

Objects communicate with one another by sending and receiving information much the same way as people pass messages to one another. That makes it easier to talk about building systems that directly model or simulate their real-world counterparts.

A message for an object is a request for execution of a procedure, and therefore will invoke a function (procedure) in the receiving object that generates the desired result. Message passing involves specifying the name of the object, the name of the function (message) and the information to be sent. Example: Real-business systems are often much complex and contain many more objects with complicated attributes and methods. OOP is useful in these types of application domains because it can simplify a complex problem. The promising areas for application of OOP include:

• Real-time systems
• Simulation and modeling
• Object-oriented databases
• Hypertext, hypermedia and expertext
• AI and expert systems
• Neural networks and parallel programming
• Decision support and office automation systems
• CIM/CAM/CAD System

Procedure-oriented programming (POP) has to majors drawbacks: (1) data move freely around the program and are therefore vulnerable to changes caused by any function in the program; (2) POP does not model very well the real-world problems. OOP was invented to overcome the drawbacks of POP.

In OOP, a problem is considered as a collection of a number of entities called objects. Objects are instances of classes. Insulation of data from direct access by the program called data hiding.

Data abstraction refers to putting together essential features without including background details.

Inheritance is the process by which objects of one class acquire properties of objects of another class.

Polymorphism means one name, multiple forms. It allows us to have more than one function with the same name in a program. It also allows overloading of operators so that an operation can exhibit different behaviours in different instances. Dynamic binding means that the code associated with a given procedure is not known until the time of the call at run-time.

//“Hello World” program

#include “stdafx.h”

#include <iostream>

using namespace std;

int main()

{

cout << “Hello World\n”;

return 0;

}

A C++ program is a collection of functions. The above example contains only one function, main(). Execution begins at main(). Every C++ program must have a main().

cout ( C Out) represents the standard output stream in C++

The operator << the insertion or put to operator. It inserts the contents of the variable on its right to the object on its left, as it is shown in Figure 2.1 Here, the identifier cout is a predefined object representing the screen and it has a simple interface. If string represents a string variable, then the following statement will display its contents:

cout << string;

The operator << is also the bit-wise left-shift operator is an example of an operator overloading, an important aspect of polymorphism. We have used the following #include directive:

#include <iostream>

This directive causes the preprocessor to add the contents of the iostream file to the program. It contains declarations for the identifier cout and the operator<< . The header file iostream should be included at the beginning of all programs that use input/output statements.

Namespace is a new concept introduced by the ANSI C++ standards committee. This defines a scope for the identifiers that are used in a program. For using the identifiers defined in the namespace scope we must include the using directive,like:

using namespace std;

In C++, main() returns an integer type value to the operating system. Therefore, every main() in C++ should end with a return(0) statement; otherwise an error may occur. The return type for main() is thus explicitly specified as int.

### A slightly more complex program

Assume that we would like to read two numbers from the keyboard and display their average on the screen.

#include “stdafx.h”

#include <iostream>

using namespace std;

int main()

{

float number1, number2, sum, average;

cout << “Enter two numbers: “; // prompt

cin >> number1; // reads number

cin >> number2; // read number from the keyboard

sum = number1 + number2;

average = sum / 2;

cout << “Sum=” << sum << “\n“;

cout << “Average=” << average << “\n“;

return 0;

}

Comments:

The program uses four variables that are declared as type float by the statement

float number1, number2, sum, average;

All variables must be declared before they are used in the program.

Input Operator. The statement:

cin >> number1;

causes the program to wait for the user to type in a number, which is placed in the variable number1. The identifier cin ( C in) is a predefined object in C++ that corresponds to the standard input stream.

The operator >> is known as extraction or get from operator. It extracts the value from the keyboard and assigns it to the variable on its right. This operator can also be overloaded. Cascading of Input/Output Operators

We have used the insertion operator << repeatedly in the last two statements for printing results:

cout << “Sum=” << sum << “\n”;

cout << “Average=” << average << “\n”;

First, send the string  “Sum=” to cout and then sends the value of sum. Finally, it sends the newline character \n so that the next output will be in the new line. When cascading an output operator we should ensure blank spaces between different items. The two statement can be combined as:

cout << “Sum=” << sum << “\n”

<< “Average=” << average << “\n”;

This is one statement but provides two lines of output. We can also cascade input operator >> as shown below:

cin >> number1 >> number2;

The values are assigned from left to the right.

Note: I recommend Visual Studio IDE (Interface Development Environment) ,  and after Introducción a C++ en Visual Studio.

Source:

Review by: Larry Francis Obando – Technical Specialist – Educational Content Writer.

Escuela de Ingeniería Eléctrica de la Universidad Central de Venezuela, Caracas.

Escuela de Ingeniería Electrónica de la Universidad Simón Bolívar, Valle de Sartenejas.

Escuela de Turismo de la Universidad Simón Bolívar, Núcleo Litoral.

Contact: Caracas, Quito, Guayaquil, Cuenca – Telf. 00593998524011

WhatsApp: +593984950376