Showing posts with label Introduction. Show all posts
Showing posts with label Introduction. Show all posts

Object Oriented in C++: Introduction

 Before going into detail about a new programming paradigm (object oriented), let's understand a little what we were going to do and what we are going to do differently.


Functional Programming

So far, we have only used one programming style: functional, also called procedural. As the name says, it is a method that uses procedures, or as we call it: functions.

Basically, it is a script, a routine of procedures and commands. In other words, we only use variables and functions. Let's take an example.

Suppose you want to calculate the arithmetic average of two numbers, in C++. Necessarily, you will have to have two variables to store the values and an average calculation. There, there is a 'script' of what should be done.

What you can do differently, is to put the average in a function, so that it can be invoked indefinitely:

#include <iostream>
using namespace std;

float average(float num1, float num2)
{
    return (num1+num2)/2;
}

int main()
{
    float num1, num2;

    cout<<"Number 1: ";
    cin >> num1;

    cout<<"Number 2: ";
    cin >> num2;

    cout<<"Average: "<< average(num1,num2) << endl;

    return 0;
}

See how this program is just a procedure, it starts running from the beginning of main() and goes to the end of it. Always. Everything we did was always like this. It has a beginning (usually variable declaration), a middle (calling functions to do various things) and an end (showing results).

The purpose of functional programming is to create functions that do things. It may seem simple and fool right? But incredible things were done using this. The Linux Kernel, for example, does not use C++, only C, that is, it has no object oriented, only procedural programming.

Over the years and decades, software has become more and more and more and more, and a little more, complex. And some problems were emerging.


Oriented Object Programming

So far, in our programs, any function could work on any data. This over time became a security issue. It would be ideal if certain functions could act only on some data.

For example, in functional programming, functions that work with a company's Treasury data could work with any data, such as that of Employees. But it would be better if the treasury had its own functions and to work with employee data, they had their own functions as well. And for the sake of security, none could touch the things of others.

Another problem: you assign a function to receive an integer. Someone accidentally uses this function and sends a float. If you do this test, it will give an error, the wrong answer will come out and it can even simply close the program by running. Can you imagine 'closing' the program of an airplane, in mid-flight? It's not cool, right?

Hence the blessed and beautiful OOP: Object Oriented Programming. It solves these problems, and in an incredibly simple and easy way. Its secret is: it starts working with something called an object.

Each object will have its own variables and only a few functions can see it act on it.

If you have a Sound object in your game, it will have specific variables, characteristics and functions acting on it. Character type objects will have specific variables, characteristics and functions for them. A function that affects Sound cannot act on a Character type object. And, wow, that avoids many bugs and potential problems.

That of each object having its data and procedures, is the so-called encapsulation, the basis of the OOP logic. It is as if there is a specific code for each 'thing'. A function only sees data for that 'thing' and can only act on that 'thing'. You can even hide information, say clearly: 'Hey, this variable here, which stores the password, can only be seen here inside the server, it is inaccessible to users outside'. And that brings incredible security.

If you are developing a game in C++ and use object orientation, you will create data and procedures that will only act and make sense in the Logic part. It will create information and functions that will only be visible and will only act on Graphics, you will create specific things for the Scenario (which are not even visible outside this scope). You encapsulate, you divide, you organize things ... are you getting the idea of OOP?

It is no longer that mess of functions and variables that everyone can see and use. A declared variable should generally only be used by the X() function. But the Y() function can indeed see and act on this variable, this is an error, a problem, and it would be interesting if this were naturally impossible, if the language itself made this separation. And it is this separation that Object Oriented does.

If you make a Web system, you want only a few functions to be available to users, such as the function Display(), which will show the grades of an Distance Education student. But if you used functional programming, the evil student can create code that calls the ChangeGrade() function, to change your grades, to hack the system. Well, he may well "guess" the name of the functions, and he will get it right...

With object-oriented programming, we can make it very clear: "Hey system, only this function and these variables can be accessed by students". When he tries to invade the system, calling other functions that are not part of that 'object' (his grades, for example), he will be summarily blocked.

This object orientation is cool, right? But let's stop talking and go to the next tutorial and start learning how to use this awesome thing for good.

Study resources

Programming Paradigm
Functional Programming

Simple C++ Calculator: How to Program

To wrap up our C++ Getting Started section, let's make a very simple, but very useful and interesting program: a calculator.

Before you see the code, try to solve it.

