C++ Basic Introduction | Full Course

C++ Basic Introduction

I (Bjarne Stroustrup) developed C++ at Bell Labs in 1980.

It is very similar to C Programming that my mate, Dennis Ritchie, created in the early 1970s.

I developed C++ as an extension to the C language.

I developed C++ to provide Simula’s facilities for program organization together with C’s efficiency and flexibility for systems programming.

C++ is so much compatible with C that it probably compiles over 99% of C programs without changing a source code line.

Though C++ is a much well-structured and safer language than C as it OOPs based.

I would call C++ as the superset of C!

It is also right if we call C++ as “C with Classes”.

What is C++?

C++ is a general-purpose, object-oriented programming language.

By general-purpose, I mean that it has a wide variety of use cases and is used in large areas.

Now, what is an object-oriented programming language?

It is just a simple notion or a way of writing a program where we use classes and objects.

We will dive deep into this in the advanced part.

For now, let’s stick to the basics.

C++ is a middle-level language, as it encapsulates both high and low-level language features.

Also, C++ supports both procedural and object-oriented programming paradigms; therefore, C++ is also called a hybrid language.

Now, you have enough idea about what C + + is.

Why C++?

I developed C++ in 1980!

Yes, you heard it right in 1980.

It has been 40 years, and C++ is still strong there!

According to the Tiobe Index of Programming language, C++ is ranked 4th as of March 2020.

Does this motivate you to learn C++?

Why learn C++?

Well, I try to give you some more reasons to learn C++.

  • C++ is a MUST for students and working professionals to become great Software Engineers.
  • C++ is very close to the hardware, so you get a chance to work at a low level, which gives you much control in terms of memory management, better performance, and, finally, robust software development.
  • C++ programming gives you a clear understanding of Object-Oriented Programming.
  • C++ is one of the evergreen programming languages and is loved by millions of software developers.
  • C++ is the most used language for application and system programming.
  • Applications of C++

Some of today’s most visible used systems have their critical parts written in C++.

  • Bloomberg (financial formation),

  • Amazon (Web commerce), Google (Web search)

  • Facebook (social media)

Many programming languages depend on C++’s performance and reliability in their implementation. Examples include:

  • Java Virtual Machines

  • JavaScript interpreters (e.g., Google’s V8)

  • Browsers (e.g., Internet Explorer, Mozilla’s Firefox, Apple’s Safari, and Google’s Chrome)

  • Application and Web frameworks (e.g., Microsoft’s .NET Web services framework).

Moreover, C++ is used in,

  • C++ is used to create games and graphics.

  • C++ is used in ATMs from which you withdraw cash.

  • C++ is also used to create desktop applications which we use daily.

How does C ++ work?

Understanding the working of C++

So what is a programming language?

A notion through which we write commands for the computers so that they can understand and execute a particular task. Right?

Now, you must be wondering how the commands which we write in English like language are understood by the computer and how it acts accordingly?

Let me try to explain this in five simple steps.

  1. First, we write the commands in English-based C++ language.

  2. Then, the English-based commands are sent to a “Compiler.”

  3. The compiler’s job is to convert the English-like based commands into the binary combination of 1s and 0s).

  4. These numbers are then submitted to the computer.

  5. The computer reads these commands and performs the tasks.

Thus, this is how a C++ program works.

*C++ belongs to Middle-Level Language criteria

Our first C++ code

I am in no mood to break the traditions. We also start with the legendary Hello World program.

I am in no mood to break the traditions, so let us start with the legendary Hello World program.

 #include  

using namespace std; 

int main() {   

cout << “Hello World!”;   

return 0; 

}

Hello World

I know that feeling when you write your first program, and you get ‘Hello World’ printed onto the screen.

So let us try and understand our first code.

Let us break up the code to understand it better:

Line 1: #include is a source code file written by programmers that allow us to perform basic but important input and output operations, such as cout (used in line 5). Header files add functionality in an easy way to C++ programs.

Line 2: using namespace std means using names for objects and variables from the standard library.

Do not worry if right now you are unable to understand the meaning of #include and using namespace std.

