LongCut logo

C++ Tutorial for Beginners - Learn C++ in 1 Hour

By Programming with Mosh

Summary

## Key takeaways - **C++ is a high-performance language**: C++ is a high-performance language used for building performance-critical applications like video games, device drivers, and web browsers. It's also a great language for learning core programming concepts. [01:09] - **Mastering C++ involves two key areas**: To master C++, you need to learn the language's syntax and grammar, as well as the C++ Standard Library (STL). The STL provides pre-written code for common functionalities like data structures and algorithms, saving you from reinventing the wheel. [02:38] - **IDE choice doesn't hinder C++ learning**: While C++ programs are created using Integrated Development Environments (IDEs) like Visual Studio, Xcode, or CLion, the specific tool you use doesn't impact your understanding of the C++ language itself. The focus should remain on the language fundamentals. [04:19] - **The 'main' function is C++'s entry point**: Every C++ program has a special function called 'main' which serves as the entry point, analogous to a TV's power button. It's crucial to type 'main' exactly as shown, as C++ is case-sensitive. [08:25] - **Semicolons terminate C++ statements**: In C++, statements, which tell the operating system what to do, must be terminated with a semicolon. Forgetting a semicolon, as demonstrated, will result in a compilation error. [12:26], [15:17] - **Order of operations matters in C++**: When writing mathematical expressions, the order of operations (precedence) is crucial. Multiplication and division have higher priority than addition and subtraction, but parentheses can be used to alter this order. [36:44]

Topics Covered

  • Why is C++ still a dominant programming language?
  • You don't need to learn all of C++.
  • What is the basic anatomy of a C++ program?
  • Understand the subtle but crucial postfix vs. prefix operators.
  • Why you should always avoid 'magic numbers' in your code.

Full Transcript

welcome to the ultimate C++ course in

this course you're going to learn

everything you need to know about C++

from the basics to more advanced

concepts so by the end of this course

you'll be able to write C++ code with

confidence if you're looking for a

comprehensive easy to follow well

organized and practical course that

takes you from Zero to Hero this is the

right C++ course for you you don't need

any prior knowledge of C++ or

programming in general everything you

need to know about C++ is in one place

so you don't need to jump back and forth

between random tutorials my name is msh

hamadani I'm a software engineer with

over 20 years of experience and I've

taught millions of people how to code

through this Channel and my online

school code with.com if you're new here

be sure to subscribe as I upload new

videos all the time now let's jump in

and get

[Music]

started before we start coding let's

spend a couple of minutes and talk about

C++ what you can do with it and how to

master it C++ is one of the most popular

programming languages in the world and

is the language of choice for building

performance critical applications video

games device drivers web browsers

servers operating systems and so on

that's why it's used by large companies

like Adobe Google Microsoft Netflix and

even government agencies like NASA just

to name a few every 3 years we get a new

version of C++ and the latest version at

this time is version 20 the next version

is coming out next year now there are

people like our famous superstar

developer John Smith who think that C++

is no longer relevant because of the

newer languages like Java or C that is

not true C++ is still one of the fastest

and most efficient languages available

so if you want to build an application

that needs to be fast and use memory

efficiently C ++ is a great choice this

is an advantage that it has over

languages like C and Java C++ is also

one of the first languages often taught

to computer science or software

engineering students because it has

influenced many programming languages

like C Java JavaScript typescript Dart

and so on so if you're looking for a job

as a software engineer learning s++ is a

great investment and opens a lot of

doors for you according to indeed.com

the average salary of a C++ programmer

in the US is just over

$170,000 a year now to master C++ there

are two things you need to learn one is

the C++ language itself meaning the

syntax or the grammar of this language

the second thing you need to learn is

the C++ standard library or STL which is

a collection of pre-written C++ code

that provides functionality that is

required by many applications examples

are data structures like list lists and

maps and algorithms for searching and

sorting data these functions are

required in almost every application so

instead of us creating all this

functionality from scratch every single

time we can reuse some of the C++ code

in this library to quickly build

applications in this course we'll

explore major functionalities in the

standard library but the standard

library is huge so we'll only scratch a

surface if you want to learn more there

are books specifically written on this

topic now a lot of people find C++ a bit

extensive and intimidating but in

reality you don't need to learn all of

C++ to be able to write substantial

programs for the same reason you don't

need to learn every feature your TV

provides just to use and enjoy it so in

this course we're going to explore C++

step by step and as we go I'm going to

show you how you can write some really

cool programs as you're learning C++

plus I'm going to give you plenty of

exercises to help you better understand

and remember the concept STS then you

will see that C++ is not really that

difficult so if you follow along by the

end of this course you'll be able to

write C++ code with confidence all right

next we're going to talk about the tools

you need to write C++

[Music]

programs to create C++ programs we use

an integrated development environment or

IDE which is basically an application

that contains an editor for writing code

as well as build and debugging tools now

there are so many different ideas out

there some of them are free the others

are commercial but the top three ones

are Microsoft Visual Studio for Windows

the Community Edition is free you can

get it from the link on the screen there

is also a Mac version but the one on the

Mac is not really that great for Mac you

can use xcode which you can get from the

App Store we also have cion which is

crossplatform so it runs on Windows Mac

and Linux you can trade for free for 30

days but then it requires a license if

you don't want to pay for a license you

can use one of the free Alternatives

again there's so many different ideas

available for creating C++ programs in

this course I'm going to use C lion but

you don't have to use it to follow along

you can use any tool you prefer because

our Focus here is not on tooling it's on

the C++ language itself now if you're an

absolute beginner and you have never

coded before I recommend you to download

the free version of celan so you can

easily follow along and then later you

can either get a license or use one of

the free

Alternatives so head over to Jet

brains.com

celion download again you can see we

have versions for Windows Mac OS and

Linux just note that if you're on Mac

make sure to download The Right DMG

because here we have two different

builds one is for Intel the other is for

apple silicon so depending on the type

of processor that your Mac uses make

sure to download The Right DMG because

the difference in performance is

significant all right so go ahead and

install this in the next lesson we're

going to create our first C++ program

[Music]

together so the first time you open C

lion you're going to see this popup box

for activating your license for now just

select start trial now you need to log

into your jet Brands account

so over here you can either sign in or

create a new account it's really simple

it's only going to take a minute or two

so I'm going to sign in with my

account good now back to cion we can

start our

trial now on this page we're going to

click on new project now on the top we

can specify the location of this project

so on my Mac it's going to be on users

SL my name/ celan project I'm going to

call this project hello world all in one

word without any spaces okay now over

here we can specify the C++ language

standard so by default version 14 is