It must receive two user numbers, and display the operations of:
  • Sum
  • Subtraction
  • Multiplication
  • Division of the first by the second
  • Rest of the division of the first by the second
  • Percentage of the first relative to the second
  • Arithmetic average

Your program should look like:
How to make create a simple calculator in C++


Try it!

How to make a calculator in C++

See how our code looked:
#include <iostream>
using namespace std;

int main()
{
    float num1, num2;

    //Receiving data
    cout << "First number   : ";
    cin >> num1;

    cout << "Second number  : ";
    cin >> num2;

    //Displaying operations
    cout << "Sum            : " << num1 + num2 << endl;
    cout << "Subtraction    : " << num1 - num2 << endl;
    cout << "Multiplication : " << num1 * num2 << endl;
    cout << "Division       : " << num1 / num2 << endl;
    cout << "Modulus        : " << (int)num1 % (int)num2 << endl;
    cout << "Percentage     : " << 100.0*(num1/num2) << endl;
    cout << "Average        : " << (num1 + num2)/2 << endl;


    return 0;
}
Yours, how was it? Different?
Put it in the comments!

See that the only thing different was the excerpt:
(int) num1% (int) num2

This is called casting, that is, since the module operator (rest of division) only makes sense with integer values and our variables are float, we put (int) before the variables to tell C ++ that we want to handle those variables, at that time, as integers.

Conversion between degree Celsius and Fahrenheit

In this tutorial, we will address two questions from our list of basic C++ exercises, about converting between Celsius and Fahrenheit temperatures.

The formulas that we will use are:

How to convert from Fahrenheit to Celsius in C ++

How to convert from Celsius to Fahrenheit

Initially, let's do from C to F.
That is, the user enters the value in Celsius and the program returns the Fahrenheit.

The mathematical formula is the first above, which in C ++ language turns:
F = (9 * C / 5) + 32;

Look:
#include <iostream>
using namespace std;

int main()
{
    float C, F;

    cout << "Celsius degrees: ";
    cin >> C;

    F = (9*C/5) + 32;

    cout << "Represents in Fahrenheit: " << F;

    return 0;
}

Converting from Fahrenheit to Celsius

Now the opposite, using the second formula, which in C ++ is:
C = 5 * (F-32) / 9;

See how our code looks:

#include <iostream>
using namespace std;

int main()
{
    float C, F;

    cout << "Fahrenheit degrees: ";
    cin >> F;

    C = 5*(F-32)/9;

    cout << "Represents in Celsius: " << C;

    return 0;
}

C++ Basic Exercises

Congratulations, you have completed the basic part of our C++ Course.
Now let's practice.

Try with all your heart, with all your calm, effort and concentration, to do the exercises below.
Leave a comment with your solutions, ok?

C++ questions

01. Write a program that asks for the radius of a circle, and then displays the circle's perimeter and area.

02. Make a program that takes the radius of a sphere and calculates its volume.

03. Make a program that receives an integer, represented a value in years. Show how many days this time interval has, assuming a year has 365 days.

04. Make a program that receives two variables: the value of hours and minutes. Then convert everything to minutes and also to seconds.

05. Create a program that receives the temperature in degrees Celsius and converts it to Farenheit.

06. Do the opposite of the previous exercises.
Conversion between Celsius and Fahrenheit

07. Make a program that asks for the current year and your age, then displays your year of birth.

Percentage Exercises in C++

08. Make a program that calculates 12% of 2112

09. Make a program that receives a user value and calculates 12% of that total.

10. Make a program that receives a percentage value from the user, and calculates how much it represents from a second value that he typed.

11. Program software that receives two numbers, where the first must be less than the second.
It then calculates the percentage that the first represents from the second.
For example, if you entered 12 and 21, that means 12 represents 57.14% of 21

12. You have become a C ++ programmer, and now you are earning super good. But you will still have to pay taxes.
Create software that receives your salary and calculates the 7% income tax.

The output of your program should be gross salary (no rebate), the amount of tax you will pay and your net salary (after deducting IR).

13. Due to inflation, every year your salary should be adjusted based on it.
For example, if inflation was 2.5% then your salary should grow by the same amount so as not to lose value.
Create a C ++ program that asks for a person's salary, last year's inflation, and apply that inflation. Show previous salary, inflation increase, and new salary.