Just think of it as something that always appears in our program. we will deep dive into this later.

Line 3: Another thing that always appears in our C++ program: 

 int main().

This is called main function.

Any code inside this curly brackets {} will be executed.

main()function is starting point of mostly C++ Programs.

Line 4: cout (pronounced “see-out”) is an object used with insertion operator (<<) to output/print text. In above example, it will print “Hello World” on the command line.

Note: Every C++ command ends with a semicolon (;)

Line 5: return 0 ends the main function.

Whenever the return type of a function is not void, we return some value.

In this example, the return type is int, and we return 0.

Again, don’t worry; we will study all this deeply later in the program.

Line 6: Do not forget to add the closing curly bracket } to actually end the main function.

Comments: What are they?

In this section, we will learn about comments.

What are comments?

Do they have to do with the comments that we make on our social media?

We comment on some pictures on social media, right?

Why do we do that? To describe something about that image, right?

Similarly, in programming, we comment to describe our code or to give some extra details about the code.

Comments in C++

C++ supports // single-line and /*………………*/ multi-line comments.

C++ compiler ignores the comment section part.

Single line comments start with //

Example:

 // This is a comment

Multi- line comments start with /* and end with */

Example :

 /* This is a multi-line comment 

We are learning C++ */

When the above written code is compiled, it will ignore the comment section part // prints Hello World.

Hello World

Understanding how to store data in C++

Computers have large memory spaces.

But as programmers, we need to utilize these spaces effectively.

Unlike our bedrooms, we don’t want this space to look messed up!

Hence, we use the concept of storing stuff in containers.

It is similar to how we keep food in containers inside the refrigerator.

These containers make it easy to access the stuff/food whenever we need it.

Let me introduce you to variables.

Now let’s assume you need to store something in your computer memory.

For this, you will need a container, just like the one you have in your refrigerator.

In programming, this storage container is called a variable.

Thus, remember the word “variable” as we will use this name a lot from now onwards.

It becomes much easier to identify the food in the container if you had put a label on the container in the refrigerator.

Similarly, we have to provide our storage container, also known as the variable, with a unique name so that it comes to our service whenever called upon.

Along with that, we also need to mention the type of value it will contain, e.g., words, numbers, etc.

The need for a variable

Now you might be thining about the use of variables? 

Rather it is any kind of application, a simple web application, where we will need to store login credentials or be it a game where we will store the game score, we use variables to store these things!

Thus, understanding that variables might be a simple concept but is a powerful one.

To understand it better, let’s compare the steps of storing food in containers to storing data in a variable.

  1. Identify one container: define the type of variable.

  2. Give the container a label: assign a name to the variable.

  3. Put food in the container: put a value in the variable.

That’s it! It is as simple as that.

Let us see how these steps would look in C++;

  • Define the type of variable: Let’s say we want to store your name, and your name would be a word, and a word in programming is called a string! We will dive deep into this in upcoming sections.

  • Give the container a label: firstName( the name we are giving to the container, TIP: Make sure that the names that you give to the container should be meaningful! It is a good practice.)

  • Put a value in the variable: firstName = “John” ()we assigned “John” to store in the container.

This is how it would finally look like:

 string firstName = “John”;

Now let’s print the value.

 cout << firstName;

John

Types of Data in C++

So, by this we are able to store data in C++.

Now let me take you ahead in this journey with an important concept, Data Types.

So, let’s stick to our refrigerator example.

We need different containers to store different items in our refrigerator.

Right?

Just like how you have different containers for water and milk, a computer programming language or any digital system, in general, has different “containers” to hold the different types of information it comes across.

These “container types” make the different data types.

  

Data Types

This allows for the separation of the types of operations that can be done on different pieces of information.

You want to be able to add the price of a pencil with that of a pen. Hence the price is identified as a specific type of data.

Whereas names are not to be arithmetically added.

So a system would put that in a different data type than a price.