selected but we can change that to a

higher version like 20 or 23 now because

23 is not official yet I would suggest

you to go with 20 good now let's create

this

project all right here's our first C++

program written in a file called

main.cpp if you accidentally close it

you can easily find it in the project

window so expand this folder and here is

main.cpp now we have another file in

this project called

cmakelists.txt we don't need that so

let's close it from here now we have the

same concept in other IDs like Visual

Studio or xcode so we have a project and

that project contains a file that is the

main file of our program now let's close

this window I'm going to delete all this

code because we're going to write it

from scratch so you understand how

everything works all right let's start

with a metaphor think of your TV your TV

has several functions it has functions

for changing the channel controlling the

volume and so on by the same token a C++

program consists of tens or hundreds or

thousands of functions each serving a

purpose now we have a special function

here called main which is the entry

point to our program this this is like

the power button of a TV okay now note

that C++ is a case sensitive language so

it's sensitive to lowercase and

uppercase letters so make sure to type

this exactly as I show you so if you

type a capital M here this is going to

have a different meaning okay so we're

defining a function now before the

function name we should specify the type

of value it's going to return this main

function should return a value of type

int which is short for integer and that

represents a whole number like 1 2 3 4

and so on so when we run our program the

operating system like Windows or Mac OS

is going to execute this function and

the value that this function returns

tells the operating system if our

program terminated successfully or not

okay so here we have int followed by

whitespace and then the name of the

function now whites spaces in C++ are

often ignored so whether we have one or

10 spaces it doesn't really matter but

in terms of formatting our code it's

better to go with one space because we

want to format this code professionally

just like how we write an article you

want to format our code just like a

published article okay now after the

function name we type a pair of

parentheses and inside the parenthesis

we can specify the parameters of this

function so a function can have zero or

more parameters for now let's not worry

about them we'll talk about them later

then we type a space again for proper

formatting followed by a pair of braces

now inside the braces we can type the

code for this function so whatever we

type here will be executed when the

operating system executes our main

function now once again in terms of

formatting there are two schools of

thought for adding the braces some

people like to add the left brace on the

same line as the function the other

people like to put the left brace on a

NE line there's really no right or wrong

here so whatever you prefer just stick

to that and make sure your code is

consistent in this course I'm going to

put the left brace on the same line

where we Define a function okay now in

this function we want to write code to

print something on the screen and for

that we're going to use the C++ standard

Library so earlier I told you that the

standard Library provides a bunch of

capabilities that we need in almost

every application so on the top we type

hashtag include and in angle brackets we

specify the name of one of the files in

the standard library that is IO stream

which is short for input output stream

in this file we have capabilities for

printing something on the screen or

getting input from the user so just like

a supermarket has different sections the

standard Library also has different

files each serving a purpose now as we

go through the course you will learn

about the other files in the standard

Library Okay so back to our main

function now here we type STD that is

short for standard library and this is

like a bucket or a container for the

features that are currently available to

us so the features we have imported on

the top okay so if you type double

colons we can see all these features now

there are a ton of features here don't

worry about any of them in this lesson

we're going to use see out that is short

for character out some people think this

is short for console out that is not

correct correct so using this object we

can output one or more characters on the

screen so we type a space followed by

two left angle brackets in other space

and then in double quotes we type the

text we want to print on the screen so

hello world okay and then we terminate

this line using a semicolon just like

how we terminate our sentences with a

period so in C++ this line is called a

statement because it tells the operating

system and what to do so whenever we

typee a statement we should terminate it

with a semicolon okay now finally we

return the value of zero and once again

we need to terminate this with a

semicolon but why zero well zero tells

the operating system that our program is

going to terminate correctly if we

return any other values positive or

negative that means our program

encountered an error okay so let's

quickly recap what we have done so far

on the top we included one of the files

in the standard library for printing

something on the screen then we defined

the main function which is the entry

point to our program now as you can see

the main function returns an integer

which is a whole number like 0 1 2 3 and

so on and in between the braces we have

written the code for this function so on

the first line we print something on the

screen and on the second line return the

value of zero as simple as that this is

your first first C++ program next I'm

going to show you how to compile and run

this

program now to run this program first we

have to compile this code to machine

code that can be run by the computer's

operating system so the machine code is

basically the native language that a

computer's operating system understands

and it's different from one operating

system to another so if we compile this

code on a Windows machine we get an

executable but that executable only runs

on Windows we cannot run it on Mac or

Linux if you want to run our application

on a Mac computer we have to take this

code on a Mac and recompile it to get an

executable for Mac okay so back to our

code to run this program we're going to

click on this play icon on the toolbar

now look at the shortcut on Mac it's

control and R always use shortcuts

because they make your life easier so

let's run this

program we get this little window down

the bottom this is called the console or

The Terminal window it's basically a way

to see the output of our program so over

here you can see the hello world message

so we're using a console application

here because console applications are

easier to create especially for people

learning a new language building

applications with a graphical user

interface or GUI is way more complex so

one once you understand the basics of

C++ you'll be ready to move on to

writing applications with a graphical

user interface if that's what you want

okay now let's minimize this window and

make a tiny problem in this code so I'm

going to remove this semicolon now let's

rerun our

program all right look this time we get

a compilation error pointing to this

line so the error is reminding us that

we have forgotten a semicolon if you're

starting out it's completely normal to

encounter these errors if you have a

typo or miss a semicolon and so on don't

let that discourage you remember

patience is the first skill of a good

programmer so if your code doesn't get

compiled pay close attention to this

video see what exactly I'm typing

compared with your code I promise if you

pay close attention you'll be able to

solve issues on your own so let's fix

the

issue all right let's move on to the

next lesson

[Music]

now going forward I want to change the

colors here and I wanted to show you how

to do that because a lot of people ask

me about the themes I use in my videos

if you're not using cion feel free to

move on to the next lesson so on the top

we go to the preferences

menu then under appearance and behavior

we select appearance now over here you

can see the themes that are installed by

default we only have four themes but we

can get more themes by clicking on this

link now on this page I'm going to sort

this list by the number of downloads so

we can see the popular ones I'm going to

pick Dracula theme it's a very popular

theme but feel free to play with these

themes and find the one that you

personally like so let's install

this

accept good now okay so this is the

dracul theme which is much better than

the default theme that comes with cion

so that brings us to the end of this

section in the next section we're going

to talk about the basics of C++ so I

will see you in the next

section now let me give you a quick

overview of how I've structured the

course so you can get the most out of it

this course is the first part of my

complete C++ series

each part is about 3 to 4 hours long so

you can easily complete it in a day or

two in the first part which is the one