14. In the city of C ++ lland there is a tolerance of 15% of the speed limit so as not to be fined. Make a program that asks the user for the maximum speed of a road and calculates how fast the car can travel without being fined. Your code will be embedded in the car's GPS system to warn the speed limit the car must travel.
Solutions: Percentage in C++

Average exercises in C++

15. Create a program that asks the user for two grades, and returns their average.

16. Do the same as the previous exercise, but for 3 grades.

17. The MIT entrance exam weights are 3 for Mathematics, 2.5 for Physics, 2.5 for Chemistry, 1.0 for Foreign language and 1.0 for English. Create a system that asks for user grades and returns their average.

C++ Data Types, Variables, and Attribution: int, char, float, double, and bool

In this tutorial of our C++ course, we will learn how to work with data (information) in programming.

Storing Information

One of the pillars of computing is the storage of information, data.
The computer basically does two things: calculations and data storage.

Almost always, it does both: data processing, like store, change, delete, do math operations, and so on.

In this tutorial, although long is quite simple, we will introduce the concepts of data types and variables in C ++, highly important knowledge for working with computer programming.

Let us know the most varied types of data, their characteristics and functions.
Beforehand, know that every variable you will use to store data throughout your programs must be declared in advance.

Using a variable that has not been declared will result in errors at compile time.

The integer data type: int

This datatype is specifically for storing numeric data of the integer type.
The integers are:
  • ..., -3, -2, -1, 0, 1, 2, 3, ...

Let's now create and declare a variable called age:
  • int age;

Ready. At this point, the computer will take a place from your computer's memory and set it aside for the age variable. And what is stored? Initially, 'junk'.

Let's now assign the value 18 to this variable:
  • age = 18;

Now, whenever we use the number variable, it will be replaced by the integer 18.
Look:

#include <iostream>
using namespace std;

int main()
{
    int age;
    age = 18;

    cout << "My age is: "<< age <<endl;
    return 0;
}

Note that cout does not print the word 'age', but the value contained within this variable.
C++ complete and free tutorial

Character data type: char

In addition to integers, we can also store characters, ie letters.
For this, we use the keyword char (from character).

Let's declare a char variable, named letter.
  • char letter;

Now let's assign a value to it. In this case, as it is a char, we must store some letters of the alphabet, such as C:
  • letter = 'C';

Note that characters must be enclosed in single quotes.
Let's print this letter on the screen:

#include <iostream>
using namespace std;

int main()
{
    char letter;
    letter = 'C';

    cout << "The third letter of the alphabet is: "<< letra << endl;
    return 0;
}

Remembering that 'a' is different from 'A', are two distinct characters.

Characters are most commonly used together, forming text. We will study this in a later section, about Strings, in our course.

Understand:

  • 5 - is a number, a data of type int
  • '5' - is a character, a letter, cannot be used for example in mathematical operations

Floating Data Type: float e double

We have already learned to deal with integers.
However, not everything in life is an integer, like your age.

Often we need to work with fractional values, decimal values.
For this we use the float and double data types:

  • float price;
  • double value;


The difference is that float has single precision, and double has double precision (that is, it fits a larger fractional part, and a larger number of bytes of memory has been reserved for this type of variable).

Let's look at a use:

#include <iostream>
using namespace std;

int main()
{
    float price;
    price = 14.99;

    cout << "Progressive C++ e-book costs: $ "<< price << endl;
    return 0;
}
C++ tutorial


The Boolean data type: bool

You may have heard that in computing (or technology in general) it's all 1 or 0, isn't it?
In fact, the values 1 and 0 are very important because they represent true and false, consecutively.

There is a data type for storing only true / false information (called booleans), bool.
Declaring:

  • bool true;


Assigning a boolean value:

  • truth = true;


Displaying the value of true on screen:

#include <iostream>
using namespace std;

int main()
{
    bool truth;
    truth = true;

    cout << "Truth in C++ is: "<< truth << endl;
    return 0;
}

Results:
C++ tutorial


Exercises:

1. Make a C++ program that displays the value of two Boolean variables, showing each possible assigned value. Use two variables.

2. Redo the previous exercise, now declaring only one variable.

Variables names

Since we have full power to choose the name we want for our variables, we also have some responsibilities.

The first is not to choose keywords, which will be lists in the following topic.
Another responsibility is that of the organization.

You will be tempted to use:
int a, float b, char c

Avoid these names. Use:

int age;
float diameter;
char letter;

That is, variable names that mean something related to the value you will store there. This helps a lot when your programs get bigger and more complex.