Following are the basic data types in C++ that we are going to learn:

  • Integer (int) – To store numbers

  • Floating Point (float) – To store fractional/ decimal numbers

  • Double (double) – To store fractional/ decimal numbers with large points

  • Character (char) – To store single character/letter

  • String (string) – To store words/ sequence of characters

  • Boolean (bool) – To store boolean values, namely, true and false.

Now you know what the data types are and why we need them.

Also, you are familiar with the types, thus let’s see an example.

Let us say we want to create an application to store game scores.

So with the knowledge from the last section, let repeat the same steps and declare a variable with an appropriate data type that will be Integer because the game score will be a numerical value.

So your code should look like this:

 int gameScore = 0; 

cout << gameScore; 

Here, int is the data type, the game score is the variable name, and 0 is the initial value given to the variable.

Similarly, we can use float, double, char, a string to store the appropriate value according to the requirement.

So, go ahead and write some code to try these data types!

What are booleans?

Is your question – What is Boolean?

Sometimes we need data in programming where there can be only one of the two values, such as:

  • YES / NO

  • ON / OFF

  • TRUE / FALSE

C++ has a special datatype named as bool, which can take the values true (1) or false (0).

In many situations we need to check something that might derive a value yes/no, true/false.

Here, booleans come into action.

Scopes of storing data

What is a Scope?

Hey, I know what you are thinking!

Why we are discussing scope in a programming course.

Wait, this is not the scope that you usually talk about in your favorite game, PUBG!

We are going to discuss the scope of variables.

Scope

A scope is a region of the program, And it has been seen that there can be three types of scopes in any program, which are as follows −

  • Local Variables, (Inside a function)

  • Global Variables, (Function Parameters), and,

  • Formal Parameters. (Outside of all functions)

Local Scope

Variables that are defined within a function known as local variables

Global Scope

Variables which are declared outside of all function, i.e., which is not defined inside a function known as Global variables. 

Till then, you do not terminate the program; global variables keep their value.

It can be accessed by any function.

A program can have the same name for local and global variables, but the value of the local variable has more impact than global means inside a function local will take preference.

Taking user input

In most of cases our program need to take input from user. this is done using input functions. after that we are going to learn how to take input from user.

How?

We use a built-in variable named as cin to get input from user using command line.

cin is pronounced “see-in”.

cin is a predefined variablein c++ reads data from keyboard with the extraction operator (>>).

The syntax is similar to that of cout.

Let’s try to understand with an example.

string name; 

cout << “Enter your name:” 

cin>>name; 

cout<< “Name entered is:” << name;

Let’s try to understand the code,

First, we declare a variable name of string data type that will hold the value entered by the user.

Next, we print a nice statement for the user “Enter your name:”

After this, the cursor will wait for the user to enter some value since we have used cin.

Once the user enters the value, the value gets stored in the name variable.

In the end, we simply print the value entered by the user.

What is decision-making?

Thus, we make many decisions in our day-to-day life.

Now let me give you a more relevant example.

Let’s say you want to develop some game.

And you want to check whether the user is logged into the profile and then playing the game or not.

Thus, we want to make some decisions depending on some conditions.

Here comes the concept of decision-making in programming.

Decision-making is about deciding the order of execution of statements based on certain conditions or repeating a group of statements until a specific conditions are met.

Decision-making structures are required so that the programmer specifies one or more conditions or take decision on that basis. program executes statements on the basis of that conditions.

C++ provides following decision-making statement :

  •  if-else

  • Switch case

Decision making using if-else

Basically, if-else is a conditional statement.

You can use if alone or in combination with else.

In general, English, if-else, can be explained as either this (as if) or that (as else).

It is used in simple conditions where we have only two options. If-else can be effectively used by combining them in a smart way.

As in the above diagram, one can see that if the condition that is provided under if gets true, then the set of codes under if block gets executed.

And if it becomes false, then the set of statements under the Else block will get executed.

And the rest program follows the path.

Syntax

if(condition)

{

}

else

{

}

Above is the syntax of the if-else block.

If the boolean expression/Condition comes to true, then if block otherwise, the else block of code will be executed.

Decision making using switch case

Switch Case

What is it?

In simple terms,