you're watching we explore the basics in

this part you will learn the

fundamentals of programming in C++ data

types decision-making statements loops

and functions now throughout the course

I'm going to give you plenty of

exercises to help you develop your

problem solving skills and build your

confidence in writing code in fact many

of these exercises are popular interview

your questions in the second part we'll

explore intermediate level Concepts such

as arrays pointers strings structures

enumerations and streams and finally in

the last part we'll be talking about the

advanced concepts such as classes

exceptions templates containers and more

so by the end of this series you will

have a solid understanding of C++ and

you'll be ready to apply it in real life

for example if you want to build games

with Unreal Engine which is a popular

gaming engine you will have the

necessary C++ skills to build games you

just need to learn about Unreal Engine

so I hope you stick around and master

C++ one of the fastest and most

efficient programming languages

[Music]

available hey guys msh here I just

wanted to say that you don't really have

to memorize anything in this course I've

put together a complete cheat sheet and

summary notes for you that you can

download as a PDF right below this video

so click the link in the description to

download this PDF so I have done my best

to create the simplest C++ tutorial for

you so if you enjoy this please support

my hard work by liking and sharing this

video and also be sure to subscribe as I

upload new videos all the

time welcome back to the ultimate C++

course in this section we're going to

talk about the basics of C++ will cover

variables and constants naming

conventions coding mathematical

Expressions writing to and reading from

the console working with the standard

library and comments so by the end of

this section you'll be able to write

simple but really useful programs in C++

now let's jump in and get

[Music]

started all right let's talk about

variables in programming we use

variables to temporarily store data in

the computer's memory now technically a

variable is the name of a location in

memory where we can store some value now

because the value can change we refer to

this location as a variable now to

declare a variable in C++ first we have

to specify the type of data we want to

store let's say int or integer for

storing whole numbers then we give our

variable a proper meaningful name like

file size now there are various ways to

name our variables we have various

conventions we'll talk about them

momentarily once we declare a variable

then we terminate the statement with a

semicolon now I want to emphasize that

you should always use meaningful names

for your variables don't use

abbreviations like FS because someone

else reading this code may not know what

FS is short for also don't go for names

like F1 or F2 or thing these are all

cryptic and ambiguous okay so we're

going to call this file size and then we

can give it a value like 100 so we

assign it the value of 100 now here we

can combine these two statements into a

single statement and that makes our code

shorter and more concise so right here

where we declare our variable we can

give it an initial value of 100 this is

called initializing a variable now we

don't need the second line okay now

let's declare another variable for

storing numbers with a decimal point for

that we're going to use a different data

type that is double we're going to talk

about different data types in the next

section so in this section we're only

going to work with integers and doubles

now we're going to call this sales and

initialize it to

9.99 okay now that we have two variables

we can print them on the console so

instead of hello world let's print file

size run our program we see 100

beautiful now while initializing

variables is not mandatory it's a good

practice to follow let's see what

happens if we don't initialize file size

and print it on the terminal well

immediately we see this warning let's

take a look the warning is saying

variable file size is uninitialized when

used here initialize local variable file

size so our ID is complaining that we

are using using a variable that doesn't

have an initial value let's run our

program and see what happens take a look

look we get this random value and if we

run our program multiple times we see a

completely different value this is what

we call garbage this is the data that is

currently in memory so as a best

practice we should always initialize our

variables before using them so I'm going

to set this to an initial value of zero

now in languages like C or we don't have

to do this if we declare an integer it

automatically gets initialized to zero

but this is not how it works in C++ okay

so this is how we can declare and

initialize variables and by the way we

can also initialize multiple variables

on the same line so over here we can

declare a second integer let's call that

counter so we add a comma and then

declare counter and optionally we can

initialize it to some value now while

this works it's of discouraged as a best

practice we should declare each variable

on a separate line so I'm going to

remove this and declare another

integer like this okay now I have a

small exercise for you I want you to

write code to swap the value of two

variables this is a common interview

question so let me explain what I mean

we're going to declare two variables A

and B now if we print a we're going to

see one on the terminal right now here's

what I want you to do over here I want

you to write code to swap the value of

these variables so when we print a we

see two and when we print B we see one

now I don't want you to reset these

variables so I don't want you to set a

to two and B to one this is not the

right solution let me give you a hint

imagine instead of these two variables

we have two buckets the first bucket is

filled with apples the second bucket is

filled with oranges now if we have these

two buckets in real life how can we swap

their content think of a solution and

then use that idea to write code to swap

the value of these variables it's not

that difficult just spend a couple

minutes on this and then come back see

my

solution so to solve this problem in

real life we need a third bucket first

we empty our Apple's bucket into this

bucket now the apples bucket is empty so

we can move the content of the oranges

bucket here now the oranges bucket is

empty so we can move the content of the

third bucket into this bucket now we

have swapped the content of our buckets

right so let's use this idea to solve

this exercise we declare a third

variable we can call the temp and we

initialize it with what we have in a

that is the value of one now we can set

a to B so whatever we have in B which is

two two is now going to be in a and

finally we're going to set B to Temp so

B is going to be one so now if we print

a we're going to see two instead of one

let's verify this so let's run our

program there you go beautiful so this

was your first programming problem if

you got stuck don't worry it's

completely normal as we go through the

course I'm going to give you more and

more exercises to help you build your

confidence next we're going to talk

about constants

[Music]

there are situations where we don't want

the value of a variable to change this

is where we use constants here's an

example let's declare a variable of type

double and call it pi and set it to

3.14 now with this we can calculate the

area of a circle right but what if

somewhere in our program I accidentally

set pi to a different value like zero

with this our calculations are going to

go wrong right this is where we can use

a constant to prevent the value of pi

from changing how do we do that very

easy we type the con keyword before

declaring this variable now look on line

five we have a red underline that is a

compilation error so if you hover our

Mouse here we see the error saying

cannot assign to variable Pi with const

qualified type const double and also if

we try to run our

program here in the terminal window we

see an error so take a look this is the

error the error is happening in

main.cpp on line five in column 8 and

here's the actual error cannot assign to

variable Pi with con qualified type okay

so this will prevent us from

accidentally modify the value of this

variable or more accurately constant

[Music]

now let's talk about naming conventions

so we have different conventions for

naming our variables and constants and

different teams prefer different

conventions so there is really no right

or wrong here but let me show you the

popular conventions so earlier we

declared a variable called file size the

way we name this variable follows what

we call the snake case so with this

convention we have to use lowercase

letters to name our variables and

constants and if we have multiple words

we should separate them using an

underscore now we have another

convention called hascal case in which

we should capitalize the first letter of

