LEARN C++ IN ONE DAY AND LEARN IT WELL: LEARN CODING FAST WITH A P RACTICAL S TEP - BY - S TEP P ROGRAMMING G UIDE

1,959 360 4MB

English Pages [79] Year 2020

Report DMCA / Copyright

DOWNLOAD FILE

Polecaj historie

LEARN C++ IN ONE DAY AND LEARN IT WELL: LEARN CODING FAST WITH A P RACTICAL S TEP - BY - S TEP P ROGRAMMING G UIDE

Table of contents :
Chapter 1. C++ Introduction
Chapter 2. Functions
Chapter 3. Functions
Chapter 4. Files
Chapter 5. Conclusion

Citation preview

LEARN C++ IN ONE DAY AND LEARN IT WELL: LEARN CODING FAST WITH A PRACTICAL STEP-BYSTEP PROGRAMMING GUIDE DR. M OUBACHIR M ADANI F ADOUL Copyright © 2020 by Dr. Moubachir Madani Fadoul All Right Reserved

No part of this publication may be reproduced, distributed, or transmitted in any form or by any means, including photocopying, recording, or other electronic or mechanical methods, or by any information storage and retrieval system without the prior written permission of the publisher, except in the case of very brief quotations embodied in critical reviews and certain other noncommercial uses permitted by copyright law.

TABLE OF CONTENTS Chapter 1. C++ Introduction Chapter 2. Functions Chapter 3. Functions Chapter 4. Files Chapter 5. Conclusion About The Author Other Books By DR. MOUBACHIR MADANI FADOUL

CHAPTER 1. C++ INTRODUCTION

Why Use C++ C++ is one of the widely popular programming languages used in the world. C++ is available in today's operating systems, Embedded systems and graphical User Interfaces. C++ is an object-oriented programming language which allows code to be reused, and gives a clear structure to programs and lowering development costs. C++ is portable and can be used to develop applications that can be adapted to multiple platforms. C++ is handy and easy to learn! As C++ is close to Java and C#, it is easy for programmers to switch to C++ or vice versa

1.2 C++ GET STARTED

This step-by-step tutorial book teaches you the basics of C++. Any prior programming experience is not required. Two things are need before start using C++:

Many compilers and text editors to choose from are available. In this step-bystep tutorial book, IDE will be used (see below). C++ Install IDE An “IDE (Integrated Development Environment)” is used to compile AND edit the code. Popular IDE's Code include: Eclipse, Visual Studio, and Blocks. All are free, and they can be used to both debug and edit C++ co Note: based can work, but with limited functionality.

Web-

Code:: Blocks is used in our step-by-step tutorial book, which is the correct way to start. You can find the latest version of Codeblocks at http://www.codeblocks.org/downloads/26. Download the setup.exe of mingw file, which installs the text editor with a compiler. C++ Quickstart We create our first C++ file as follows. “Open Codeblocks and go to File > New > Empty File. Write the following C++ code and save the file as myfirstprogram.cpp (File > Save File as)”:

If you don't understand the code above, don't worry – the details will be discussed in later chapters. For now, you focus should be on how to run the code.

it

should

look

like

this

In

Codeblocks,:

Then, go to “Build > Build and Run” to execute (run) the program. The below example shows the result:

Congratulations! Now you have written and executed your first C++ program.

1.3 C++ SYNTAX The following code breaks up to understand it better:

Example explained

Omitting Namespace Some C++ programs can be executed without the need for standard namespace library. The namespace std line is omitted and changed to the std keyword, followed by the “::” operator for some objects:

1.4 C++ OUTPUT (PRINT TEXT) Together with the > on “cin” to display a string entered by a user:

A space is considered in “cin” (tabs, whitespace, etc) as a terminating character, which means that even if you type many words, it can only display a single word:

From the example above, the program is expected to print "John Doe", but it prints only "John". That's why, the “getline() function” is often used to read a line of text, when working with strings. The first parameter takes “cin”, while, and the string

variable as second:

1.19 CONDITIONS AND IF STATEMENTS From mathematics, the usual logical conditions are supported by C++:

To perform different actions for different decisions, these conditions can be used. The following conditional statements are supported by C++:

1.20 THE IF STATEMENT To specify a block of C++ code to be executed if a condition is true, the “if statement” is used.

The example below tests two values to find out if 20 is greater than 18. If the condition is true, print some text:

Example explained The example above uses two variables, y and x, to test whether “y” is greater than “x” (using the “> operator”). As y is 18, and x is 20, and its known that 20 is greater than 18, The screen prints "x is greater than y".

1.21 THE ELSE STATEMENT To specify a block of code to be executed, the else statement is used, if the condition is false.

Example explained The example above, (time > 18) time is greater than 18, so the condition is false. Because of this, the else condition in introduced, this print to the screen "Good evening". If the time was less than 18 (time < 18), the program would print "Good day".

1.22 SWITCH STATEMENTS

to select one of many code blocks to be executed, use the switch statement.

To calculate the weekday name, the weekday number is used in the example:

1.23 THE BREAK KEYWORD

The C++ breaks out of the switch block, when it reaches a break keyword. This stops the code execution and case testing inside the block. The job is completed if a match is found, it's time for a break. More testing is not needed.

1.24 The default Keyword Some codes are specified by the default keyword to run, if there is no case match:

1.25 FOR LOOP Use the for loop instead of a while loop, in case you exactly know how many

times you want to loop through a block of code:

Example explained Statement 1 before the loop starts (int i = 0), sets a variable. Statement 2 the condition for the loop to run (i must be less than 5) are defined. The loop will start over again. If the condition is true, if it is false, the loop terminates. Statement 3 increases a value (i++) each time the code block in the loop has been executed. Another Example This example prints only even values between 0 and 10:

1.26 BREAK The break statement has already been used in an earlier chapter of this stepby-step tutorial book. It jumps out of a “switch statement”. The break statement jumps out of a loop. When i is equal to 4, this example jumps out of the loop:

1.27 CONTINUE The continue statement breaks one iteration inside the loop, provided that specified condition occurs, and continues with the next iteration in the loop. The value of 4 is skipped in this example:

1.28 ARRAYS To store multiple values in a single variable, arrays are used, instead for each value, declaring separate variables.

Define the variable type, by declaring an array, specify the name of the array followed by “square brackets” and assign the number of elements to be stored: string cars[4]; To hold an array of four strings, a variable is declared. To insert values to it, an array literal is used - place the values in a comma-separated list, inside curly braces:

1.29 ACCESS THE ELEMENTS OF AN ARRAY By referring to the index number, you access an array element. The value of the first element in cars is accessed in this statement:

1.30 CHANGE AN ARRAY ELEMENT By referring to the index number can change the value of a specific element,:

1.31 CREATING REFERENCES

A reference variable is a "reference" to an existing variable, and it is created with the “& operator”:

1.32 CREATING POINTERS From the previous chapter, you learned that we get the “memory address” of a variable by using the & operator:

To

stores

the memory address as its value, a pointer is used. A pointer variable is created with the * operator and points a data type (“like int or string”) of the same type. The variable address you're working

with is assigned to the pointer:

Example explained By using the asterisk sign * (string* ptr), create a pointer variable with the name” ptr”, that points to a “string” variable. Note that the type of the pointer must match the type of the variable you are working with. To store the memory address of the variable called food, use the & operator, and assign it to the pointer. Now, ptr holds the value of food's memory address.

CHAPTER 2. FUNCTIONS A block of code which only runs when it is called is defined as a function. In a function you can pass data, known as parameters.

Functions are performing certain tasks, and they are necessarily for reusing code: Define the code once, and use it many times. Create a Function Some pre-defined functions are provided in C++, such as “main()”, which executes code. But its possible to create your own functions in order to perform certain actions. To create (often referred to as declare) a function, specify the name of the function, followed by parentheses ():

2.1 CALL A FUNCTION Declared functions are "saved for later use", and will be later executed, when they are called.

Declared functions are not executed immediately. Calling a function can be done by writing the function's name followed by two parentheses () and a semicolon; In the following example, “myFunction()” is used to print a text (the action), when it is called:

2.2 FUNCTION DECLARATION AND DEFINITION A C++ function consists of two parts:

However, the declaration and the definition of the function - for code optimization can be separate. You see often C++ programs that have function definition below main(), and function declaration above main(). This will make the code easier to read, and better organized:

2.3 ARGUMENTS AND PARAMETERS Information is entered into functions as a parameter. Inside the function, parameters act as variables. After the function name, parameters can be specified, inside the parentheses. If you want to add as many parameters as you want, just separate them with a comma:

In the following example a function takes a string called fname as parameter. When the function is called a first name is passed along, which is defined inside the function to “print the full name”:

2.4 RETURN VALUES The void keyword that used in the previous examples specifies that the function cannot return a value. If you want the function to return a value, try to use a data type (such as “int, string”, etc.) instead of “void”, and use the return keyword inside the function:

The result is also stored in a variable:

2.4 FUNCTION OVERLOADING The function overloading allows multiple functions to have the same name with different parameters:

The following example is having two functions that add numbers of different type:

It is better to overload one, instead of defining two functions that should do the same thing. The example below overloads the “plusFunc function” to work for both “double” and “int”:

CHAPTER 3. FUNCTIONS WHAT IS OOP? “OOP stands for Object-Oriented Programming”. Procedural programming is the functions that perform operations on the data or writing procedures, while object-oriented programming is creating objects that contain both functions and data. “Object-oriented programming” possesses many advantages “over procedural programming”:

3.1 WHAT ARE CLASSES AND OBJECTS?

Objects and classes are the two main aspects of object-oriented programming. The following illustration illustrates the difference between objects and class:

Another example:

So, “a class is a template for objects, and an object is an instance of a class”. After creating the individual objects, individual objects inherit all functions and the variables from the class. The next section teaches much more about objects and classes.

3.2 CLASSES/OBJECTS C++ is an “object-oriented programming language”. Everything in C++ is connected with objects and classes, along with its methods and attributes. For example: in real life, a bicycle is an “object”.

The bicycle comes with attributes, such as weight and color, and methods, such as drive and brake. Methods and attributes basically are functions and variables that associated with the class. These are named often as "class members". A class is a user-defined data type to be used in our program, and it worked as an object constructor, or a "blueprint" to create objects.

3.3 CREATE A CLASS Use the class keyword, to create a class:

Example explained

3.4 CREATE AN OBJECT An object is created in C++, from a class. the class named “MyClass” is already created, so now by using this we can create objects. Creating an object of “MyClass” is done by specifying the class name, followed by the object name. Use the dot syntax (.) on the object, to access the class attributes (myString and myNum ):

The following example defines a function inside the class, and names it "myMethod".

Defining a function outside the class definition, can be done by declaring the function inside the class and then defining it outside of the class. This is

achieved by defining the name of the class, followed the scope resolution :: operator, followed by the function’s name:

3.8 ENCAPSULATION The idea of “Encapsulation”, is to ensure that "sensitive" data is kept hidden from the users. Achieving this by declaring class variables/attributes as private (cannot be accessed from outside the class). Providing the public get and set methods helps modifying or reading the value of a private member.

3.9 ACCESS PRIVATE MEMBERS Use public "get" and "set" methods, to access a private attribute:

Example explained The salary attribute is set to private and have restricted access. The public “setSalary() method” takes a parameter (s) and assigns it to the salary attribute (salary = s). The value of the private “public getSalary() method”.

salary

attribute

is

returned

by

the

Inside main(), we have created an object of the Employee class. Now the “setSalary() method” is used to set the value of the private attribute to 50000. Then we call the “getSalary() method” on the object to return the value.

WHY ENCAPSULATION?

3.10 INHERITANCE It is possible in C++ to inherit methods and attributes from one class to another. The "inheritance concept" is grouped into two categories:

,

Use

the “:” symbol, to inherit from a class. The example below shows from the Vehicle class (parent), the Car class (child) inherits the methods and attributes

CHAPTER 4. FILES To work with files, we use the “fstream” library. To use the “fstream library”, include both the header file AND the standard :

4.1 CREATE AND WRITE TO A FILE

Use either the “fstream” or “ofstream” object, to create a file, and specify the name file. Use the insertion operator (