Switch statement allows programmer to test a condition and based on the result the program can execute a particular set of statements. Switch-case is an alternative to if-else ladder. and the intersting thing is that code looks much cleaner.

Don’t worry, Let me explain to you.

The following rules are applied to a switch statement −

  • The expression used in a switch statement is some condition or a boolean expression.

  • In switch-case any number of case can be used but Each case must be followed by the value and a colon.

  • The constant-expression for a case and the switch variable both must have same data type.

  • When the value of switch variable after execution is equal to a case then the statements after that case are executited untill a break is found.

  • When the compiler founds a break then the control immediatly exit switch and executes next line after that.

  • logically every switch needs a break statement. But suppose we don’t write break after any case then compiler is not going to show any error, it simply executes untill break is found.

Like in real life suppose we don’t get any vehicle/LIFT for home we start walking(default Solution).

In same way in switch case we can write default case which is going to execute if non of cases is true.

NOTE: There is no need to write default case in the last.Or we can write default case in the beginning also.

What is looping?

In simple terms, looping means iterating over some tasks. Means doing the same task again and again untill a specfic condition is met.

An iteration is normal, just as in real life.

For example,

  • In a library, one could repeatedly read catalog cards to find the location of the book he wishes to read.

Please forget the computerized catalogs; assume to use the catalog card which exists on physical cabinets.

The iteration technique used might be different, but the task of reading catalog cards was still the same, which in the best case, only one read task was needed.

  • In the kitchen, one could repeatedly slice the onion when making pizza sauce.

The task to slice those onions is iterated.

  • Everywhere, one might repeatedly sing a song in an attempt to memorize it.

The task to sing those same songs repeatedly is an iteration.

Looping in Programming

Such situations can occur when you need to execute a block of code multiple times.

In general, statements are executed sequentially:

In a function, the first statement is executed first, then the second, and so on.

Programming languages provide a variety of and many types of control structures to allow for more complex execution routes.

C++ provides the following Loop control statements that we will learn in the subsequent sections:

  • For Loop

  • While Loop

  • Do while Loop

For Loop in C++

Let’s start with the first one: For Loop.

Syntax

for ( initilization; condition; increment ) {    

statement 1;

statement 2; 

}

The flow-control in a for Loop −

  • The initilization step is executed only once and at starting of loop.

This step allows us to declare and initialize control variables for loop.

  • Next, the condition is evaluated.

  • in this step we write conditions for control variables intilized in 1st step. these control variables are checked for condition. if condition comes true then the code inside loop will be execute.

If it is false, the cycle of repeating same task breaks, the control shifts to the next statement after loop and none of the Body statement is going to execute.

  • if the condition is true then After executing the body of the for loop , the control jumps back up to the 3rd step means increment or decrement the control variables intilized in 1st step.

This statement can be left blank as long as a semicolon appears after the condition.

  • The condition is now re-evaluated.

If it is true, the Loop executes, and the process repeats itself (body of loop, then increment step, and then again condition).

After the condition becomes false, the for loop terminates.

When the given code is compiled and executed, it prints numbers from 10 to 19

First, we initialize a variable a with value of 10

Next, we give a condition a< 20; this means the value of a should not be greater than or equal to 20.

Lastly, we increment the value of variable a by 1

Thus, In the first execution,

Value of a: 10

Gets printed.

Then the value of control variable is incremented by one and checked whether it is less than 20.

The same procedure continues until the condition becomes false and the control comes out of the Loop.

C++ while loop

A while loop is used to do a task continuesly until a given condition becomes true.

Now we are going to learn syntax of the while loop,

 while (condition) {    

statement s1; 

statement s2;

…statement sn;

}

Here, statement word refers to both single as well as group of statement.

The condition can return any value true or false. In General any value other than zero is considered true.

The loop is going to repeat untill the condition is true.

Control passes to the line immediately following the Loop when the condition becomes false.

Do while Loop

Now we are going to learn a special/ intersting loop control technique named as do-while loop. This allows program to executes first code and after that condition is checked. In the do while loop code is executed at least once.

rest Do-while loop works in same as while loop.

Syntax