every word so the same variable using

Pascal case looks like this this is

Pascal case and by the way the text that

I put here that starts with two forward

slashes this is is called a comment

we'll talk about comments later in this

section but for now just remember that

comments are a way to describe our code

they don't get compiled okay now we have

another convention that is similar to

Pascal case the only difference is that

the first letter of the first word

should be lowercase so file size this is

camel case we also have Hungarian

notation which is a pretty old notation

and it's not relevant anymore with hung

notation we should prefix the name of

our variables with a letter that specify

their type so here we have an integer so

we use a lowercase i and then file size

just like Pascal case this is called

Hungarian

notation now quite frankly this is a

very old notation it's not relevant

anymore but I still see people using it

I've seen it a lot in Windows source

code the reason this is not relevant

anymore is because in the old days we

didn't have editors so if we declared a

variable somewhere and we wanted to know

its type we had to scroll up to find the

type of that variable so with Hungarian

notation we could look at a variable and

immediately tell its type but this is

not the case anymore because these days

we have powerful editors if we simply

hover our Mouse over any

variable we can see it type so here you

can see file size is an integer variable

right so these are the popular

conventions out there in this course I'm

going to use camel case for naming our

variables and constants and Pascal case

for naming our classes we'll talk about

classes later in the course now if you

don't like these conventions and prefer

to use snake case that's totally fine

but make sure to stick to your own

convention the more consistent your code

is the easier it is to read understand

and maintain it next we're going to talk

about mathematical expressions

[Music]

so you have learned how to declare

variables and constants now let's see

how we can write mathematical

expressions for performing calculations

this is where the fun begins so I'm

going to declare two variables X and Y

now we can declare a third variable and

set it to x + y so what we have here is

called the addition operator and X and Y

here are called operat so now let's

print Z on the terminal so STD double

Colon c out Z take a look so now we see

13 beautiful we also

have subtraction

multiplication and division but division

is a little bit tricky in this case

because we're dealing with two integers

the result of the division is going to

be an integer even though in reality

dividing 10 by 3 is going to result in a

number with a decimal point which we

call a floating Point number in

programming so if you're onun our

program we see three but what if you

want to see a floating Point number well

changing the type of Z to double is not

going to solve this problem because as I

told you earlier if both our numbers are

integers the result of the division is

also going to be an integer so to get a

floating Point number we have to convert

one of these numbers to a double

so take a look first the warning goes

away now if you run our program one more

time look we get

3.3333 okay so this is how division

works in C++ now let me revert this back

to integer and integer now we have

another operator called modulus which

Returns the remainder of a division so

what is the remainder of division of 10

by 3 it's one let's verify it there you

go okay now using these operators we can

modify our variables let me show you

what I mean so for Simplicity I'm going

to remove Y and Z we only have X and

we're going to print it on the terminal

let's say we want to increment X by five

here's how we do it we Type X = x + 5 so

first this piece of code or this

expression is going to get evaluated the

result is 15 and then the result will be

stored in in X okay now similarly we can

subtract five from X we can multiply X

by five and so on okay now we also have

two more operators you need to know and

they are increment and decrement

operators so let's say we want to add

one to X we can say x = x + 1 that is

totally fine but there is a shorter and

more concise way to write this code we

can say

x++ this is the increment operator we

also have decrement operator but we

don't have the equivalent for

multiplication or division only

increment and decrement okay now this

increment operator there are two ways we

can apply it we can apply it as a

postfix or as a prefix let me show you

the difference so I'm going to delete

these two lines let's declare another

variable called Y and set it to X plus

plus if we apply this as a post fix

first the current value of x which is 10

is going to be assigned to Y so Y is

going to be 10 and then X will be

incremented by one so if you run our

program X is going to be 11 but Y is

going to be 10 let me show you so we

print x x is 11 but if you print

y y is going to be 10 okay so let me add

this as a comment for clarity in this

case X is going to be 11 and Y is going

to be 10 now what if we apply the

increment operator as a prefix so we

declare another variable and set it to

Plus+ X in this case because we applied

this operator as a prefix first the

value of x is going to be incremented by

one so X is going to be 11 and then the

result will be stored in

Z so in this case both x and z are going

to be 11 let's verify it so if you print

Z well in this case z is 12 I made a

mistake because in the previous

statement we incremented X by one so if

we comment out this line it's not going

to get executed so now when we run our

program X is going to be 11 and Z is

going to be 11 as well let's verify it

so here is z beautiful and let's also

print

X there you go

so here's what you need to take away if

you apply the increment or decrement

operator as a prefix first this piece of

code is going to get evaluated so first

X is going to be incremented by one and

then the result is going to be stored in

the other variable in contrast if you

apply this operator as a postfix first

the current value of x which is 10 is

going to be stored in y and then X is

going to be incremented by one

hey guys MOS here I hope you have been

enjoying this tutorial so far I just

wanted to let you know that this

tutorial is the first hour of my

complete C++ Series where you will learn

everything you need to know from the

basics to more advanced concepts so

watch this tutorial to the end and if

you still want to learn more use the

link below this video to enroll in the

full course the complete course contains

three parts each part being around 3 to

4 hours long so you can complete them in

a day twoo you will also get a

certificate of completion and a 30-day

money back guarantee again if you're

interested the link is below this video

in the description

box when writing mathematical

Expressions especially the more complex

ones you need to take into account the

order or priority of operators let me

show you what I mean so I'm going to

declare a variable called X

and set it to 1 + 2 * 3 now let's print

X on the console what do you think we're

going to get pause the video and think

about it for a second the answer is

seven this is a very simple math

question but unfortunately a lot of

people get it wrong here's the reason in

math the multiplication and division

operators have a higher order or a

higher priority so when evaluating this

piece of code or this expression first

this part is evaluated so 2 * 3 is six

and then six is added to one so the

result is seven let's verify it so I'm

going to run the program there you go we

have seven okay so here's what I want

you to remember in math or any

programming

languages the multiplication and

division operators always have a higher

priority than addition or subtraction

operators but we can always change the

order of these operators using

parenthesis so in this case if we wrap

this piece of code with parenthesis

first this piece is evaluated so 1 + 2

is three and then three is multiplied by

three so the result is going to be nine

let's verify it so run the program one

more time there you go okay now here's

your exercise for this lesson take this

mathematical expression and implement it

in C++

assume X is 10 and Y is 5 so if you

implement this correctly Z is going to

be 1.3 so pause the video and work on

this for a couple minutes then come back

see my

solution all right here's the solution

I'm going to declare X and set it to 10

then y we set it to five and for Z first

we have to add 10 to X but we have to