Also avoid:
double salaryprogrammer;

Use:
double salary_programmer;

Or yet:
double salaryProgrammer;

Notice how this makes it easier to read and from the start we can already predict what kind of information you have in these variables, do you agree?

Reserved Keywords

There are some words you should not use as names for your variables, as they are reserved for the inner workings of C ++.

Are they:
and, and_eq, asm, auto, bitand, bitor, bool, break, case, catch, char, class, compl, const, canst cast, continue, default, delete, do, double, dynamic_ cast, else, enum, explicit, export, extern, false, float, for, friend, goto, if, inline, int, long, mutable, namespace, new, not, not_ eq, operator, or, or_eq, private, protected, public, reg i ster, reinterpret_cast, return, short, signed, sizeof, static, static_cast, struct, switch, template, this, throw, true, try, typedef, typeid, typename, union, unsigned, us ing, virtual, void, volatile, wchart, while, xorxor_eq

Exercise Answer

#include <iostream>
using namespace std;

int main()
{
    bool booleanValue;
    booleanValue = true;
    cout << "Truth in C++: "<< booleanValue << endl;

    vabooleanValuelorBooleano = false;
    cout << "False in C++: " << booleanValue << endl;
    return 0;
}

C++ simple output: cout, <<, endl, \n and Others special characters

In the previous tutorial, we learned how to create the first C ++ program, famous Hello, world! or hello world !.

To do this, we use a very special command: cout.
Let's deepen our studies on this subject.
cout << endl C++ simple output

Simple output (printing on the screen):
cout and <<

What we did in the first C++ program was simply print a message on the screen.
We say that we printed something on the console (black screen of commands), or more specifically, made a C++ output to the screen.

Specifically, cout is a piece called an object. Specifically, an object of the ostream class.
Don't worry about those terms for now. Let's look at it in our C ++ object-oriented tutorials.

This command is standard output stream, ie it is the standard output of information. That is, through cout we can send information to standard output, which is the command terminal, the little black window that appears in front of you, when we run the program.

Let's now display the message: "Welcome to the Progressive C ++ course":
#include <iostream>
using namespace std;

int main()
{
    cout << "Welcome to the Progressive C++ course";
    return 0;
}
Run this program and see the result.

And the << operator signals that we are sending information (in this case, the text) to the cout command:
cout << something (something is being sent to standard output).

We can rewrite the program as follows:
#include <iostream>
using namespace std;

int main()
{
    cout << "Welcome to the"<<"Progressive C++ course";
    return 0;
}
Cool, right?

Let's now write on the screen:
cout command in C++

Just use the cout command twice, do you agree? Look:
#include <iostream>
using namespace std;

int main()
{
    cout << "Welcome to";
    cout << "Progressive C++";
    return 0;
}
Do not forget the semicolon at the end of each command. This is universal in C ++.

The result is:
\n special character

Oops! One minute! It was all stuck together, what was the problem?

End of line endl and \n

A string is nothing more than a text.
After the first sentence, "Welcome to the" there is a character, although we can't see it.

It's the line break, it's the same thing that happens when you wirte a text and hit ENTER key, it skips, it breaks to the next line.

We can solve this by using the endl (end line) command, which is a stream handler, see:
#include <iostream>
using namespace std;

int main()
{
    cout << "Welcome to the" << endl;
    cout << "Progressive C++";
    return 0;
}

Another way to break the line is by using the \ n character.

In this case, it goes inside the string, as if it were a text character:
#include <iostream>
using namespace std;

int main()
{
    cout << "Welcome to the\n";
    cout << "Progressive C++";
    return 0;
}
Note that we can even do this using just one cout command:
#include <iostream>
using namespace std;

int main()
{
    cout << "Welcome to the\nProgressive C++";
    return 0;
}
The character '\n' occupies 1 byte of memory in program execution. endl calls a system function to do the same effect as \n.

C++ special characters

\n is not called a special character. Let's look at some others:

  • \t - has the same effect as TAB in a text editor
  • \r - Carriage return: Position the screen cursor at the beginning of the current line, does not advance to the next line.
  • \a - Alert, on old machines produced a sound (a beep)
  • \\ - Used to print the character \
  • \'- Used to print the character ' (single quotes)
  • \"- Used to print character "(double quotes)

References

http://www.cplusplus.com/reference/iostream/cout/
http://www.cplusplus.com/reference/ostream/endl/