do {    

statement(s1); 

statement (s2);

}  

while(c);

here c means condition used for control checking.

Notice in the do-while loop conditional expression appears at end , so the statement in the Loop executes minimum once before the condition is tested.

If the condition becomes true, the flow of control come back to do executes the block of statement again.

This process repeats until condition becomes false.

What is an array?

Imagine a box of cookies. If you look carefully, you can observe the below things.

A cookie box is a container that holds all the cookies.

Since it’s a cookie box, only cookies are stored in it.

Each cookie is in its unique position.

We can give numbers to cookies from 1 to 5

Each cookie can be picked up by its numeric position, like if you want to eat cookie number 4, then you would pick up the cookie at the fourth position.

Imagine you want to create such a kind of cookie box in programming which will help you store similar kinds of values, i.e., only cookies.

And you can access these cookies(values) whenever you want.

How do you think this can be achieved in C++?

The answer is by using ‘Arrays‘.

Let’s see how it is done.

What is an array?

The array is nothing but a container that helps you to store similar kinds of values, i.e., values of a similar data type.

These values are called Elements.

You can access each Element by its unique position in the array whenever you want.

This unique position is called an index.

Thus, An array in C++ is a collection of items stored at contiguous memory locations, and elements can be accessed randomly using indices of an array.

The index in the array always starts from 0.

The number of elements an array can store is called array Size.

Syntax:

 type arrayName[arraySize];

Type: The type of values to be stored in an array, Eg: int, string, etc.

arrayName: Name of the array

Arrays: the maximum amount of values that can be stored in an array.

Thus, let’s try to declare an array that would store roll numbers of 5 students.

 int roll_no[5];

Working with arrays

Assigning values to elements of an array is called array initialization.

Let’s initialize our array roll_no and store roll numbers of 5 students.

 roll_no[0]=45; 

roll_no[1]=89; 

roll_no[2]=16; 

roll_no[3]=10; 

roll_no[4]=23;

The numbers inside the square brackets are index.

We have already learned that each Element of an array is accessed by its index, and it always starts from 0.

The value of the elements at index 0 will be 45, at one will be 89, and so on…

Note that we can also combine the array declaration and initialization like below,’

 int roll_no[5]={45,89,16,10,23};

Accessing elements

As discussed earlier, an Element in an array is accessed by its index.

We can use ‘for’ Loop to access the elements by looping through its index.

 int roll_no[5]={45,89,16,10,23}; 

for (int i =0,i<5;i++){        

cout<< “Element at index ”<<i<<”is”<<roll_no[i]<<endl; 

}

Output

Element at index 0 is 45 

Element at index 1 is 89 

Element at index 2 is 16 

Element at index 3 is 10 

Element at index 4 is 23

Thus, the for loop will iterate through the index of the roll_no array, and we accessed the array elements by roll_no[i].

That was about arrays!

What is a Function?

Functions?

If you want a group of lines(viz, a module) in C++ to be run again and again with different values, you have to use functions.

(For the same values, you can copy-paste, but it’ll make the program messy and difficult to read.)

If you need to make a calculator, for example, you cannot write the codes for adding, subtracting, multiplying, dividing again and again.

Or, if your program needs to add ten different pairs of digits, you should use a function for this instead of writing the code ten times for different values.

Thus, the moral of the story is, functions allow us to group tasks together and use them in the places where we require them, rather than writing the same code again and again.

What are functions?

“A function is a block/set of statements that together perform a specific task.”

Every program in c++ has at least one function, which is main().

A function executes only when it is called.

  1. function

  1. The function is the entry point of any C++ program.

It is the point at which the execution of a program is started.

When a C++ program is executed, the execution control goes directly to the main() function.

Every C++ program has a main() function.

Why use the function?

Know you know what functions are…

Let’s see why we use them.

Functions are used for dividing a large code into modules; due to this, we can easily debug and maintain the code.

Any function can be called many times.

Advantages of functions

  • Code Reusability

  • Develop an application in module format.

  • Easily debug the program.

  • Enhance the Readablity of code.

Structure of Function