wrap this in parenthesis because this

whole thing is going to be our numerator

once we have the numerator then we're

going to divide it by 3 * y but here's

the tricky part we have to wrap this

whole expression in parenthesis because

the result of this expression is going

to be our denominator if you don't use

parenthesis here our denominator is

going to be three and the result is

going to be different so we wrap this

whole thing in parenthesis and now let's

print Z on the terminal so we should get

1.3 again if you didn't solve this

properly don't worry don't let that

discourage you remember you're a student

you're learning if you know everything

and you could solve every problem you

would be the one teaching right so don't

let that discourage you and let's move

on to the next

[Music]

lesson so you have learned how to write

to the console or The Terminal window in

this lesson I'm going to show you a few

more techniques of writing to the

console so let's start by declaring a

variable now let's say on the terminal

we want to print xal 10 how do we do

this well first we go in the STD

namespace and pick up C out which is an

object that represents the standard

output stream I know it's a mouthful but

let me explain it for you in programming

a stream represents a sequence of C

characters the standard output is our

console or terminal window so using C

out we can write a sequence of

characters on the standard output which

is our console window right now these

double left angle brackets are called

The Stream insertion operator it's an

operator for inserting something to our

output stream in this case we're going

to write a sequence of characters which

we specify using double codes now in

programming or C++ specifically this is

called a string we'll talk about strings

later in the course so here I'm going to

print x equals and right after we want

to print the actual value of x so we

terminate this statement and you see out

one more time but this time we print X

okay let's run our program and see what

we get so we see X is 10 beautiful now

we can combine these statements into a

single statement so we get rid of the

second C out and this semicolon and then

put everything on the same line now we

are changing multiple stream insertion

operators so if we run our program one

more time we get the exact same result

beautiful now what if we declare a

second variable so let's declare Y and

set it to 20 and then repeat so one more

time see out y equals and then we add

why take a look all right here's what we

get but wouldn't that be nicer if yals

20 was on the second line well to solve

this problem right here we need to add a

new line so once again we chain the

stream insertion operator and this time

we go in the city name space and pick up

endel which represents the end of the

line okay now let's run our program one

more time that is much better okay now

once again we can simplify this code by

combining these two statements so again

we don't need the second C out so let's

remove that and this semicolon as well

now if we run our

program we get the exact same result

however our code is not formatted

properly it's a little bit hard to read

this code so here I'm going to use tabs

and spaces to align these operators so

what we have in our code look exactly

like what we expect in the output okay

this is better now there is a tiny

problem in this code we have a bit of

repetition of STD double colons so we

have repeated this in two places let me

show you how to simplify this code so

before our main function we use the

using directive to pick up the STD name

space so here we type namespace STD now

STD is defined anywhere in this file so

we don't have to repeat it in multiple

places so we can simply access all

objects in the STD namespace so let's

remove that and this one as well and

finally let's

realign this brackets great so now our

code is cleaner more concise and easier

to read great now here's your exercise

imagine you have a store and you have

made

$95,000 now as part of your tax return

you have to pay state and County tax at

different rates so state tax is 4%

whereas County tax is 2% now I want you

to write code to show your total sales

as well as your state tax your county

tax and the total tax you have to pay on

this income so pause the video and work

on this exercise for 5 minutes then come

back see my

solution all right here's my solution

first we need a variable for storing the

total sales and for that I'm going to

use a double so even though we don't

have any scent values here but for

monetary values we should always use a

double so double sales equals

95,000 now right after let's print the

total sales here we add a dollar sign

that's nicer then we chain the insertion

operator to print sales followed by the

end of line now before going any further

let's run our program and make sure

everything works so run

total sales is $95,000

great next we need to calculate the

state tax so let's declare another

variable called state tax and here we

get sales and multiply it by

0.4 and then once again we print this on

the terminal so state

tax is this value followed by the end of

line now once again let's run our

program and make sure everything works

so this is how I want you to write code

write a bit of code run it make sure

everything works before going further

baby steps so

run so our estate tax is 3,800 great now

let's improve this code the first thing

I want to improve here is formatting so

the first two lines are about the total

sales whereas the second two lines are

about the state tax these are two

different stories right so here I add a

vertical line to separate these stories

just like how we have multiple

paragraphs in an article we want to

write our code so every story is

separated from other stories okay so

here's our state tax then I add another

vertical line to separate it from the

return statement great now this line is

totally fine but generally speaking it's

best to avoid magic numbers like this

here because even though this is a very

simple example in more complex programs

these mag magic numbers might be

confusing someone else reading your code

may not know what that number represents

so here we can make our code more

expressive by storing this value in a

separate variable so we declare a

variable called state tax rate and set

it to

0.4 and then we can reference that

variable right

here now it's completely clear what this

value represents it's our state tax rate

but this has another benefit if we use

this variable in multiple places in our

code and then tomorrow this dat tax

changes we don't have to come back and

modify multiple places we have a single

place where we have stored this value

okay now there is a tiny problem in this

code the problem is that I can

accidentally change theate tax rate how

can we solve this problem using a

constant so we qualify this with the

const keyword that's better now we have

to repeat the same three lines for our

County tax so I'm going to copy this and

paste it and again note the vertical

line this is to separate these stories

so over here we're going to rename this

to County tax rate which is going to be

2% and over here we going to calculate

the county

tax and print it

accordingly County tax good nothing new

and we should also replace state tax

rate with County tax rate so let me show

you a shortcut here look I haven't typed

County tax rate I just typed kind of an

abbreviation so count TR so we can use

abbreviations to quickly type our code

and press enter to complete it okay now

let's run our program and make sure

everything

works so our County tax is 1900

beautiful now the final part we declare

another variable called total tax which

equals State Tax Plus County tax and

finally we print it on the

terminal total tax okay so once again

see how I've named my variables all the

variables are properly named they're

meaningful there is no ambiguity in this

code we don't have t 1 T2 TR whatever

don't write code like that next we're

going to talk about reading input from

the

[Music]

user all right now let's see how we can

read input from the console so you have

learned that c out represents the

standard output string now in this file

in iio stream we have another object

called cin which represents the the

standard input stream which we can use

for reading data from the console let me

show you how first we're going to use C

out to print a label on the screen so

enter a

value now using C in we can read that

value and put it in a variable but first

we need to declare a variable so let's

declare an integer called value then we

use C in along with the stream

extraction operator to read that value

and put it in this variable able okay so

this is called the stream extraction

operator it's the opposite of stream

insertion operator I know it can be

confusing but the easiest way to

remember this is to think of the

direction of data flow so in this case

we have reading data from the console or

the standard input and putting it into

this variable in contrast with see out

you're basically getting this sequence

of characters and putting them into the

console so this is the way to remember

this okay now to verify that our program

works let's print the value that we just

read so let's run our

program enter value let's say 10 and we

get 10 in the output beautiful now what

if we enter a floating Point number a

number with a decimal point let's see so

this time I'm going to enter

10.1 the decimal part is gone because we

declared this value as an integer so if

you want to read a floating Point number

here we have to use a double type take a

look so one more time 10.5 now we get

10.5 beautiful now we can also read

multiple values so let's change this

label to enter values for X and Y now

let's declare two variables called X and

Y first we read X

and then we read Y and finally we can

print x + y this is like a simple

calculator so take a look we can enter

10 and 20 and the result is 30 now we

can also separate these numbers using a

space and the program will still work

take a look so one more time 10 space it

doesn't matter one or more spaces we add

the second number and we get the same

result okay now similar to see out here

we can chain these statements together

so we can get rid of the second

statement and chain the stream

extraction operator to read the second

value so look we start from the console

we read something and put it in X then

we read something else and put it in y

it's exactly like before but our code is

shorter so this is how we can read input

from the console now as your exercise I

want you to write a program for con

converting temperatures from Fahrenheit

to Celsius so when you run your program

the program should ask the user to enter

a temperature in fahrenheit and then it

should convert it to Celsius and print

it on a terminal so pause the video and

spend a few minutes on this then come

back see my

solution all right here's the solution

it's pretty easy first we use see out to

print a label like

Fahrenheit then we declare a variable

for storing the temperature in

fahrenheit

Fahrenheit next using C in we read that

value and put it in this

variable then we declare a variable of

type double called Celsius the reason

I'm using a double here is because the

conversion might result in a floating

Point number so here's the formula

Fahrenheit minus 32 we wrap this in

parenthesis and then divide it by

1.8 the finally using C out we print the

temperature in celsius now let's test

our program so 90 in Fahrenheit is

equivalent to 32.2 in

[Music]

Celsius so you have seen that the

standard Library gives us the capability

to read from or write to the console now

in this lesson we're going to look at a

different part of the standard Library

that gives us several useful

mathematical functions so on the top

we're going to use the include directive

one more time to include a file called C

maath this file declares a bunch of

useful mathematical functions now if

you're curious what these functions are

just go to Google and search for cmath

reference there are many different

websites that give you a C++ reference

one of them is C+ plus.com the other is

CPP reference.com and so on so as an

example let's look at this

page so over here you can see all the

functions declared in the cmath library

in this lesson we're going to look at a

couple of them one of them is Seal which

rounds up a value the other is floor

which rounds down a value now if you

click on any of these functions you can

learn more about it so on the top you

can see different versions of c and C++

so C90 and c99 represents the old C

language C++ 98 is one of the early

versions of C++ that came in year

1998 then we have C++ 11 that was

released in year 2011 so you can see how

this function has evolved over different

versions of C or C++ now don't get hung

up too much about these details all I

want you to pay attention to here is

that this function takes an input of

type double and returns

another double so let's see this in

action so back to the code here in the

main function to use the floor function

we type floor followed by a pair of

parentheses and then we Supply the input

value which is called an argument so we

pass 1.2 now we get a double value that

we can store in a variable so let's

declare a variable of type double called

result and set it to the return value of

the floor fun function and then we

terminate this statement with a

semicolon now over here we say that we

are calling the floor function which

means we're executing it we giving it a

value and getting a new value now we can

print the result just like before and

the result is one okay now some

functions take multiple values or

multiple arguments one of them is the

power or power function so let's take a

look

po requires two arguments here we need

to pass two values separated by comma so

if we say 2 comma 3 that means 2 to the

power of three now when we type this C

lion adds these labels lcpp underline X

and lcpp underline y these are the name

of the parameters of this function so C

lion adds this to make our code a bit

more understandable okay now if we run

this we get eight okay now as an

exercise I want you to write a program

that asks the user to enter the radius

of a circle and then it should print the

area of a circle it's pretty easy you

can knock it out in a couple of

minutes all right here's my solution

first we use see out to print a

label into radius then we declare a

double variable called radius next we

you see in

to read the value the user enters into

this

variable now we declare another variable

called area and here we have to use the

old formula pi * R to ^ of 2 so we can

type the pi number here but earlier I

told you that we should avoid magic

numbers as much as possible so we're

going to store this value Pi in a

separate

variable or even better we can make this

a constant okay now can say area equals

Pi * this is where we use the power

function to get radius to the power of

two as simple as that now finally we use

see out to print the area Let's test our

program so if we

enter 4 the area is

[Music]

5024 all right the last we're going to

cover in this section is comments we use

comments to clarify our code and to make

it easier to understand as I told you

before comments don't get compiled now

in C++ we have a couple of different

ways for writing comments we can start

with two forward slashes and whatever we

type in front of these slashes will be

considered a comment now we can add the

slashes above a line or in front of it

either way works but as you can see here

we have limited space because we're

basically bound to what is left here of

course we can write a longer comment but

then we'll have to constantly scroll to

the left and to the right to see what is

going on so it's more conventional to

write the comment above a line now if

you want to have multiple lines again we

can start a new line of comment like

this okay now in C++ we have another way

for writing a multi-line comment instead

of two forward slashes we start with a

forward slash

and an asterisk and then press enter now

cine automatically generates this block

of comment these two characters

represent the beginning of the block and

these two characters represent the end

of the comment block what we put in

between will be considered a multi-line

comment now different teams have

different preferences in terms of which

style of comments should be used so

there is really no right or wrong here

just pick one style and stick to it now

one thing I want to emphasize about

comments is that you should not overuse

them because they make your code harder

to understand and maintain so you should

use comments only to explain wise and

how not what let me show you what I mean

so here I can write a comment and say

declare a variable and initialize it to

zero well it is obvious that that's what

we're doing on the next line so this

comment is completely unnecessary and

it's making our code a little bit

verbose we don't want to sprinkle our

code with all these kinds of unnecessary

comments instead we should use comments

to explain wise and how's if you made

certain assumptions while writing this

code we should comment those assumptions

so in the future when we come back we

see why we did things in a certain way

okay so that's all about comments and

that brings us to the end of this

section so I will see you in the next

section welcome back to the ultimate C++

course in this section we're going to

explore the fundamental data types in

C++ in detail we'll talk about various

built-in types as well as their size and

limits more specifically we'll explore

various types for representing numbers

and their differences you will learn how

to generate random numbers which is a

very useful technique especially for

building games you will also learn how

to work with Boolean values characters