A function declaration we describe the information about function name, parameters type and return type.

A function definition provides the actual commands of the function.

functions are known with various names like a method or a subroutine or a procedure etc in various programming languages.

The C++ standard library providesa lot of built-in functions that we can use according to our need.

For example, cin, cout, and much more.

These are the functions that are already there in the system, and we haven’t defined them.

Declaring and Defining a function

we are going to define a demo function named as greater that takes two parameters num1 and num2, and returns the greater number of both −

 int greater(int num1, int num2) {    

// local variable declaration    

int result;      

if (num1 > num2){       

result = num1;    

}    

else{       

result = num2;    

}    

return result;  

}

So let’s try to understand the function that we just defined…

 int greater(int num1, int num2)

  • Above the line of code declares a function with a name greater, since it will return an integer value( the number which is greater), the return type will be int.

  • Next, it accepts two parameters, num1 and num2 (Two numbers from which we want to find the greater one)

Logic

 int result;   

if (num1 > num2){       

result = num1;   

}   

else{       

result = num2;   

}   

return result; 

Above is the logic to find the greater number.

But as of now, it does not work!

Why?

Because – A function executes only when it is called.

Function Calling

While creating a C++ function, we need to define what the function is going to perform.

To use a function, or that block of code we need to call or invoke that function.

When we calls a function, control is transferred to the called function.

After executing the code inside the block the control comes back and executes the next line after function calling statement.

To call a function, we have to pass the required parameters along with the function name, and if the function returns a value, then you can store the returned value.

We call the function in the main() function and pass the required parameter as given below,

 int main () {    

// local variable declaration:    

int a = 100;    

int b = 200;    

int ret;    

// calling a function to get the greater value.    

ret = max(a, b);    

cout << “Greater value amongst the two is : ” << ret << endl;    

return 0; 

}

Greater value amongst the two is: 200

That’s how functions work in C++.

Revisiting Strings

The term string refers to an ordered sequence of characters.In most programming languages, such strings are enclosed in either single or double-quotes.

In C++, the enclosing delimiters are double-quotes.

A string represents a sequence of characters.

C++ provides two types of string representations −

  • The C-style character string

  • The string class type was introduced with Standard C++.

The C-Style Character String

As C++ derives a lot from C, The C-style character is actually a one-dimensional array of characters that is terminated by a null character’ \0′.

String Class in C++

C++ library provides a string class or library that supports various operations and additionally much more functionality.

Let us check the following example −

 string name = ”John”; 

cout << name;

HINT: We have seen this in previous topics

The string is actually a class in C++ standard library.

It is defined in the standard library  or .

So when you declare an object of string, basically, you are instantiating an object of class string.

String Functions

We know a string is a class in C++.

Thus, it also contains some predefined functions in C++. Let’s check them out!

String functions

  1. strcpy(S1, S2): this is function used for making copy of string S2 and storing that into S1 string.

  2. strcat(s1, s2): Concatenates string s2 into the end of string s1

  3. strlen(S1) : Returns length of string S1

  4. strcmp(S1, S2): Returns 0 if S2and S1 are the same; less than 0 if s1<s2; greater than 0 if s1>s2

  5. strchr(S1, ch): Returns a pointer to the first occurrence of character ch in string S1

  6. strstr(s1, s2): Returns a pointer to the first occurrence of string s2 in string s1

Example

#include  

#include  

using namespace std; 

int main () {    

string str1 = “Hello”;    

string str2 = “World”;    

string str3;    

int len ;    

// copy str1 into str3    

strcpy( str3, str1);    

cout << “strcpy( str3, str1) : ” << str3 << endl;    

// concatenates str1 and str2    

strcat( str1, str2);    

cout << “strcat( str1, str2): ” << str1 << endl;    

// total length of str1 after concatenation    

len = strlen(str1);    

cout << “strlen(str1) : ” << len << endl;    

return 0; 

}

strcpy( str3, str1) : Hello strcat( str1, str2): HelloWorld strlen(str1) : 10

Recommended Books for c++





Leave a Reply

Your email address will not be published. Required fields are marked *