on strings as well as arrays which we

use for storing a list of values so by

the end of this section you will have a

deep understanding of these fundamental

data types and how to use them to write

useful programs so now let's jump in and

get

[Music]

started so you have seen that in C++ to

declare a variable we need to specify

its type that's why we say C++ is a

statically typed language meaning when

declaring a variable we need to specify

its type and this type cannot change

throughout the lifetime of our program

other examples of statically type

languages are C Java typescript and so

on in contrast to statically typed

languages we have dynamically typed

languages like python JavaScript and

Ruby in these languages we don't have to

give our variables a particular type the

type will be determined based on the

value that we assigned to these

variables and that type can change

throughout the lifetime of our program

okay so that is the difference between

statically and dynamically typed

languages now in C++ we have a bunch of

different built-in data types so far you

have only seen int and double but we

have more built-in types that we're

going to cover in this section in this

lesson I'm going to give you a basic

overview of these types but as we go

through this section you'll become more

familiar with these types so for storing

whole numbers we have int which takes

four bytes of memory on most systems

this is not a hard and fast rule

depending on the implementation the

number of bytes taken by an integer can

vary from one system to another but for

the most part you can assume that an

integer takes four bytes of memory in

four bytes we can store numbers from

minus 2 billion to plus 2 billion now if

you want to store a smaller number we

don't need to waste four bytes of memory

so we can use the short type which takes

two bytes of memory and in byes we can

store the values from - 32,000 to +

32,000 now for storing larger numbers we

have long which is often the same as int

on most systems and long long which

takes eight bytes of memory and allows

us to store really large numbers

speaking of experience most of the time

you'll be using short or in types unless

you're working on programs that involve

complicated mathematical computations

now for numbers with decimal places

which we call floating Point numbers we

have double which you have seen so far

the double type takes 8 bytes of memory

now we also have float which takes four

bytes of memory and long double which

takes 8 bytes of memory as well again

most of the time you would be using

double especially for storing monetary

values because the flow type can result

in loss of accuracy now we also have the

Bull type for storing true and false

values they're often used to represent a

condition like like is this person

eligible for a loan or not we also have

another built-in type called Char for

storing single characters so that was a

basic overview of the fundamental data

types in C++ again as we go through this

section we'll explore these types in

more

[Music]

detail now that you're familiar with the

basic built-in types in C++ let's let's

look at a few different ways to declare

and initialize variables so I'm going to

start by declaring a double called price

and we're going to set this to

99.99 nothing new so far but what if we

want to declare a float well we can

declare a float called interest rate and

we set it to

3.67 and here at the end we type the

letter F that is short for float this is

really important because if you don't

type this by default the compiler will

treat this number as a double and then

it will try to store a double inside a

float variable and this can potentially

cause data loss so when working with

float values always type an F at the end

it can be uppercase or lowercase it

doesn't really matter now there is

another reason we should type this

letter we'll come back to this shortly

now let's declare a long so long file

size we can set this to 990,000 now

similar to the float type here we should

add the L suffix because if you don't

type this the compiler will treat this

number as an integer so to force the

compiler to treat this as a long we type

either an uppercase or a lowercase L now

the lowercase L can be confused with the

number one so the best practice is to

use a capital l okay now let's declare a

variable for storing a character so we

say Char letter and here we use single

quotes to represent a character like a

okay and finally let's look at a

Boolean we're going to call this is

valid and we can set it to true or false

these are the acceptable values for

booleans now with any of these types we

can also use the auto keyword to let the

compiler infer the type of our variables

for example if we change bull to Auto

and then hover our Mouse over is

valid look the comp compiler knows that

is valid is of type bull similarly if we

change charart to Auto and look at the

type of this variable we can see it's of

type chart now here's the interesting

part if we change long to Auto we can

see that file size is of type long

because we added the letter L at the end

if we don't type this and use the auto

keyword look file size is treated as an

integer so that is why we need to add

this suffix similarly for floats if we

use Auto now we can see interest rate is

a float but if you remove the suffix it

will be treated as a double right so

this is the benefit of using the auto

keyword it kind of makes our code

shorter and more consistent you don't

have to use it if you don't like it but

the auto keyword is particularly useful

when working with more complex types

we'll look at that in the future now

there is one more way to initialize

variables in modern C++ that you need to

know and that's called brace

initialization so let me delete all this

code and declare an integer called

number and set it to

1.2 now here we get a warning because we

have a yellow underline but our code

still gets compiled so if we print

number and run our program we see the

fraction part is gone and we see one

okay now there is another way to

initialize this variable and prevent

this kind of scenario where we assign

the wrong value to a variable so instead

of the assignment operator we use braces

so we put this value inside braces now

look we have a compilation error because

we have a red underline so our code is

not going to get compiled the brace

initializer stops us from making such

mistakes now there is another benefit to

using brace initialization if we don't

Supply a value here our number variable

will be initialized to zero so if you

run this program we see number is zero

however if you remove the empty

initializer here and run our program

again you can see we get this random

value which we say it's garbage and

every time we run our program we get a

different value so this makes our

programs unpredictable so we should

either initialize our variables using

the assignment operator to a proper

value or we should use an empty brace

[Music]

initializer in math and programming we

have different number systems that serve

different purposes in our day-to-day

life we use decimal or base 10 numbers

which can contain digits 0 to 9 but

computers don't understand these digits

they only understand zeros and ones

that's why we have the binary or base

two system so the number in this system

can only contain zeros and ones now we

can take any number and represent it as

a binary for example the number 255 in

the decimal system is equivalent to 8

1es in the binary system it's a very

long number that's why we use the

heximal or base extend numbers to

shorten binary numbers a heximal number

can contain the digits 0 to 9 as well as

the letters a to f as you can see

heximal numbers are more common compact

now in programming we use heximal

numbers to represent colors you probably

heard of RGB or red green blue colors

using only six digits of a heximal

number we can represent any color that's

very useful we don't have to deal with

really large decimal or binary numbers

now let's see how we can represent these

numbers in

C++ so I'm going to declare an integer

called number and set it to 255 now if

you want to represent this number in the

binary system we type z b as a prefix

and then we type a binary number I'm

going to type 8 ones so 1 2 3 4 5 6 7 8

now let's print the number take a look

we get 255 okay now we can represent the

same number in the hexo decimal system

so instead of 0 B we type 0x and then we

type a hexo decimal number in this case

double F which can be operate case or

door case it doesn't really matter let's

run our program one more time look we

get the same number beautiful now most

of the time I would say 99% of the time

we use decimal numbers but depending on

the kind of application you're building

in some situations you may want to

represent a number as binary or

hexadecimal okay now irrespective of how

we represent numbers our numbers can be

positive or negative if we dealing with

a positive number we don't have to type

a positive sign it's assumed by default

but for negative numbers obviously we

have to type a minus now in C++ we have

a special keyword called unsigned if you

apply this to a numerical type that type

cannot accept negative values now on the

surface you might think this is a good

value but it can actually cause

programming problems that are hard to

spot for example let's print this number

on the console and see what we

get so we get this really large positive

number as another example we might

initialize this number to zero and then

somewhere else in our program we might

decrement this number now if we print

this instead of negative one we're going

to get this really large positive number

so my suggestion is to stay away from

the unsigned keyword just because C++

has this feature doesn't mean you should

use it that's why earlier in the course

I told you that you don't need to learn

all of C++ all of its features to build

use and substantial programs so stay

away from the unsigned

[Music]

keyword when working with numbers a

concept unit to understand is narrowing

and that happens when you initialize a

variable of a smaller type using a

larger type here's an example let's

declare an integer called number and set

it to 1

million now to make this code more

readable we can separate these digits

using a single quote that's better now

let's declare a short called another and

set it to

number now we immediately get this

warning saying narrowing conversion from

int to sign type short is implementation

defined I know it's a mouthful basically

the warning is saying that because we're

converting an integer to a short this

conversion is a narrowing conversion so

it's going to result in narrowing down

our number which is 1 million so now if

we

print another and run our program we see

16,000 this is the result of narrowing

conversion now obviously if we used a

brace initializer

here we could prevent this our code

wouldn't even get compiled so this is

another benefit of the brace initializer

okay now what if we do the opposite what

if we declare this number as

short and put it in an integer now in

this case we have a warning because this

number is too large to fit in a short

variable because as I told you earlier

using the short data type we can store

numbers from minus 32,000 to plus 32,000

so let's change this to let's just say

100 and then put it in an integer now we

can use the brace initializer or the

assignment operator it doesn't really

matter let's run our

program we get 100 so the opposite is

not an issue so the short type takes two

bytes the integer takes four bytes if

you store a smaller number in the larger

memory space we're not going to

encounter data loss so the additional

bytes in memory are going to be filled

with

[Music]

zero all right now let's see how we can

generate round random numbers in C++

this is very useful we can use random

numbers in creating games that involve

rolling a dice card or other elements so

we have a function called Rand that is

defined in a library called cstd lip so

on the top we need to include another

file from the standard Library called C

STD lib okay now we call this function

and get a random integer so let's store

it here and then print it on the

terminal now let's run this

program so this is the number I get on

your machine you're probably going to

get something different now here's the

thing every time we run this program we

get the exact same number the reason for

this is that these numbers are not

really random they're basically based on

some kind of mathematical formula so to

get a random number we need to see the

random number generator with a different

value let me show you what I mean so we

have another function called s Rand that

is short for seed Rand if you see the

random number generator with the value

of five now we get a different random

value but again every time we run this

program we get the exact same random

number if we see this with a different

number now our random number is going to

be different so how can we get truly

random numbers well we have a function

for getting the current time in terms of

the number of seconds elapsed from

January 1970 if we use that function

every time we run our program we're

going to get a different number let me

show

you so first on the top we need to

include another file called ctime in

this file we have a function called time

that Returns the current time in terms

of number of seconds elapsed from

January 1st 1970 now to call this

function we have to give it a special

argument called null pointer or null PTR

we'll talk about this later in the

course if this is too confusing for you

just use the number zero but C lion is

going to give us a warning don't worry

about that it's just suggesting to use

null pointer now this returns a long

value which is El lapsed seconds so to

see this in action instead of printing a

random number let's print the elapsed

seconds now if you're on our

program this is the number of seconds

elapsed from January 1st 1970 now every

time we run our program we get a

different value right so we can use this

to se the random number generator so

instead of hardcoding the number six we

can use elapsed seconds now we gener a

random number and print it on the

terminal take a

look so every time we at our program we

get a different random number great but

this random number is way too large what

if you want to specify an upper limit

well over here where we generate the

random

number we can use the modulus operator

and specify the upper limit so if you

type 10 that's going to return the

remainder of division by 10 so that can

only be numbers 0 to 9 right take a look

so now we have two if we run our program

again we get nine three and so on

beautiful now we have a warning here

under Rand the warning is saying the

Rand function has limited Randomness use

C++ 11 random Library instead so in C++

11 we have a different way for

generating random numbers but that's

more complicated it's not suitable for

beginners so for now this is a good way

for you to learn how to generate random

numbers now we can make this code a

little bit more concise in this case we

don't really need this variable a lapse

seconds because anyone familiar with C++

knows that time of zero or time of null

pointer Returns the current time in

terms of number of elapse seconds so we

can grab this function and pass it as an

argument to the srand function and now

we don't need the extra variable so this

function will return a value and that

value is going to be passed to this

function as an argument okay so this is

how we can Generate random numbers in

C++ now as an exercise I want you to

write a program to roll a dice so every

time we run this program we should get

two random values between 1 to six now

to limit the range of the random number

use this formula on the screen you will

see my solution next

all right let's look at my solution so

on the top we are including three files

iio stream CSD lip and C time now in the

main function we are seing the random

number generator with the current time

now to generate a random value we're

going to use the formula I showed you

earlier so we call the Rand function and

then get the remainder of division by

this expression our maximum value is six

our minimum value is one and then we

need to add one to it now someone else

looking at this code will probably have

no idea what these numbers represent

that's why I told you that you should

avoid magic numbers so this is a great

opportunity to use a constant so we

Define two constants constant integer

mean value of one and constant integer

max value of six now here we can use the

short type because we don't really need

to store or large numbers here so it's

better to use the short type to save

system resources the memory so we have

two constants now instead of hardcoding

these magic numbers we use our constants

and this makes our code more readable

and easier to understand okay so using

the modulus operator we get the

remainder of division by this expression

now we need to wrap the whole thing in

parenthesis and add the minimum value to

it this will give us a random number

between 1 to six so we can store it in a

variable called die one or first

whatever you prefer then we need to

duplicate this and create a second

variable called

second and finally we can print

everything using SE out so first here we

chain the stream insertion operator we

can add a comma and the second variable

now let's run

program so we get three and four one

more time 5 and six 6 and six

beautiful we have reached the end of

this tutorial again as I said this

tutorial is the first hour of my

complete C++ Series so if you want to

learn more use the link below this video

to enroll and please support me by

liking and sharing this video thank you

so much and have a fantastic day

[Music]

Loading...

Loading video analysis...