Top Banner
ALPHACPP.COM Starting with the tutorials – C++ tutorial January 1, 2015 Udit Pandoh This module will be beneficial for basic C++ programmers as well as for those who have no experience with C++. In this we will provide you C++ contexts, how programs are executed, how to create your program. Each module is broken into different topics and each topic containing a number of subtopics related to it. There is no fixed time that should be given to it. The concepts from each topic tend to build on from the previous topics. So clear your concepts and then proceed further. Before starting, let’s mark some important goals for C++: 1) Textbooks play a vital role in clearing the basic concepts. But the authors, sometimes, are precise about topics due to which a student might have tons of queries about these short topics and so they tend to suffer in future. So, it is very necessary to clear the doubts side by side. 2) It is not only important to read the text but understand it, using examples, which should clear the queries on the spot. 3) Do practice by making programs along with the topics you have read. Just like a person cannot learn to swim by seeing (from outside) another person swimming or by just reading about the various styles of swimming. The person must enter the pool himself and flap his/her hands to actually learn. 4) Most importantly, you will have a lot of fun during coding and it will help you to become practical in your approach towards problems. If there is any bug in the code you will think over it again and again which will help in increasing your mental ability. Sharing is caring UDIT PANDOH LEAVE A REPLY Your email address will not be published. Required fields are marked * Name * Email * Website Comment You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data- url=""> <span class="" title="" data-url="">
166
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Cpp

ALPHACPP.COM

Starting with the tutorials – C++ tutorial

January 1, 2015 Udit Pandoh

This module will be beneficial for basic C++ programmers as well as for those who have no experience with C++. In this we will provide you C++

contexts, how programs are executed, how to create your program. Each module is broken into different topics and each topic containing a number of

subtopics related to it. There is no fixed time that should be given to it. The concepts from each topic tend to build on from the previous topics. So clear

your concepts and then proceed further.

Before starting, let’s mark some important goals for C++:

1) Textbooks play a vital role in clearing the basic concepts. But the authors, sometimes, are precise about topics due to which a student might have

tons of queries about these short topics and so they tend to suffer in future. So, it is very necessary to clear the doubts side by side.

2) It is not only important to read the text but understand it, using examples, which should clear the queries on the spot.

3) Do practice by making programs along with the topics you have read. Just like a person cannot learn to swim by seeing (from outside) another

person swimming or by just reading about the various styles of swimming. The person must enter the pool himself and flap his/her hands to actually

learn.

4) Most importantly, you will have a lot of fun during coding and it will help you to become practical in your approach towards problems. If there is any

bug in the code you will think over it again and again which will help in increasing your mental ability.

Sharing is caring

UDIT PANDOH

LEAVE A REPLY

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

Name *

Email *

Website

Comment

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite><code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

Page 2: Cpp

2.1 Welcome to the world of variables – C++ tutorial Introduct ion to programming languages – C++ tutorial

Post Comment

Notify me of follow-up comments by email.

Notify me of new posts by email.

ARCHIVES

June 2015

May 2015

April 2015

March 2015

February 2015

January 2015

April 2013

META

Register

Log in

AlphaCpp.com All rights reserved. Theme by Colorlib Powered by WordPress

Search...

Page 3: Cpp

ALPHACPP.COM

Introduction to programming languages – C++ tutorial

January 2, 2015 Udit Pandoh

In this C++ tutorial we would get introduced of programming languages. Computers, nowadays, are imaginably fast and are getting even faster by the

day. Computers understand only fixed set of instructions and do that what it is told to do so. The visible part and the computer machinery on which

instructions are executed are called HARDWARE and the set of instructions is called SOFTWARE.

After this we will read different types of languages in this Cpp tutorial.

Machine Language

The set of instructions which can be understood directly by the system is called MACHINE LANGUAGE. There are two interesting things about this

language:-

This language is always in the binary form.(i.e.; in 2 digit form which are 0 & 1)

0 & 1 are generally called binary digits (short form ‘BITS’)

Binary form is translated by the CPU (Central Processing unit) which makes very much easy for the user to operate the computer.

But in the past, user had to input using the binary digit, which was very difficult for the user. Also, different set of instructions were understood by

different types of CPU’s, making it even more difficult for the user.

ASSEMBLY LANGUAGE

As we can see, machine language was very hard to work with it so we had to create another type of language, namely assembly language. In this

language, set of instructions are defined by some short names. (In place of using whole binary code) This makes the user to operate the system more

efficiently. But a problem aroused, as machines could only understand machine language. So, a device called ASSEMBLER was invented which solved the

problem and made it much easier to operate the system. But, the assembly code written for one CPU could not be run on another CPU, so we had to

move further.

HIGH LEVEL LANGUAGE

To make it easier, high level languages were developed like:- C, C++ Pascal, JAVA, JavaScript, Python and many more. Programs written in high level

languages can easily be translated into machine language for execution. High level languages are much easy to read as a well as write.

E.g.: – a=10; b=50;

In this, we can perform a task in this language in a very easy manner. E.g.: – a=b * 10 – 5;

But if we had to perform this task in assembly language it would have taken us at least 5-6 steps, and let us not talk about machine language.

After the languages we will study the different types of language converters on this Cpp tutorial.

COMPILER

It is software which reads the high level language code in one go and can translate into the language in which the CPU can understand. High level

languages are comparatively much easier than assembly language. Nowadays, compilers are very fast, especially when compared to the ones used in the

earlier days. They often do better job than a human being who enters the code.

INTERPRETER

It is software which converts high level language into machine language by executing it line by line. For error debugging interpreter plays a vital role in

helping the user to correct the debug at the same time. But, once errors are removed, unnecessary usage of memory takes place as it has to be

present in the memory always.

After the end of different types of converters our one one more C++ tutorial which covers the topic i.e.; about the programming languages.

Sharing is caring

UDIT PANDOH

Page 4: Cpp

Start ing w ith the tutorials – C++ tutorial Brief History of C/C++ – C++ tutorial

LEAVE A REPLY

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

Name *

Email *

Website

Comment

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite><code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

Post Comment

Notify me of follow-up comments by email.

Notify me of new posts by email.

ARCHIVES

June 2015

May 2015

April 2015

March 2015

February 2015

January 2015

April 2013

META

Register

Log in

Search...

Page 5: Cpp

AlphaCpp.com All rights reserved. Theme by Colorlib Powered by WordPress

Page 6: Cpp

ALPHACPP.COM

Brief History of C/C++ – C++ tutorial

January 3, 2015 Udit Pandoh

In this C++ tutorial we read the brief history of C/C++Through this C++ tutorial we would know that how C/C++ languages were developed at that

time with no concept of this computer languages.

The C language was first developed in 1972 by Dennis Ritchie. Richie’s primary goal was to produce a language that was easy to compile as well as code.

C ended up being so efficient and flexible that the UNIX operating system was rewritten using C. Earlier most of the operating systems were written in

assembly language making it difficult to use on other computers (due to lack of portability). This led to the huge popularity of UNIX as an operating

system.

Later, the C++ (pronounced C plus plus) was developed by Bjarne Stroustrup as an extension to C (++ is used to denote increment). After this, the

main priority was how to make the language even more efficient, easy to compile and easy to read and write. C language was getting obsolete because it

did not fulfill the main goals and was not so much efficient as well as flexible for the user.

In 1983, AMERICAN NATIONAL STANDARDS INSTITUTE (ANSI) formed a committee to establish a standard C. Around 1990 they introduced C89

standard programming language. After some modifications in it they launched C90 and went on to release till C99, in which they adopted features which

were already common in C++.

C++ came into use after 1998 when ISO (International organization of standardization) committee approved it. C++’s claim to fame is due to the fact

that it is an object-oriented language.

Note: You do not learn to program in C before learning C++ as commonly told. You will learn everything you need to know in these tutorials.

Through this Cpp tutorial now we are aware of history of main computer languages i.e.; C and C++.

Sharing is caring

UDIT PANDOH

LEAVE A REPLY

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

Name *

Email *

Website

Comment

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite>

Page 7: Cpp

Introduct ion to programming languages – C++ tutorial Introduct ion to basics of a program – C++ tutorial

<code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

Post Comment

Notify me of follow-up comments by email.

Notify me of new posts by email.

ARCHIVES

June 2015

May 2015

April 2015

March 2015

February 2015

January 2015

April 2013

META

Register

Log in

AlphaCpp.com All rights reserved. Theme by Colorlib Powered by WordPress

Search...

Page 8: Cpp

ALPHACPP.COM

Introduction to basics of a program – C++ tutorial

February 1, 2015 Udit Pandoh

Our First programA program is nothing but a sequence of lines of code. A program is further divided into statements. Statement is the smallest part of the program.

Statements are nothing but a way for us to instruct the compiler. Statements can further be categorized for better understanding of basics.

See this piece of code:

The first line int x represents a declaration statement. As suggested by its name, a declaration statement is used to declare a variable, like the ones you

might have studied in your algebra class. The word int is used to indicate that the variable declared is an integer, whereas x represents the name of the

variable.

The second line of the code x = 5 is used to assign numerical value to the variable x and so it is called an assignment statement. From now on, the x has

a value 5, just like the variables from algebra.

It should be noted that these variables must be declared before they can be put to use in the program.

C++ is also capable of evaluating an expression. Expression is nothing but a mathematical statement, which is to be evaluated by the program.

For example consider this,

As we can see, it is an assignment statement assigning the value of x – 3 to our variable y but the compiler evaluates this expression to 2 (the computer

always does its algebra right) first and then assigns it to y.

The third line of our code std::cout <<x; is an output statement. This instructs the compiler to output the value of the variable which is 5 on the screen.

Also, you must have noticed we have used ‘;’ after every statement. This is done to indicate to the compiler that the statement has terminated and it

can move on the next statement to be executed.

FunctionsFunctions are very essential to any coding language. A function can be defined as a set of statement used to achieve a particular task. I believe the best

way of understanding functions is through examples.

For instance, if we have to create a program which tells us which of the given two numbers is larger, this can be easily done using functions. Firstly, we

will create a function and name it, say, greaterNumber. Then we will be writing a set of codes inside greaterNumber which help us to determine the bigger

number

Every C++ program consists of a function named main(), this is the main function (pun intended) from which the compiler starts executing the

program.

We will study more about function in later tutorials.

LibraryA library is a precompiled set of codes which can be used in different programs. Library also consists of functions which, as we know, are used to achieve

a particular task.

For example, inf0 we are making a program for mixing music we will be using a sound library.

One of the most frequently used library is iostream which is used to display result on the screen or input it from the user. In fact the ‘io’ in the word

iostream stands for input and output.

You might remember we had used std::cout << earlier in the tutorial. This (std::cout<<) also belongs to the iostream library.

The core C++ language is very small but it does come with C++ standard library which helps us to have more additional functions at our disposal.

123

intint x;x = 5;std::coutcout << x;

123

intint y; y = x – 3;

Page 9: Cpp

Compiling our first program

Now that we have a basic understanding of the structure of a program let us put our knowledge into action.

See this code here:

Here #include tells the compiler that what we will be using a library, in this case it is iostream about which we have discussed earlier.

int main() is our main function from where the compiler starts the execution

of the program.

std::cout is the output object representing the console or screen. We have discussed about its use earlier.

Like there are addition (+), subtraction (-) operators in mathematics; << is what we term as the output operator.

Double quotes (“ ”) are sometimes used after the output operator. The information written inside the double quotes is displayed as it is on the screen

without any interpretation by the compiler.

You may have noticed how we have used ; to end every statement. This is done to indicate to the compiler about the start and end of each statement.

Then it comes to the return statement. It basically returns or provides a value to the operating system, generally describing whether the program ran

successfully or not.

The value 0 represents that the program ran successfully.

Adding the word int with main tells the compiler that return statement is a integer.

One more thing to note is that we start and end the main function with curly brackets ({ }). All the statements within the curly brackets indicate that

they are the part of the function.

On running the above code the output will be Hello world!. In fact, the first program we learn to write in any computer language is to display Hello World

on the screen.

Enter the above code and hit ctrl + F5 and the program should run successfully and voila!! You just ran a functional C++ program it’s the first big step in

the journey.

C++ tutorialsSharing is caring

basics c++ coding funct ion hello world introduct ion learn program statements tutorial tutorials variables visual studio

UDIT PANDOH

LEAVE A REPLY

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

Name *

Email *

Website

Comment

1234567

#include <iostream> intint main(){std::coutcout <<”Hello world! ”;returnreturn 0;}

Page 10: Cpp

Brief History of C/C++ – C++ tutorial Comments – C++ tutorial

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite><code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

Post Comment

Notify me of follow-up comments by email.

Notify me of new posts by email.

ARCHIVES

June 2015

May 2015

April 2015

March 2015

February 2015

January 2015

April 2013

META

Register

Log in

AlphaCpp.com All rights reserved. Theme by Colorlib Powered by WordPress

Search...

Page 11: Cpp

ALPHACPP.COM

Comments – C++ tutorial

February 2, 2015 Udit Pandoh

SignificanceA comment is a very important part of coding which is often given no significance by new programmers !!

Lets say you have two friends who both like to code. Both of them have written a code to help a fruit seller organize himself. One of them writes the

statement like this.

and the other one like this

Though there is a difference in both of these statements but if you run them in the compiler both will work exactly the same.

So what is the difference between the two?Well, the second statements consists of what we call a comment. A comment is something which does not affect the working of a program but helps us

and others to understand the code better.

Coming back to our original example when we see our first statement we can logically understand that there is a variable x which has a value of 10 but it

does not help us understand its role in program ?

On the other hand the second statement’s comment, i.e, at the right hand side of ‘//’ helps us know that x is used to store the information about

the no. of apples !

Inserting the ‘//’ directs the compiler that anything we write from now on is a comment hence compiler ignores it during execution of the program.

Consider for an example

In the above example since ‘int x ;’ is written after ‘//’ the compiler ignore it code and hence stores a variable named x.

1 intint x = 10 ;

1 intint x = 10 ; //number of apples.

1 //int x ;

1 std::coutcout <<"using comments"; //whatever we write now will be ignored by the compiler

Page 12: Cpp

We can also write comments between ‘/*’ and ‘*/’. This helps us write the comments in more than one line (// allows us to write in only one line).

We can even use a comment to tell how the function is supposed to work.

For instance we are writing a function to to check if a given no. is an even number or not.

One of the most important thing to learn is to use good comment that actually help the person understand the code;

for example:

Clearly, this is a bad comment as we can obviously see the marks variable is set to 0.

Here, we can know why was marks set to 0 thus this is considered a good comment.

Remember when a comment is written, it should be written such that it can easily be read by even a person who doesn’t know how to code. When you

are working with a group of friends on a project or looking at your programs you worked on earlier comments really pay off :), here is another example.

Comment out codeThere is another important use of codes. It is called commenting out, which implies that there might be times when you don’t want to use a particular

fragment of your code during execution. All you need to do is to apply ‘// ‘ at the start of every statement you want the compiler to ignore. They will

not be executed since these are now considered as comments !!

In the second case the compiler will now ignore this statement while it compiles the program.

This may seem useless at first but it really helps this can be done on a number of occasion:

1)Suppose, a part of our program is not working correctly, i.e we are getting compile errors so we can comment the

statement which is causing errors for now so that we can run the rest of the program.

2)Suppose, we have written a set of statements but now we have a got a better set of statements to use instead of what we were using earlier instead

of deleting the old ones we can comment them as a reference to the new code and until it is made sure that the new code works perfectly fine.

3)Sometimes, a code brings up the unexpected result we can comment the parts of code slowly to find the statement which is causing the program.

At a glanceTo comment on code, use // on multiple lines of code, or the /* */ style to comment on more than one line.The basic use of comments is to make the

program more understandable .

c++ tutorial

1234567

/*To check whether a number is even number or not1)First input the number from the user.2)Divide the number by two.3)If the remainder is 0 then the number is a even number.4)If the number leaves a remainder then the no is not a even number.*/

1 intint marks = 0 ; // marks set to zero

1 intint marks = 0 ; //initial marks are set to zero before we start adding numbers to them.

12345

//bad commentintint x = ((input*100)/total) ;//we multiply input by 100 and then divide by total. // good commentintint x = ((input*100)/total) ;// to obtain the percentage.

123

coutcout <<"hello world " ; // normal statement; //cout <<"hello world";

123

// std::cout << "1"; //single line comment// std::cout << "2";// std::cout << "3";

12345

/*std::cout << "1"; ; //to comment on more than one linestd::cout << "2";std::cout << "3";*/

Page 13: Cpp

Introduct ion to basics of a program – C++ tutorial Hello Variables – C++ tutorial

Sharing is caring

c++ coding comment comments compiler cpp learn program t ips tutorials visual studio

UDIT PANDOH

LEAVE A REPLY

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

Name *

Email *

Website

Comment

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite><code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

Post Comment

Notify me of follow-up comments by email.

Notify me of new posts by email.

ARCHIVES

June 2015

May 2015

April 2015

March 2015

February 2015

January 2015

Search...

Page 14: Cpp

April 2013

META

Register

Log in

AlphaCpp.com All rights reserved. Theme by Colorlib Powered by WordPress

Page 15: Cpp

ALPHACPP.COM

Hello Variables – C++ tutorial

February 3, 2015 Udit Pandoh

The term x in the above statement is what we term as a variable.

VariablesA variable in C++ is a name of the location of the memory that can be used to store and retrieve information. As we know that, all computers have a

memory known as RAM (random access memory) which is available for programs to use while working. When a variable is declared, a part of memory

gets reserved for that variable.

variables in C++ are like the variables we all have used in our algebra class but there are some basic things we need to understand first.

The objective of declaring a variable is telling the compiler to allocate some memory on RAM. Once that is achieved we give the variable a value. One

thing we must remember is this value is not permanent As the name suggests we can change its value at any time.

In this module we are going to study about the variables whose value is an integer

DeclarationNow question arises how to declare an integer variable in a C++ coding?

Here’s an example of it: –

As we type this statement a location gets reserved for this variable x in the RAM. For e.g.:- the variable x is assigned memory location let say 10. Now,

whenever we will use the variable x, CPU automatically understands that it should go to location 10 to receive the value.

Now we will understand that how the variable is assigned a value. It is very simple we will assign it with using an ASSIGNMENT OPERATOR. i.e. ‘=’

(commonly called equal to)

As we type this statement CPU automatically understands that ‘it has to put the value 20 in location 10’.

One more thing to note down is either we first declare the variable in one statement and provide its value in another or declare both of these statement

together.

and

L-value & R-valueIn C++, variables are also known as L-VALUES. An l-value is a value which has a specific address in the memory. Since, all variables have address hence,

all variables are l-value. They were originally this because they were always written on the left side of the assignment operator; For e.g.; 10=50 is an error

because 10 is not an l-value as 10 has no location reserved in the memory and that’s why a value cannot be assigned to it.

Opposite to this there is a term called as R-VALUE. It is a value which can be assigned to an l-value. For e.g.:- x, here x is evaluated as the value that

assigned to it at last.

1 intint x = 10; // what is x ?

1 intint x;

1 x = 20;

12

intint x ;x = 10 ;

1 intint x = 10 ; // both of the codes have no difference during execution

123456

intint x; //OK Mr.compiler allocates the memoryx = 5; //x now possesses the value 5x = 10+20; //x now equals 30intint y; //declare variable yy = 50; // y = 50y = x; // y = x i.e. y = 30

Page 16: Cpp

Wait what ? In last two examples one might get confused one must see that in the last two examples x is not acting as a variable but as the value it has

been given that is 30. Both these variables expression are valid as long as the variables on the right side of ‘=’ have a value.

Consider the following example

Uninitialized variableA variable that has not been assigned with any value is called an UNINITIALIZED VARIABLE. Using this type of variable is most common mistake by the

beginners for C++. The compiler will not show the value because the variable has no value stored in the memory. But the modern compilers display an

error at the time of compiling the program.

They will display : uninitialized local variable ‘x’ used

To overcome this problem you should always remember two things when it comes to variables: declaration and initialization.

c++ tutorialSharing is caring

alphacpp basics c++ coding compiler cpp introduct ion learn program statements t ips tutorials user variable variables visual studio

UDIT PANDOH

LEAVE A REPLY

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

Name *

Email *

Website

Comment

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite><code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

Post Comment

Notify me of follow-up comments by email.

Notify me of new posts by email.

7 y = x+12; //y = 42

12

intint x;coutcout <<x; //wrong x has no value to display

Page 17: Cpp

Comments – C++ tutorial Output- C++ tutorial

ARCHIVES

June 2015

May 2015

April 2015

March 2015

February 2015

January 2015

April 2013

META

Register

Log in

AlphaCpp.com All rights reserved. Theme by Colorlib Powered by WordPress

Search...

Page 18: Cpp

ALPHACPP.COM

Output- C++ tutorial

February 4, 2015 Udit Pandoh

Show me the screen

Now that we are done with basic understanding of a variable lets us move forward to the next section that is output. Writing the program is one thing

but what’s the point when nothing is displayed to the screen, no one cares what is your code unless you show it in action.

Though we can give you some technicalities like what files are used for output but for now we will skip this and concentrate on practical application. We

use key word i.e cout.

After writing ‘cout’ in a statement for every thing we need to display, we use ‘<<‘ ( output operator ) before each one so that we can output or display

more than one thing on the same line.

for eg;

Note that the second time because we were on the same line we wont be needing to write cout again for variable but only the ‘<<‘ ( output operator ).

1234567

#include <iostream>intint main(){intint x = 10 ;std::coutcout << x;returnreturn 0 ;}

1234567

intint main(){intint x =10 ;intint y = 20;std::coutcout <<x <<y ;returnreturn 0;}

Page 19: Cpp

StringSecond thing is we may need to display some text on the screen, for instance if I am writing a program to simply add two numbers but for that I would

need to ask the user for it like “Enter two numbers you want to add up “.

Displaying text is also simple we write the text we want inside ” and ” so that compiler know they are only being displayed on screen and have no

significance in the execution of the code, since it is like collection of some letters or numbers we call this expression a string.

Also one more thing, when you write something like this

You might expect that when you run the program, ‘hello’ is in one line and world in the next but its not true C++ expects you to decide when you want

to start the next line there are two ways to do this.

std::endl1)Firstly, you can use ‘endl’ whenever you want to jump to next line in output just enter <<endl and it will be done like this.

And of course since writing world in next line dose not do anything but std::endl does you can even write the code like this there will be no difference.

You may have noticed that we do not write endl between ” and ” because it is not something displayed on screen but actually a code telling the compiler

to change the line.

“/n”2)Suppose we want to insert a new line in the same string but not two different ones then ‘endl’ will not be of use

but we enter ‘/n’ between the last word of the line we are on and the first word of the new line.

This will output ‘hello’ on one line and world on the other

We recommend users to only use endl statement as it is more easy to understand that we are changing the line by looking at the code.

c++ tutorialSharing is caring

<< basics c++ change line coding display learn output t ips tutorial tutorials visual studio

UDIT PANDOH

LEAVE A REPLY

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

Name *

Email *

Website

1 std::coutcout << "this is a string we can even include numbers and other symbols 123@" ;

12

std::coutcout <<"hello";std::coutcout <<"world";

12

std::coutcout <<" hello " <<std::endl ;std:coutcout <<"world " ;

1 std::coutcout <<"hello" <<std::endl <<"world";

1 std::coutcout <<"hello /n world ";

Page 20: Cpp

Hello Variables – C++ tutorial Input – C++ tutorial

Comment

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite><code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

Post Comment

Notify me of follow-up comments by email.

Notify me of new posts by email.

ARCHIVES

June 2015

May 2015

April 2015

March 2015

February 2015

January 2015

April 2013

META

Register

Log in

AlphaCpp.com All rights reserved. Theme by Colorlib Powered by WordPress

Search...

Page 21: Cpp

ALPHACPP.COM

Input – C++ tutorial

February 5, 2015 Udit Pandoh

What is your favorite game that you have ever played ? Now imagine how would it have been if the user cannot control anything in the game, well that

will surely suck !! So now we will be learning to take an input from the user.

If you have understood output, input should not be difficult for us.

Like the output function uses cout keyword and ‘<<‘ , we will use cin keyword and ‘>>’ ( input operator ).

For example if we were making a program that makes the user enter a number and then output that number on the screen.

One important thing to learn is that since user will be entering a value that value needs to be stored somewhere in the memory and for that we will be

requiring a variable that can store the value the user enters ( input )and use it further in program

So first we will declare a variables, let it be x. But of course we wont give it any value or input as that is what user is supposed to do.

The program is pretty straight forward but still we will discuss some points. One of the things you must understand is that providing ‘cin’ does not means

the user can input anything, for eg a fraction or a string, the user can only input data of the type the variable which is holding its value is.

Since we are declaring our variable with int that is integer hence the program expects the user also to input an integer as you may have noticed we will

never put x between ” and ” as it is actually being used in the program,

and now once that x has a value we can output to the screen by using cout.

NOTE – For now, we will only cover taking input of integers we will be covering other section of the topic later.

Getting rid of std::Now that we have covered the input and output you would have noticed that we are using ‘std::’ between every cout and cin. all these are part of the

standard library in a container or namespace termed as std.

hence writing std is nothing but name of the container cout and cin live in.

We will discuss about namespace later but for now the thing we need understand is that of we are using something contained in standard library a lot in

our program we may want to avoid writing std:: again and again , to do this simply add the following code at the start of the program

1 std::coutcout <<" enter the amount of money you want to donate " ; // lol

123456789

#include <iostream>intint main (){intint x;std::coutcout <<" please enter the choice ";std::cin >> x;std::coutcout <<"you entered - " <<x ;returnreturn 0 ;}

Page 22: Cpp

After this every time we use cin and cout we dont need to write std:: again and again as the above code directs the compiler if it ever encounters a

strange name, it will check for it in the std container.

Here is the hello world program we used in the chapter 1.0

now adding the “using namespace std” the program becomes

c++ tutorialSharing is caring

>> basics c++ coding control input learn program t ips tutorial tutorials user visual studio

UDIT PANDOH

LEAVE A REPLY

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

Name *

Email *

Website

Comment

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite><code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

Post Comment

1 usingusing namespacenamespace std;

123456

#include <iostream>intint main(){std::coutcout << "Hello world! ";returnreturn 0;}

1234567

#include <iostream>usingusing namespacenamespace std;intint main(){coutcout << "Hello world! ";returnreturn 0;}

Page 23: Cpp

Output- C++ tutorial Start ing w ith operators – C++ tutorial

Notify me of follow-up comments by email.

Notify me of new posts by email.

ARCHIVES

June 2015

May 2015

April 2015

March 2015

February 2015

January 2015

April 2013

META

Register

Log in

AlphaCpp.com All rights reserved. Theme by Colorlib Powered by WordPress

Search...

Page 24: Cpp

ALPHACPP.COM

Starting with operators – C++ tutorial

February 6, 2015 Udit Pandoh

C++ is a very flexible languages and the only thing which can provide limitation to what you can do with it is your imagination.

when we are using c++ we need to do many operations with the variables, hence comes the need for operators.

Though operators is very vast topic which we will slowly cover in future sections for now we must understand their basic use.

For now you can use arithmetic operator like addition , subtraction ,multiplication and division.Also we have the the assignment operator ‘=’

(equal to) to give values to variables.

Lets say we want to make a program to add two numbers and display the result on the screen:

1)Declare two integers say x and y.

2)Obtain their value by taking input form the user

3)add the two variable using ‘+’ operator

But wait !! where will the value of the sum of these variables stored ? since we will be needing memory to do that therefore we will be

declaring a third integer to hold that value.

If (#include <iostream>) , (int main { } ) or return statement confusing you refer to the tutorial 1.0.

Similarly we can use the subtraction multiplication or division too.

Literals

A literal is a fixed value which is inserted directly by the user in the code such as 1 , 14 , 3.56

All these are fixed value and hence do not need to be allocate space in the memory like variables let us understand this by an example :

123456789101112131415161718

#include <iostream>usingusing namespaces std;intint main(){//1) We will declare three integersintint x , y , z ; //2)take input from usercin >>x >>y; //3)add x and y and store their value in zz = x + y ; //4)output the value of z to the screencoutcout <<"the sum of " <<x <<" and " <<y <<" is " <<z; returnreturn 0 ;}

123

intint x = 12 ; // x is a variable 12 is a literal.coutcout << "hello world" ; //even "hello world" is a literal.intint y = 10 + 2 ; //y is a variable 10 and 2 are literals.

Page 25: Cpp

Input – C++ tutorial Keywords & Ident ifiers – C++ tutorial

Expression

An expression is the combination of literals , expression and operators,every statement in the previous example were expressions.

Here y is a variable = is an assignment operator 15 & 10 is a literal and + is a addition operator.

C++ tutorialsSharing is caring

add basics c++ coding cpp epression equal learn literal operand operator operators output program subtract t ips tutorial

tutorials user varibale visual studio

UDIT PANDOH

LEAVE A REPLY

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

Name *

Email *

Website

Comment

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite><code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

Post Comment

Notify me of follow-up comments by email.

Notify me of new posts by email.

1 intint y = 15 + 10 ;

ARCHIVES

Search...

Page 27: Cpp

ALPHACPP.COM

Keywords & Identifiers – C++ tutorial

February 7, 2015 Udit Pandoh

Keywords are some words which have a special meaning to the compiler. they all serve unique purpose and cannot be used as a normal identifier.

there are a total of 73 keywords in c++

asm continue float new signed try

auto default for operator size of typedef

break delete frined private static union

case do goto protected struct unsigned

catch double if public switch virtual

char else inline register template void

class enum int return this volatile

const extern long short throw while

We already have used some of these keywords and as we progress further in these tutorials we will learn about almost all of them.

Identifiers

Identifiers are the building blocks of a program they are defined as the name given to variables , function , classes structures , etc.

There are few rules one should keep in mind while writing identifiers.

1)The name of a identifier cannot start with a number.

2)C++ differentiates between lower case and upper case letters.

3)The identifier can be named using letters, numbers, and the underscore character but not whitespace or any symbol.

4)The identifier can not be a keyword as keywords already have a defined purpose in the language.consider the following example.

If we were to write a program to take the input of a students roll number, class and percentage we will write a, now the task was given to a lazy person

who did not wrote it correctly and now the compiler is showing errors lets see the program first

12

intint 1subject ; // illegal identifier cannot start with a number. intint subject1 ; //legal as the identifier is not starting with a number.

1 intint Name,name ; // considered as two different identifiers

123456

intint name ; //legal it contains only letters. intint name1 ; //legal it contains letters and a number. intint name_1 ; //legal it also contains an underscore. intint nAmE_1 2 ; //illegal it contains a whitespace after 1. intint $name ; //illegal a symbol is used. intint name_% ; //illegal a symbol is used.

12345678

#include <iostream>usingusing namespacenamespace std;voidvoid main(){intint classclass, roll number, percentage% ;cin >>classclass >>roll number >> percentage% ;coutcout <<classclass <<roll number <<percentage% ;}

Page 28: Cpp

Well all the three identifiers were wrong in the first one class is a keyword hence it cannot be name of an identifier ,

in the second case whitespace has been used instead of an underscore character and in third case a symbol has been used.

Note – If we are writing a identifier which includes two name like roll number there are two ways to write them first is that we separate them using an

underscore as discussed earlier and the other one is using capital letter to indicate the start of a new word.

Sharing is caring

UDIT PANDOH

2 thoughts on “Keywords & Identifiers – C++ tutorial”

LEAVE A REPLY

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

Name *

Email *

Website

Comment

12

intint roll_number ; //we used underscore two differentiate between the two.intint rollNumber ; // since number is a different word we started it with an uppercase letter.

REPLY

MOONMarch 20, 2015 at 5:49 am

I loved the tutorials very good job

REPLY

UDIT PANDOHMarch 20, 2015 at 6:35 am

Thanks mate

Page 29: Cpp

Start ing w ith operators – C++ tutorial Writ ing a neat code – C++ tutorial

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite><code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

Post Comment

Notify me of follow-up comments by email.

Notify me of new posts by email.

ARCHIVES

June 2015

May 2015

April 2015

March 2015

February 2015

January 2015

April 2013

META

Register

Log in

AlphaCpp.com All rights reserved. Theme by Colorlib Powered by WordPress

Search...

Page 30: Cpp

ALPHACPP.COM

Writing a neat code – C++ tutorial

February 8, 2015 Udit Pandoh

OK now we know the basics of writing a code in c++ but what is the way to write neat codes ? Well there comes basically four things one should keep in

mind.

1) Always use comments so that you and others can understand the program without searching through the codes

Note – we are not using comments in our programs because we are generally explaining every statement afterwards .

2)Use spacing and make the code neat which we discuss further in the post.

3)Learning to name variables correctly

4)Using endline and adding text to make the program more presentable.

We already discussed using comments in chapter 1.2 second comes the spacing one thing we should clearly understand is that simply hitting the space

key dose not necessarily mean that we will be leaving space consider the following example.

all the above statements are basically same that is the compiler at the time of compiling ignores the spacing unless and until it was between quotes for

eg.

this should have made your concepts pretty clear by now, but the question is how can we use this ignorance of spaces by the compiler to our

advantage ? Lets try to make the code more neat using this

12345678

intint x ; intint x; intint x ; intintx ;

123

coutcout <<"hello" <<"world" ; // prints 'helloworld'coutcout <<"hello world" ; // prints 'hello world'coutcout <<"hello world" ; // prints 'hello world'

12

intint main() {intint x,y,z;

Page 31: Cpp

Though the above given examples are identical to the compiler but we can clearly see the second example is written in a much more neat also making it

much more easier to read and understand.

Naming the variables

Another important topic is learning to name the variables like we read about a good comment we will now try to learn naming variables in the right way.

lets take for an example that we are making a game in which we are giving our player fighting strength of 80 out of 100. Well lets say i asked two people

to store this information in a statement one person wrote this.

Though both were logically correct but the second person chose to name the variable as strength instead of writing x which made his code more

understandable.

Though this may not seem much of a difference right now but as our programs become more and more complex. naming the variables x,y,a or b

makes it very difficult to understand what is its use in the program.

So its better to develop a habit of naming the variables which helps us understand their use in the program easily.

From whatever we learned in this tutorial let us write a program first without using any tips given in this tutorial and the other applying them all.

Problem – Write a code to input marks of three subjects and give their average.

And lets rewrite the code now in a better way.

Well there is a clear difference between the two programs though they both help us get the average marks.

C++ tutorialsSharing is caring

UDIT PANDOH

34

coutcout<<x<<y ;cin>>x>>y; }

123456

intint main(){intint x,y,z ;coutcout <<x <<y ;cin >>x >>y ;}

1234

intint x = 80 ; //and the other one wrote.intint strength = 80 ;

12345678910

#include <iostream>usingusing namespacenamespace std;voidvoid main(){intint a,b,c,d;coutcout<<" Enter marks for maths physics and chemistry resp. " ;cin>>a>>b>>c ;avg=(a+b+c)/3;coutcout<<avg;}

123456789101112

#include <iostream>usingusing namespacenamespace std;voidvoid main(){intint avg,sub_1,sub_2,sub_3 ;coutcout <<" Enter marks for each subject " ;coutcout <<endl ;cin >>sub_1 >>sub_2 >>sub_3 ;avg =(sub_1 + sub_2 + sub_3 ) / 3 ; // divide by three for averagecoutcout <<endl <<endl <<" Average = " ;coutcout <<avg ;}

Page 32: Cpp

Keywords & Ident ifiers – C++ tutorial 0.2 Introduct ion to programming languages – C++ tutorial

LEAVE A REPLY

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

Name *

Email *

Website

Comment

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite><code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

Post Comment

Notify me of follow-up comments by email.

Notify me of new posts by email.

ARCHIVES

June 2015

May 2015

April 2015

March 2015

February 2015

January 2015

April 2013

META

Register

Log in

Search...

Page 33: Cpp

AlphaCpp.com All rights reserved. Theme by Colorlib Powered by WordPress

Page 34: Cpp

ALPHACPP.COM

Recap – Variables – C++ tutorial

March 1, 2015 Udit Pandoh

As we studied in the earlier tutorial ,a variable is used by us to access memory and store some information in it , I don’t want to trouble you with much

detail right now ,so all we need to understand is that memory is just combination of 0 and 1 which simply indicates on or off. we use variables to direct

how and where to use this memory

In maths we have learned different type of numbers such as integers , natural numbers, rational numbers . similarly we have different types of such

data types . Till now we have been using variable of type integer ,in this chapter we will study various data types and which one to use at what time. But

first we will study some more basics which we cover in this chapter.

Why do we need variables ?Let us understand this with a series of application .

1) We need to store the strength number of warrior in the game.

Lets say that the strength points are 10 but how do i store this information in my program ? We need it to store this data in memory and the only way

to do that is use variable ,hence we will declare a variable and store this information.

2) Display a number on the screen which user enters.

To enable the user to input a number we will use cin but the next question where do i store this information ? Yes you are right we will declare a variable

and store the input number in hat variable.

3)We are multiplying two numbers and get the answer.

Here when we add two multiply lets say 1 & 2 .Yes first we will store these two values in variables, but then after we multiply them we need a third

variable to store their product too.

This should be enough to give you the basic idea. We will cover the rest of it in the next lesson.

C++ tutorialsSharing is caring

alphacpp basics c++ c++ problem coding cpp introduct ion learn program recap t ips variable variables visual studio

UDIT PANDOH

LEAVE A REPLY

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

Name *

1 intint strength = 10 ;

123

intint x ;cin >> x ;coutcout << x ;

1234

intint x , y , z ; x = 1 ; y = 2 ; z = x * y ;

Page 35: Cpp

Mult iplicat ion table Countdown

Email *

Website

Comment

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite><code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

Post Comment

Notify me of follow-up comments by email.

Notify me of new posts by email.

ARCHIVES

June 2015

May 2015

April 2015

March 2015

February 2015

January 2015

April 2013

META

Register

Log in

AlphaCpp.com All rights reserved. Theme by Colorlib Powered by WordPress

Search...

Page 36: Cpp

ALPHACPP.COM

Definition and Initialization – C++ tutorial

March 2, 2015 Udit Pandoh

DefiningWe already covered this topic in Chapter 1 ,the basic way of definition is very simple, first we write the name of the data type followed by the name we

want to give it.

We learned what are data types in the previous lesson and cover types of them in the following lessons if you are getting confused how are we going to

know which data type to use at what time do not worry you will be knowing it by the end of this chapter.

Second comes the name of the variable as discussed earlier it is your choice how would you like to name , whether names like x , y , z or a full name

such as apples. We recommend that you try to use names as they make it clear what is the variable being used for .

Here int directs the compiler that the variable is an integer whereas population is a a name we gave to the variable and since I used a name it easily tells

that variable is declared to tell the population of some place.

InitializationInitialization means to store some value in the variable you can think of it like this when we define a variable we rent an apartment though we have

rented it , it is still empty when we initialize it we fill it with stuff.

Therefore you need to define a variable before initializing it can be compared to face that you cannot fit stuff if you have not rented the apartment.

Second there s no use of a variable if you are not providing it with a value at a point of time, can be compared to the fact that renting an apartment is

of no use if do not put something in it and keep it empty.

To note – It is not important that you initialize a variable when it is being defined.

There is no difference between the above codes at all , many times in future you will be needing to define the variable at one time and initialize it later.

There are two ways to initialize a variable. remember there is no logical difference between the two methods you can use any of it

1) Explicit Initialization

In this method we use the ‘ = ‘ that is the assignment operator followed by the value.

2)Implicit Initialization

In this method we simple write the value we want to assign between two round brackets ‘( )’ .

C++ tutorialsSharing is caring

12

//the general from isDatatype name ;

12

//For exampleintint population ;

1 intint x = 5 ;

12

intint x ;x = 5 ;

1 intint apples = 5 ;

1 intint apples(5) ;

Page 37: Cpp

Store owners problem Funct ion Parameters – C++ tutorial

alphacpp basics c++ coding compiler cpp definat ion define int ializat ion int ialize introduct ion learn program tutorials visual studio

UDIT PANDOH

LEAVE A REPLY

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

Name *

Email *

Website

Comment

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite><code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

Post Comment

Notify me of follow-up comments by email.

Notify me of new posts by email.

ARCHIVES

June 2015

May 2015

April 2015

March 2015

February 2015

January 2015

April 2013

Search...

Page 38: Cpp

META

Register

Log in

AlphaCpp.com All rights reserved. Theme by Colorlib Powered by WordPress

Page 39: Cpp

ALPHACPP.COM

Using Variables – C++ tutorial

March 3, 2015 Udit Pandoh

There are two pieces left two complete the puzzle , that is understanding where and how to use variables actually in a program.

First of all by now you must have notice that we can declare more than variable at once only.

but here comes a scope for a lot of mistakes so let us discuss them one by one.

1) More than one variable can be initialized in one statement but the all must be of the same data type ;

consider this

after understanding first rule it is pretty obvious you only need to write int once in the statement no matter how many variables are there i.e it is

understood in the above statement that y is also an integer.

2)What we studied is valid in terms of definition but not initialization i.e

Second thing we need to understand is when do we initialize the variables ? What i recommend is to declare the variable as much close to the

statement when we are actually using it.

for example if we are taking input of a number , adding 5 to it and then giving an output it will be something like this

but a more better way is :

Here we did not initialize all the variables at once but at the time when we needed them.This helps us understand the code in a better way as we can

know in the above what was their use by looking at statements around them , if they would have been initialized all at once it wold have been difficult to

know their actual use in the program.

C++ tutorialsSharing is caring

UDIT PANDOH

1 intint x , y , z ,a ,b ,c ;

123

intint x , y ; // correct they all are of the same data i.e integer ; intint x , charchar y ; // wrong x is of type integer whereas y is a char (character) ;

1 intint x ,y;

12345

intint a , x , y = 5 ; // only sets y to 5 not other variables,x and a are just defined intint a = 5 , x = 5 , y = 5 // now x , y and a are all equal to 5

1234

intint x , y ;cin >> x ;y = x + 5 ;coutcout << y ;

12345

intint x ;cin >> x ;intint y ;y = x + 5 ;coutcout <<y ;

Page 40: Cpp

Funct ion Parameters – C++ tutorial Size of variables – C++ tutorial

LEAVE A REPLY

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

Name *

Email *

Website

Comment

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite><code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

Post Comment

Notify me of follow-up comments by email.

Notify me of new posts by email.

ARCHIVES

June 2015

May 2015

April 2015

March 2015

February 2015

January 2015

April 2013

META

Register

Log in

Search...

Page 41: Cpp

AlphaCpp.com All rights reserved. Theme by Colorlib Powered by WordPress

Page 42: Cpp

ALPHACPP.COM

Size of variables – C++ tutorial

March 4, 2015 Aaryan Kapoor

We learned earlier that memory is divided into byte-sized units, with each unit having a unique address. We think of memory as a place where we can

put and retrieve information, and use variables as the name of an address to do the same.

However, most variables actually take up more than 1 byte of memory (i.e. more than one address). The amount of memory that a variable takes is

based on its data type as well as on the hardware/compiler you are working on. This is why we use declare the variables of various data types, so that

the computer itself knows how much memory is required and how it is supposed to use it.

There are several reasons it is useful to know how much memory a variable takes up.

1. The more memory a variable takes up automatically means it can store more values

This is because each bit stores either 0 or 1 (i.e. 2 values).

So, 2 bits of memory can store:

Memory address 1231 1232

Value 1 0 0

Value 2 0 1

Value 3 1 0

Value 4 1 1

4 values.

To generalize, a variable with n bits can hold 2 (2 to the power of n) possible values. Since a byte is 8 bits, a byte can store 2 (256) possible values.

So you might use bigger variables for storing bigger values (say, speed of light, accurately).

2. Every time we declare a variable, a small part of memory is used as long as the variable is in existence. As, modern computers have a lot of

memory, this often isn’t a problem, especially if only declaring a few variables. However, for programs that need a large amount of variables, say

10,000 (yes the programs can require so many variables), the difference between using 2 byte and 8 byte variables can be significant.

The size of C++ basic data typesYou might want to ask “Then how much memory does each variable of different data types take?”. It is not actually possible to predict how much

memory each variable will take as we have already told you that it also depends upon the hardware/compiler the person is using.

Still, C++ guarantees a minimum size for all the variables. Minimum size of some of the basic data types is given below:

Category Type Minimum Size

boolean bool 1 byte

character char 1 byte

integer short 2 bytes

int 2 bytes

long 4 bytes

long long 8 bytes

floating point float 4 bytes

double 8 bytes

long double 8 bytes

The actual size of the variables may be differing.

sizeof operatorIn this section of Cpp tutorial we will determine the size of data types on a particular machine, we use an operator named sizeof. The sizeof operator is a

unary (one that requires only single variable) compile-time operator that takes either a type or a variable, and returns its size in bytes.

It can be used in two forms:

sizeof var (where var is a variable)

n 8

Page 43: Cpp

sizeof (type) (where type is a C++ data type)

You can compile and run the following program to find out how large some of the data types are:

Your results may vary if you use different type of machines, or different compilers.

Note that you cannot take the sizeof the void type, since it has no size (doing so will cause a compile error).

As told already, you can also use the sizeof operator on a variable name. Look at the following snippet:

Sharing is caring

AARYAN KAPOOR

LEAVE A REPLY

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

Name *

Email *

Website

Comment

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite><code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

Post Comment

1234567891011121314151617

#include <iostream> intint main(){ usingusing namespacenamespace std; coutcout<<“Size of boolbool: ”<<sizeofsizeof(boolbool)<<“ bytes”<<endl; coutcout<<“Size of charchar: ”<<sizeofsizeof(charchar)<<“ bytes”<<endl; coutcout<<“Size of shortshort: ”<<sizeofsizeof(shortshort)<<“ bytes”<<endl; coutcout<<“Size of intint: ”<<sizeofsizeof(intint)<<“ bytes”<<endl; coutcout<<“Size of longlong: ”<<sizeofsizeof(longlong)<<“ bytes”<<endl; coutcout<<“Size of floatfloat: ”<<sizeofsizeof(floatfloat)<<“ bytes”<<endl; coutcout<<“Size of longlong longlong: ”<<sizeofsizeof(longlong longlong)<<“ bytes”<<endl; coutcout<<“Size of doubledouble: ”<<sizeofsizeof(doubledouble)<<“ bytes”<<endl; coutcout<<“Size of longlong doubledouble: ”<<sizeofsizeof(longlong doubledouble)<<“ bytes”<<endl; returnreturn 0;}

1234

intint num;floatfloat fl;coutcout<<“Size of intint: ”<<sizeofsizeof num;coutcout<<“Size of floatfloat: ”<<sizeofsizeof fl;

Page 44: Cpp

Using Variables – C++ tutorial Integers Basics – C++ tutorial

Notify me of follow-up comments by email.

Notify me of new posts by email.

ARCHIVES

June 2015

May 2015

April 2015

March 2015

February 2015

January 2015

April 2013

META

Register

Log in

AlphaCpp.com All rights reserved. Theme by Colorlib Powered by WordPress

Search...

Page 45: Cpp

ALPHACPP.COM

Integers Basics – C++ tutorial

March 5, 2015 Aaryan Kapoor

IntegersAn integer type variable is a variable that can only hold integers (without decimal part).

E.g. -2, -1, 0, 1, 2

Char is a special case, in that it falls into both the character and integer categories. We’ll talk about its properties as character later. In this module, we can

treat it as a normal integer.

The key difference between the various integer types is that they have different sizes. We must note that C++ only guarantees minimum size for

variables and not a fixed size.

We will talk about size of variables in later modules.

Defining integersThe various types of integers are declared the following way.

1. Char

2. Short

OR

3. Int

4. Long

OR

NOTE: C++ 11 has added a new type of int, namely long long int which stores even greater values than long int. It is declared as:

OR

As you might have noticed, short int, long int and long long int are same as short, long and long long, respectively. So, it is generally preferred to use the

shorthand versions over the full ones.

Signed and Unsigned integersNow under this Cpp tutorial section we will learn signed and unsigned intgers. A variable with n bits can store 2 different values. But what are those

values? The values of an integer variable is determined by two factors: its size (in bits), and whether it is ‘signed’ or ‘unsigned’. These values are called the

range of the variables.

1 charchar ch;

1 shortshort intint num;

1 shortshort num; //both are equivalent

1 intint i;

1 longlong intint lnum;

1 longlong lnum; //both are equivalent

1 longlong longlong intint llnum;

1 longlong longlong llnum; //both are equivalent

n

Page 46: Cpp

A signed integer is a variable that can hold both negative and positive numbers.

We can declare a variable as signed by using the keyword signed.

E.g.

The keyword signed need not be written before the variable type as it signed by default.

A 1-byte signed integer has a range of -128 to 127 (both included).

Similarly, a 2-byte signed integer has a range of -32768 to 32767 (both included).

You might have already noticed that the range of n-bit signed integer is from -2 to 2 -1.

Sometimes, we do not need negative numbers like storing the distance between two places, or the time taken for some task. This can be achieved by

using unsigned integers.

An unsigned integer is variable that can only hold positive values.

We can declare a variable as unsigned by using the keyword unsigned.

E.g.

A 1-byte unsigned integer has a range of 0 to 255 (both included).

Similarly, a 2-byte signed integer has a range of 0 to 65535 (both included).

You might have notice that the range of n-bit signed integer is from 0 to 2 -1.

So, declaring a variable as unsigned means that it cannot store negative numbers, but at the same time it can store positive numbers that are twice as

large.

Size/Type Type Range

1 byte signed Signed -128 to 127

1 byte unsigned Unsigned 0 to 255

2 byte signed Signed -32,768 to 32,767

2 byte unsigned Unsigned 0 to 65,535

4 byte signed Signed -2,147,483,648 to 2,147,483,647

4 byte unsigned Unsigned 0 to 4,294,967,295

8 byte signed Signed -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

8 byte unsigned Unsigned 0 to 18,446,744,073,709,551,615

The easiest way to remember the difference between signed and unsigned integers is that negative numbers have a ‘sign’ and so are signed whereas

positive numbers do not and so are unsigned.

Default signs and integer best practicesAll integer variables except char are signed by default. Char can be either signed or unsigned by default (but is usually signed).

Generally, the signed keyword is not used, except on char (when it necessary for the char to be signed).

NOTE: It is best to avoid use of unsigned integers unless completely necessary.

C++ tutorials

12345

signedsigned charchar ch;signedsigned shortshort sh;signedsigned intint num;signedsigned longlong lnum;signedsigned longlong longlong llnum;

n-1 n-1

12345

unsignedunsigned charchar ch;unsignedunsigned shortshort sh;unsignedunsigned intint num;unsignedunsigned longlong lnum;unsignedunsigned longlong longlong llnum;

n

Page 47: Cpp

Size of variables – C++ tutorial Integers-Overflow – C++ tutorial

Sharing is caring

AARYAN KAPOOR

LEAVE A REPLY

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

Name *

Email *

Website

Comment

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite><code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

Post Comment

Notify me of follow-up comments by email.

Notify me of new posts by email.

ARCHIVES

June 2015

May 2015

April 2015

March 2015

February 2015

January 2015

April 2013

Search...

Page 48: Cpp

META

Register

Log in

AlphaCpp.com All rights reserved. Theme by Colorlib Powered by WordPress

Page 49: Cpp

ALPHACPP.COM

Integers-Overflow – C++ tutorial

March 6, 2015 Aaryan Kapoor

Avoiding integers overflowIf we try to put a number outside of the data type’s range into our variable it leads to overflow. Overflow occurs when data is lost because a variable has

not been allocated enough memory to store them.

As you know, larger numbers require more bits to represent. Since variables have fixed number of bits available, so this leads to a limit on the values the

variable can store.

Overflow examplesConsider an unsigned integer of 8-bits. It can easily store values from 0 to 255. But what happens when we try to enter a bigger number say 300. This

is a perfect example of overflow.

300 = 1 0010 1100

Here, the memory for the variable is only 8-bits, but the 300 requires atleast 9-bits. So, the computer retains the 8 least significant bits (i.e. 8 bits from

the right end). So, only 0010 1100 is left behind which is equal to 44.

Thus, overflow leads to loss of information.

We will discuss the conversion of binary to decimal and vice versa in later Cpp tutorials.

Now, let’s take a look at an example using actual code, assuming a new data type for integers (newint) which is 8 bits:

The program will print the following output:

x was: 255

x is now: 0

The value of the variable was overflowed. The result is that the value of the variable after reaching the end of the range, starting from the beginning

again.

What is actually happening is that the number 127 is represented as 1111 1111 in binary. Clearly, you can see that 255 is the largest number that we

can store in 8 bits. When we add 1 to the value, the new value should be 256. However, 256 is represented in binary as 1 0000 0000, which, as you can

see requires 9 bits. The least significant 8 bits are left behind while the most significant bit is ignored. What is left behind is 0000 0000 which is equal to the

number 0, which is our result.

If you don’t understand this, it is all right as binary system is discussed in later modules.

Similarly, we can overflow the bottom end of our range as well which, as you might by now expect, leads to the top of the range.

1234567891011

#include <iostream> intint main(){ usingusing namespacenamespace std; unsignedunsigned newint x = 255; coutcout << "x was: " << x << endl; //initial value of x x = x + 1; // 128 is out of range coutcout << "x is now: " << x << endl; //final value of x returnreturn 0;}

1234567891011

#include <iostream> intint main(){ usingusing namespacenamespace std; unsignedunsigned newint x = 0; coutcout << "x was: " << x << endl; //initial value of x x = x - 1; // -1 is out of range coutcout << "x is now: " << x << endl; //final value of x returnreturn 0;}

Page 50: Cpp

Integers Basics – C++ tutorial 2.7 — Boolean Values – C++ tutorial

The program will print the following output:

x was: 0

x is now: 255

Thus, overflow leads to loss of information. To avoid this, always use a big enough variable.

It is important to note that this results of overflow should be applied to unsigned only. Overflowing for signed integers or non-integers may lead to

different results on different systems. So, it is not advisable to depend on the result of the overflow.

C++ tutorialsSharing is caring

AARYAN KAPOOR

LEAVE A REPLY

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

Name *

Email *

Website

Comment

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite><code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

Post Comment

Notify me of follow-up comments by email.

Notify me of new posts by email.

ARCHIVES

June 2015

May 2015

Search...

Page 52: Cpp

ALPHACPP.COM

Float and Double

May 23, 2015 Aaryan Kapoor

Integers are great when it comes to writing, wait for it, INTEGERS. But what happens when you want to write numbers with a decimal part. This is very

floating point numbers come to your rescue.

Basically, there are three types of floating point numbers (with their declaration and initialization)

1. float

2. double

3. long double

The size of these numbers is not fixed but a minimum size is guaranteed by the C++, these are:

float 4 bytes

double 8 bytes

long double 8 bytes

So, you must use the best suited, neither too big nor too small, variable type for your needs.

Storing in Scientific NotationBut first of all, what is scientific notation?

Scientific notation (a.k.a Exponential notation) is a way of representing too huge or too small numbers in easy to understand.

Eg: Mass of sun is (approx) 1,989,000,000,000,000,000,000,000,000,000 kg.

whereas rest mass of an electron is (approx) is 0.00000000000000000000000000000091 kg.

As you can clearly, this numbers are very difficult to write, let alone use in calculations. This is where scientific notation comes to the rescue.

Scientific notation is generally of the form of:

n.m x 10 OR n.mEp OR n.mep

Here, n is a number from one to nine, m is all (or major) digits following the first digit, while p is the exponential power of 10.

Now, the mass of sun can be written as 1.989E30 kg

while that of electron can be written as 9.1 × 10 kg

Now, back to the topic. It can be very difficult to write the floating numbers as we clearly saw. So, we can use scientific notation to represent them.

We use n.mep OR n.mEp form in case of floating point numbers.

Eg: double sun= 1.989E30;

double electron= 9.1e-31;

If you want your output in scientific notation, you can use the scientific command (from iomanip header file), which is as follows:

Eg:

1 floatfloat f=1.1;

1 doubledouble db=1.21;

1 longlong doubledouble ldb=1.321;

p

-31

1234567

#include<iomanip>...usingusing namespacenamespace std;floatfloat fl=121.121;coutcout<<"Without scientific: "<<fl<<endl;

Page 53: Cpp

Output:

Without scientific: 121.121

With scientific: 1.12121e2

You can clearly see how scientific command works.

PrecisionWhile dealing with the floating type numbers, precision is the key. By default, the precision is set to six i.e. by default only six digits are printed and the

rest are simply left out.

This is where setprecision() comes to help. As the name suggests, it allows the programmer to fix the precision of the numbers used in the program, it is

stored in the iomanip header file.

Eg:

Output:

9.87654e7

Notice, it automatically converts the number into scientific notation, in order to convert it into the precision limit.

Output:

9876532.1

Now you can see how the setprecision() command works.

Rounding errorsAs you might remember, values are stored as binary in the memory. This method works quite well for the integer part, but when it comes to decimal part

it is not quite the best method out there. It often leads to rounding errors, especially when low memory variables (float) are selected. These errors often

go unobserved, due to the fact that most of the time the errors are beyond the precision limit. But if we try to get more precise answers, there is when

we see the real issue.

Eg:

Output:

float = 1.3333333730697631835

double = 1.3333333333333332593

Note that we declared f1 and f2 and initialized them as 4 and 3, respectively and then divided them instead of directly dividing 4 and 3. This is because if

we simply divide 4 and 3, the compiler assumes them as integers and leads to integral division, simply resulting in 1. While storing them in f1 and f2

makes the compiler consider them as float and does the complete division. Same goes in case of double.

You can avoid this by using implicit conversions.

To avoid rounding errors (especially if correctness is the key), one must go for double over float, due to the higher precision offered.

Sharing is caring

89

coutcout<<scientific; // adding scientific commandcoutcout<<"With scientific: "<<fl;

123

//without setprecision()floatfloat fl=98765432.1;coutcout <<fl;

12345678

//with setprecision()#include<iomanip>...coutcout<<setprecision(10); //sets precision to 10.floatfloat fl=9876532.1;coutcout<<fl;

12345

coutcout<<setprecision(20);floatfloat f1=4, f2=3, f3=f1/f2;doubledouble d1=4, d2=3, d3=d1/d2;coutcout<<"float = "<<f3<<endl;coutcout<<"double = "<<d3<<endl;

Page 54: Cpp

sw itch statement Arrays and loops

AARYAN KAPOOR

LEAVE A REPLY

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

Name *

Email *

Website

Comment

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite><code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

Post Comment

Notify me of follow-up comments by email.

Notify me of new posts by email.

ARCHIVES

June 2015

May 2015

April 2015

March 2015

February 2015

January 2015

April 2013

META

Search...

Page 56: Cpp

ALPHACPP.COM

2.7 — Boolean Values – C++ tutorial

March 7, 2015 Aaryan Kapoor

Another interesting topic in c++ is Boolean variables they are very similar to normal variables but the difference is they can hold only two possible values:

true (1) and false (0).

We declare the Boolean variables using the keyword bool.

When assigning values to boolean variables, we use the keywords true and false.

The logical NOT operator (!) can be used to the convert the value from true to false and vice versa.

When we print the values with cout, it prints 0 for false, and 1 for true:

Output is as follows:

1

0

0

1

If you want cout to print “true” or “false” instead of 0 or 1, you need to use std::boolalpha in the iomanip header:

Output will be:

1

0

true

1 boolbool abc;

12

boolbool tr = truetrue;boolbool fa(falsefalse);

12

boolbool tr=truetrue; //evaluates tr as trueboolbool fa=!tr; //evaluates fa as opposite of tr i.e. false

12345678910111213

#include <iostream> intint main(){ usingusing namespacenamespace std; boolbool tr(truetrue); coutcout << tr << endl; coutcout << !tr << endl; boolbool fa=!tr; coutcout << fa << endl; coutcout << !fa << endl; returnreturn 0;}

123456789101112131415

#include <iostream>#include <iomanip> intint main() { usingusing namespacenamespace std; boolbool b=truetrue; coutcout << b << endl; coutcout << !b << endl; coutcout << boolalpha; // print all bools from now on as true or false coutcout << b << endl; coutcout << !b << endl; returnreturn 0;}

Page 57: Cpp

false

Boolean in if-statementIf statements are of the form:

OR

In both forms, the condition is checked. If condition is true, then if-statement is executed.

In the second form, if condition evaluates to false, then else-statement is executed.

NOTE: Zero is considered to be false and all other non-zeros are considered true.

The output will be:

b is false

Boolean values are also useful as the return values for functions that check whether something is true or not.

In the following example, we check whether the number is zero or nonzero using functions.

Sharing is caring

AARYAN KAPOOR

LEAVE A REPLY

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

Name *

Email *

1 ifif (condition) ifif-statement;

123

ifif (condition) ifif-statement; elseelse elseelse-statement;

12345

boolbool b(falsefalse);ifif (b) coutcout << "b is true" << endl;elseelse coutcout << "b is false" << endl;

12345678910111213141516171819202122

#include<iostream> boolbool isfunc(intint x) { returnreturn x; /*Since function is of bool type so it will return 1 when true and 0 when false*/} intint main(){ usingusing namespacenamespace std; intint num; coutcout<< “Enter a number: ”; cin>>num; boolbool chck=isfunc(num); ifif(chck) coutcout<<“The number ”<<num<<“ isis nonzero”; elseelse coutcout<<“The number ”<<num<<“ isis zero”; returnreturn 0;}

Page 58: Cpp

Integers-Overflow – C++ tutorial Char – C++ tutorial

Website

Comment

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite><code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

Post Comment

Notify me of follow-up comments by email.

Notify me of new posts by email.

ARCHIVES

June 2015

May 2015

April 2015

March 2015

February 2015

January 2015

April 2013

META

Register

Log in

AlphaCpp.com All rights reserved. Theme by Colorlib Powered by WordPress

Search...

Page 59: Cpp

ALPHACPP.COM

Char – C++ tutorial

March 8, 2015 Aaryan Kapoor

In this Cpp tutorial we are going to study the keyword Char, as already discussed, is an integer, but we often use it in different ways. Char stores value as

an integer but it is used store any member of the C++ basic character set. The value of a char variable is typically interpreted as an ASCII character.

ASCII stands for American Standard Code for Information Interchange, and it defines a set of English alphabet and some symbols as numbers to be

saved in the memory. For instance, the character ‘A’ is code 65 while that of ‘a’ is 97. The ASCII defines a total of 256 codes (1-byte can store only 256

different values), which includes non graphic characters, letters, digits, symbols etc.

Also, you might have noticed that we write the character in single quotes. So, 1 is different from ‘1’ as 1 is an integer while ‘1’ is a character (They are

even stored differently in the memory).

This can be clearly seen when we initialize two char variables.

Printing charWhen using cout to print a char, cout outputs the char variable as an ASCII characters instead of a number.

This output will be:

A

rather than the expected 65.

We can also output char literals directly:

This output will be:

A

Inputting charYou can input the char simply by using cin:

The following program asks the user to input a character and then display the character as well as its ASCII code:

123

charchar num(1) //stores the value in num as 1 charchar ch(‘1’) //stores the value as ASCII code for 1 (49)

12345678910

#include <iostream> intint main(){ usingusing namespacenamespace std; charchar ch(65); //initializing ch with an integer coutcout<<ch; //cout prints a character returnreturn 0; }

1 coutcout<<‘A’

1 cin>>ch;

123456789101112

#include <iostream> intint main(){ usingusing namespacenamespace std; charchar ch; coutcout<<“Input a character: ”; cin>>ch; intint num=ch; coutcout<<ch<<“ has ASCII code ”<<num<< endl; returnreturn 0;}

Page 60: Cpp

ch will only hold 1 character, so even if you enter multiple characters it will just take the first one. This is because char occupies 1 byte. The rest of the

user input is left in the input buffer, a place where input is stored for any other future calls to cin.

This can be clearly seen here.

The output will be:

Input a character: ABC

A has ASCII code 65

B has ASCII code 66

This is not a good method for conversion of one data type to another. Rather, we should use type casting about which you will learn in later modules.

Size of char, its range, and default signChar is defined by C++ to always be one byte in size. By default, a char may be signed or unsigned (though it’s usually signed). If you’re using char to

hold ASCII characters, you don’t need to specify a sign.

If you’re using a char to hold small integers, you should always specify whether it is signed or unsigned as signed char can hold a number between -128

and 127 while unsigned char can hold a number between 0 and 255.

Escape sequencesAs discussed earlier c++ has some characters that have special meaning. These characters are called escape sequences. An escape sequence starts with

a ‘\’ (backslash), and then a following letter or number. They must be used inside quotes.

The most common escape sequence is ‘\n’, which adds a new line, just like endl.

Another commonly used escape sequence is ‘\t’, which simply does the job of tab key.

Here’s a table of all of the escape sequences:

Name Symbol Meaning

Alert \a Makes an alert, such as a beep

Backspace \b Moves the cursor back one space

Formfeed \f Moves the cursor to next logical page

Newline \n Moves cursor to next line

Carriage return \r Moves cursor to beginning of line

Horizontal tab \t Prints a horizontal tab

Vertical tab \v Prints a vertical tab

Single quote \’ Prints a single quote

Double quote \” Prints a double quote

1234567891011121314151617

#include <iostream> intint main(){ usingusing namespacenamespace std; charchar ch; coutcout << "Input a character: "; //assume the user enters ABC cin >> ch; // ch = 'A', BC enters input buffer intint num= ch; coutcout << ch << " has ASCII code " << num << endl; cin >> ch; /*computer will not wait for input and take input from buffer*/ // ch = 'B', C enters input buffer num=ch; coutcout<<ch<<" has ASCII code "<<num<<endl; returnreturn 0;}

1 coutcout<< “Start\nend”;

1 coutcout<<“Working of\ttab”;

Page 61: Cpp

Backslash \\ Prints a backslash

Question mark \? Prints a question mark

Octal number \(number) Translates into char represented by octal

Hex number \x(number) Translates into char represented by hex number

Newline (\n) vs. std::endl — which should you use?We can use \n to move the cursor to the next line just like std::endl. However, they are slightly different.

So when should you use ‘\n’ vs std::endl? The short answer is:

You should use std::endl when you need to ensure your output is output immediately. But it might lead to loss in performance.

Usage of ‘\n’ slows down the output but at the same time it increases performance, ever so slightly.

Introduction to stringText put between double quotes (and not single as in char) is called a string (e.g. “Hello”). A string is not just a continuous collection of char. So, we will

discuss it in more detail, later.

C++ tutorialsSharing is caring

AARYAN KAPOOR

LEAVE A REPLY

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

Name *

Email *

Website

Comment

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite><code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

Post Comment

Page 62: Cpp

2.7 — Boolean Values – C++ tutorial Constants – C++ tutorial

Notify me of follow-up comments by email.

Notify me of new posts by email.

ARCHIVES

June 2015

May 2015

April 2015

March 2015

February 2015

January 2015

April 2013

META

Register

Log in

AlphaCpp.com All rights reserved. Theme by Colorlib Powered by WordPress

Search...

Page 63: Cpp

ALPHACPP.COM

Constants – C++ tutorial

March 9, 2015 Aaryan Kapoor

Symbolic constantsA symbolic constant is a name given to a constant literal value. These can be quite useful as you would not have remember (or find) these values and

write them again and again. There are two ways to declare symbolic constants in C++.

1. Using macros: We will use preprocessor directives in this case.

What it actually does is that, it simply replaces the name of the constant with the constant from compiling the program.

Consider the following snippet of code:

When you compile this code, the preprocessor replaces Pi every time with 3.1415 and then compiles it.

This is method has two benefits.

1. It can be clearly seen what is being done without adding any comment.

2. If you want to change the value (you cannot in this case, though) of the constant, you can do it once, rather than doing it at everyplace it

appears

But there are a few problems.

Firstly, macros simply replace the name with the constant value before compilation (by preprocessor) but we would still see the code as the same and so

it might get difficult to debug.

Eg: In the above example, the previous example, the computer sees the lines as

But we would still see it as

So, we would have to find the definition of Pi in the program to see what we mean here. This could get cumbersome when we have lot of #define values

are used.

Secondly, #define values have global scope. This means there can be naming issues involved i.e. a local variable having the same name as that of the

#define value.

Eg:

This program will show error. This is because preprocessor replaces this

int A=1; with int 12=1;

1 #define name constant

123

#define Pi 3.1415floatfloat area = Pi * r * r;floatfloat Perimeter = 2 * Pi * r;

123

#define Pi 3.1415floatfloat area = 3.1415 * r * r;floatfloat Perimeter = 2 * 3.1415 * r;

123

#define Pi 3.1415floatfloat area = Pi * r * r;floatfloat Perimeter = 2 * Pi * r;

123456789

#include<iostream>#define A 12 intint main(){usingusing namespacenamespace std;intint A= 1;coutcout<<A;}

Page 64: Cpp

So, the computer then tries to declare a variable with name 12, which is illegal as it starts with a digit. So, the compiler shows an error.

2. Using const keyword: We use the keyword const (constant) in this case.

It is a better way to define constants than using macros. The general form is:

where const keyword means that the value assigned to the identifier is constant;

<data_type> is any valid C++ data type; <name> is name of the identifier; and <value> is the value of the identifier.

Eg:

NOTE: It is compulsory to initialize a constant, unlike a variable.

Eg:

This will show an error.

Also, value of const cannot be changed; neither by the programmer nor by the user.

Eg: (by programmer)

This will show an error suggesting that you cannot change the value of a constant.

(by user)

Output:

1

No matter whatever the user inputs, the value of ‘a’ will remain as 1 and so the output will be 1.

The first snippet would look like this.

You might not think there is not a major difference but there is.

It solves both the problems faced by us in using macros:

Firstly, the declaration and use of constants using this method can easily be detected by the compiler as well as the person debugging the program as

the computer and debugger reads the program the same way.

Secondly, const can have any scope we want. Just like variables, constants have global, local or block scope.

Const variables act exactly like normal variables in every case except the fact that they cannot be assigned a value (after initialization).

C++ tutorialsSharing is caring

AARYAN KAPOOR

1 const <data_type> <name> = <valuevalue>;

1 const floatfloat Pi = 3.1415;

12

const floatfloat Pi;Pi = 3.1415;

12

const intint a = 1;a=2;

123

const intint a = 1;cin>>a;coutcout<<a;

123

const floatfloat Pi = 3.1415floatfloat area = Pi * r * r;floatfloat Perimeter = 2 * Pi * r;

Page 65: Cpp

Char – C++ tutorial Operators – Arithmetic – C++ tutorial

LEAVE A REPLY

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

Name *

Email *

Website

Comment

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite><code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

Post Comment

Notify me of follow-up comments by email.

Notify me of new posts by email.

ARCHIVES

June 2015

May 2015

April 2015

March 2015

February 2015

January 2015

April 2013

META

Register

Log in

Search...

Page 66: Cpp

AlphaCpp.com All rights reserved. Theme by Colorlib Powered by WordPress

Page 67: Cpp

ALPHACPP.COM

Implicit type conversion

June 3, 2015 Aaryan Kapoor

An implicit type conversion is a conversion performed by the compiler without any knowledge / intervention of the programmer. This generally happens

when we try to perform operations between variables / operands of different data types. The compiler converts all the operands to the data type of the

largest (with respect to size of the memory they use) operand. This is called Type Promotion. This is done using the following algorithm (if any of the

condition is satisfied then the compiler simply does the step otherwise checks for the next condition):

S.No If either’s type is Then resultant type of the other operand is

1. long double long double

2. double double

3. float float

4. Integral promotion (check at the end of the table)

5. unsigned long unsigned long

6. long and the other is unsigned int i) long (if long can represent all the values of the unsigned int)ii) unsigned int (iflong cannot represent all the values of the unsigned int)

7. long long

8. unsigned unsigned

Integral Promotion: A char, a short, enumerator or an int (signed/ unsigned) may be used as an int. If int can represent all the values of the original type,

the value is converted to int. Otherwise it is converted to unsigned int.

Eg:

Here we are assuming the short forms of data types (and not their variables) to tell you the resultant data types in each case.

char ch; int i; long l; unsigned long ul; float fl; double db; long double ldb;

((ch+i) * (l / fl)) – ((ul*i) / (db * ldb))

= (i * fl) – (ul / ldb)

= fl – ldb

= ldb

We have avoided the examples where it depends upon the values (eg- unsigned int and long, unsigned int and int) as it cannot be simply predicted.

Sharing is caring

AARYAN KAPOOR

LEAVE A REPLY

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

Name *

Page 68: Cpp

compare the two strings Explicit Type Conversion

Email *

Website

Comment

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite><code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

Post Comment

Notify me of follow-up comments by email.

Notify me of new posts by email.

ARCHIVES

June 2015

May 2015

April 2015

March 2015

February 2015

January 2015

April 2013

META

Register

Log in

AlphaCpp.com All rights reserved. Theme by Colorlib Powered by WordPress

Search...

Page 69: Cpp

ALPHACPP.COM

Explicit Type Conversion

June 3, 2015 Aaryan Kapoor

Unlike Implicit type conversion, explicit type conversion is done by the programmer. In this type conversion, the programmer forces an expression to be

of the specific type. This is done by:

where type is any valid C++ data type to which conversion is to be done.

The explicit conversion of an operand to a specific is known as ‘type casting’.

Eg:

Output:

2

2.5

Clearly, in the first case, there is integral division and the resultant is the quotient you would get on dividing two integers (without decimal part, not even

zeroes). In the second case, we have converted the expression is converted to a float i.e. all terms are treated as float (with decimal part) using external

type conversion. So, the resultant is also a float.

You might think this works for a single term but this is not true. This works for all the terms in the expression.

Eg:

int a=5, b=2, c=1, d=4;

cout<< a/b * c/d<<endl;

cout<< (float) a/b * c/d;

Output:

0

0.625

In the first case, (as earlier) integral division is taking place. The term should have been evaluated to 0.625, but the term is evaluated till 0 only. In the

second case, ‘THE WHOLE EXPRESSION’ is converted to float, making all the terms float. This leads to complete division and finally the result is 0.625.

As you might have noticed by now, type casting is unary operator.

If we want to convert a value to a bigger data type (in terms of their size), there is no issue. But if we convert a value to a lower data type, we could

face some potential problems:

1. Loss of precision

2. Loss of data (the original value was out of range for the new data type)

Eg: On converting a value from floating type to integer type (say, float to int) there maybe loss of fractional part (if there was any). If original value was

out of range for integer type, then the result is undefined.

Sharing is caring

AARYAN KAPOOR

1 (type) expression

1234

//We want to completely divide two integersintint a = 5, b = 2;coutcout<< a/b<<endl;coutcout<< (floatfloat)a/ b;

Page 70: Cpp

Implicit type conversion comments in java

LEAVE A REPLY

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

Name *

Email *

Website

Comment

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite><code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

Post Comment

Notify me of follow-up comments by email.

Notify me of new posts by email.

ARCHIVES

June 2015

May 2015

April 2015

March 2015

February 2015

January 2015

April 2013

META

Register

Log in

Search...

Page 71: Cpp

AlphaCpp.com All rights reserved. Theme by Colorlib Powered by WordPress

Page 72: Cpp

ALPHACPP.COM

Operators – Arithmetic – C++ tutorial

March 10, 2015 Udit Pandoh

Arithmetic operators are used to carry all the arithmetic operations in a c++ program, these are further divided into unary and binary operators

Binary Operators

Function Symbol Example

Addition + a + b

Subtractoin - a - b

Multiplication * a * b

Devision / a / b

Modulus % a % b

Now in this C++ tutorial we will study Binary operators. The word binary itself suggests that two values are required to perform the operation i.e I cannot

add a single variable i need to at least two values to perform addition.

some example are

Modulus operator

You are familiar with all of these except the modulus operator, it used to find the modulus of the first operator relative to the second suppose we are

taking two values a and b if i apply the modulus operator it return the remainder obtained when we divide a by b.

Note – The operator only works when both the values are integers

the above expression evaluates to 1 since on dividing the 21 by 5 we obtain a remainder of 1 .

At first you may think what is the need for the modulus operator but in fact it is very useful in c++ , consider this

1) Check whether 5 is a prime or not.

2) Check whether a number is an odd number.

3) Check whether a number is a multiple of 5.

All these cases require the use of the modulus operator for example in the first case if i were to check weather a number is a prime number or not i would

simply divide the number by 2 , 3 and 4 if the remainder is not 0 in any case 5 is a prime number as the modulus operator giving result 0 indicates

the first number is completely divisible by the second number.

Similarly in the second case to check if a number is odd or not i will simply apply the modulus operator between the number and 2 ,check what result it

yields as we know that even number are those numbers are multiple of 2 therefore if the result will be zero i will know that the number is not an

odd number.

Third case is pretty simple we will use the same basic principle.

Another interesting use one can think of is that if i were two print all number from 10 to 20 on a screen , but changing line after every 5 numbers, it will

1 a + b ;

1 a - b ;

1 c * d ;

1 c / d ;

1 21 % 5

Page 73: Cpp

Constants – C++ tutorial Operator – Increment and Decrement – C++ tutorial

simply activate endl

when the following expression results in 0.

Though we don’t know how to write this program right now, i gave the example to tell you how can we us modulus operators in a c++ program.

C++ tutorialsSharing is caring

UDIT PANDOH

LEAVE A REPLY

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

Name *

Email *

Website

Comment

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite><code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

Post Comment

Notify me of follow-up comments by email.

Notify me of new posts by email.

1 number of words already printed % 5

ARCHIVES

June 2015

May 2015

April 2015

Search...

Page 75: Cpp

ALPHACPP.COM

Operator – Increment and Decrement – C++ tutorial

March 11, 2015 Udit Pandoh

Function Symbol Example

Pre Increment ++ ++x

Pre Decrement -- --x

Post Increment ++ x++

Post Decrement -- x--

As we will study more you will find out that many times we need to add or subtract 1 from a variable say x .

since it is a very common practice, we have two operators known as increment operator and the decrement operator.

The Increment operatorIn this section of Cpp tutorial, Increment operator as discussed above is used to add one to a given variable . there are two ways of using increment

operator

first is the prefix version, for a variable x it would be

One should Note there is no difference between writing

But that’s not it there is also the postfix version, in the postfix version first the value is evaluated in the expression before its increment. I know it

may seem a bit confusing but let me give u an example first.consider

You may think that here x will become 8 and then 7 will be added which will result in y to hold the value 15, but you are wrong remember the statement

I gave above.

Lets understand why we are wrong when we evaluate y to 15 we assume that first x was incremented and then value of y was calculated.

But first the statement is evaluated therefore in the above example y will be evaluated first , therefore it will be equal to 14 ( 7 + 7 ) i.e after is is

evaluated then x will be incremented and hold the value 8. if we were to do any calculation in the next statement there x would be equal to 8 instead of

7.

Consider this program if you have understood what as meant above.

123

x = x + 1//orx = x - 1

1 ++x ;

123

++x ;//orx = x + 1 ;

123

intint y , x = 7 ;y = ( x++ ) + 7 ;coutcout << y ;

12345

intint x = 8 , y = 4 ;coutcout << x <<y ; // 1 statementcoutcout <<++x <<y ; // 2coutcout <<x <<++y ; // 3coutcout <<x ++ <<y ++ ; // 4

Page 76: Cpp

Operators – Arithmetic – C++ tutorial Operators- Relat ional- C++ tutorial

Well lets evaluate all these statements one by one in the first statement program simply outputs the values of x and y i.e 8 and 4 in the second

statement we applied the prefix increment here x is incremented and then evaluated therefore here x and y will be 9 and 4 respectively, remember in

prefix increment or decrement first variable is incremented or decremented and then evaluate unlike postfix version. In the third case x

simply retains the value 9 whereas y is incremented and then evaluated this gives the result 9 and 5 respectively for x and y. In the fourth statement ,

this is postfix increment hence both x and y are evaluated but the effect of increment will occur in the next statement i.e x and y will still be equal to 9

and 5. in the fifth statement though we simply output the values of x and y but the effect of increment will take place and hence x and y will now be

equal to 10 and 6 respectively

Decrement operatorIn this section of C++ tutorial, Decrement operator is same in every way to the increment operator except the face that instead of ++ , — is used .

This should be enough make you understand these two operators.

C++ tutorials

Sharing is caring

UDIT PANDOH

LEAVE A REPLY

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

Name *

Email *

Website

Comment

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite><code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

Post Comment

Notify me of follow-up comments by email.

Notify me of new posts by email.

6 coutcout <<x <<y ; // 5

Search...

Page 78: Cpp

ALPHACPP.COM

Operators- Relational- C++ tutorial

March 12, 2015 Aaryan Kapoor

What if you want the user to input two numbers and check which of them is greater? Here, we take help of relational operators.

Relational operators compare the values among different operands and give the result. Relational operators result in Boolean value i.e. they give result as

1, if the relation is true, and 0, if the relation is false.

Since two values can have only the following relations:

1. 4 < 5

2. 6 > 1

3. 3 = 3

So, we have relational operators based on these 3 conditions:

Symbol Name Example Result

== Comparison (equality) 3 == 5 0

< Less than 3 < 5 1

> Greater than 3 > 5 0

<= Less than or equal to 3 <= 5 1

>= Greater than or equal to 3 >= 5 0

!= Not equal to 3 != 5 1

NOTE: A very common mistake is to use the assignment operator (=) in place of relational operator (==). You should not be confused

between them.

Eg:

See this program to clarify any further doubts.

Output will be:

num==2 prints 0

num=2 prints 2

For the first statement, the system checks whether the variable named num is equal to 2. Since it is false, thus it results in 0.

In the second statement, (=) being the assignment operator, assigns the value 2 to the variable named num. Now, we try to print ‘num’. So, the

resultant output is 2.

The relational operator has lower precedence than arithmetic operators. Thus, the system reads:

a+2<b+3

as

12

a==12; //checks whether a is equal to 12a=12; //assigns 12 to a;

123456789

#include<iostream>intint main(){ UsingUsing namespacenamespace std; intint num=3; coutcout<<“num==2 prints ”<<num==2<<endl; coutcout<<“num=2 prints ”<<num=2;returnreturn 0;}

Page 79: Cpp

(a+2)<(b+3)

Rather than

a+(2<b)+3

So, you must be careful.

Relational operators between signed and unsignedWe must avoid comparing signed and unsigned integers. This is because, when we compare signed and unsigned the compiler treats signed integers as

unsigned and thus produce unexpected results.

Eg:

Output:

0

This is completely unexpected. Let’s see how it works (you need to know how data is stored using binary).

3 is stored in memory as 0000 0011.

-1 is stored in memory as 1000 0001.

Since, it treats -1 as unsigned, thus 1000 0001 will translate to 129, which is clearly greater than 3.

If you really have to compare, then you need cast (type-casting, about which you have already learnt) as follows:

in the previous example.

But, you must remember that you should use bigger of the data types, so that both of the values can be compared without error.

Eg:

Relational operators for floating pointYou must avoid using relational operators for floating point numbers. This is because; they often have rounding off errors that might cause some

unexpected results.

Eg: 4.3*5.05=21.7 (when precision is 1)

4.3*5.05=21.715 (when precision is 3 or more)

Clearly, floating point numbers will not even equate two same expressions in this case. Because of errors, we should avoid the comparison of floating

type, still sometimes its unavoidable so we will cover it in later tutorials.

C++ tutorialsSharing is caring

AARYAN KAPOOR

LEAVE A REPLY

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

Name *

123

intint a=-1;unsignedunsigned b=3;coutcout<< a<b;

1 a<(signedsigned intint)b;

123

intint num1=-3;unsignedunsigned num2=123;coutcout<<“num1<num2 = ”<<(signedsigned longlong)num1<(signedsigned longlong)num2;

Page 80: Cpp

Operator – Increment and Decrement – C++ tutorial Operators- Logical – Cpp tutorial

Email *

Website

Comment

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite><code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

Post Comment

Notify me of follow-up comments by email.

Notify me of new posts by email.

ARCHIVES

June 2015

May 2015

April 2015

March 2015

February 2015

January 2015

April 2013

META

Register

Log in

AlphaCpp.com All rights reserved. Theme by Colorlib Powered by WordPress

Search...

Page 81: Cpp

ALPHACPP.COM

Comma and conditional operators – Cpp tutorial

May 13, 2015 Aaryan Kapoor

The Comma OperatorA comma operator is used to combine several expressions. The expressions are executed from left to right and the result of the operator is the result of

the rightmost expression.

NOTE: It has the lowest precedence, and must always be enclosed within brackets.

Eg:

This assigns 3 to a along with assigning 1 to b and 2 to c. This works in the same way as:

See another example:

The output will be:

x= 2

y=1

It simply works on the fact that comma operator has lower precedence than even assignment operator.

As we shall see, the comma operator does not find much use in programming except the for loop, about which you will learn later.

You must see two things here:

1. The comma used between parameters in function calls (you will learn later) is a separator i.e. used to separate and not an operator.

Eg:

The comma used when two or more variables are declared is also a separator and not an operator.

Eg:

so this point leads to another example:

The compiler shows an error here.

what actually happening here is that the computer first assigns 1 to x and then tries to create variables of name 2 and 3, which are not allowed as they

start with a digit. So, there is an error.

Conditional operator

1 intint a= (b=1, c=b+1, c+1);

123

intint b=1;intint c=b+1;intint a=c+1;

12345

intint x, y;x= (1, 2);y= 1, 2;coutcout<< “x = ”<<x<<endl;coutcout<< “y= ”<<y;

12345

intint func (intint x, intint y) //this is not an operator{//does something}intint a=func(b,y) //this is not an operator

1 intint x, y, z; //this is not an operator

1 intint x= 1, 2, 3;

Page 82: Cpp

For example, you have to announce if the person has passed (‘p’) or failed (‘f’) based on their marks.

This can be easily done with the help of conditional operator.

Conditional operator is a ternary operator i.e. it operates on 3 operands. The general form of conditional operator is:

expression1?expression2:expression3

This means, if expression1 is true, expression2 is executed, otherwise expression3 is executed.

Eg:

This simply means if the marks entered by the user are greater than or equal to 50, the result would be P (pass), otherwise, it would be F (fail).

This also shows that conditional operator has higher precedence than assignment but lower than relational operator. In fact, the precedence is quite low

just above comma operator and assignment operator. So, it is a better idea to put it in brackets, to avoid any risk of error.

See this for example:

So, this program is for a shop that gives a base discount of 10% and another 10% if your bill crosses 5000. But, the program is not giving expected

results. This is because, + has greater precedence than conditional operator. So, the computer adds base (10) to the bill amount and checks if it is true.

If it is true, it gives a total discount of 10% and if it is false, it gives no discount at all.

The corrected program will be:

Conditional operators can be used to assign a particular value to a variable (out of two), based on the condition being true or false.

Eg:

You can also nest two or more conditional operators.

Eg:

The programs assigns grade as A, B or C based on the marks.

But you should avoid conditional operators as they soon become too difficult to understand and error prone. (It is better you use if-else statements,

about which you will learn latter).

C++ tutorialsSharing is caring

AARYAN KAPOOR

LEAVE A REPLY

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

Name *

12

cin>>marks;charchar result = marks>=50? ‘P’: ‘F’;

12

intint base=10;intint disc=base + bill>5000?10:0;

12

intint base=10;intint disc=base + (bill>5000?10:0);

123

intint grt, lsr, num;cin>>num;num>100?grt:lsr=1;

12

cin>>marks;charchar grade= marks>=75?(marks>=90? ‘A’: ‘B’): ‘C’;

Page 83: Cpp

Break And Continue – C++ Tutorial Arrays – C++ Tutorial

Email *

Website

Comment

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite><code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

Post Comment

Notify me of follow-up comments by email.

Notify me of new posts by email.

ARCHIVES

June 2015

May 2015

April 2015

March 2015

February 2015

January 2015

April 2013

META

Register

Log in

AlphaCpp.com All rights reserved. Theme by Colorlib Powered by WordPress

Search...

Page 84: Cpp

ALPHACPP.COM

Operators- Logical – Cpp tutorial

March 14, 2015 Aaryan Kapoor

What happens when you want to test not one but, say, two or more conditions together? Like, when you want to check your email must know your

email address as well as password. When one of them doesn’t satisfy the condition (are not correct) the emails won’t open up.

This is what logical operators do. They basically help you check whether or not one or more of the conditions specified are true, exception being the

NOT operator.

NOTE: Knowledge about truth table will help you understand these operators better. But their knowledge is not necessary.

There are three logical operators to combine various expressions:

1. || (logical OR)

2. && (logical AND)

3. ! (logical NOT)

Logical ORThe logical OR (||) combines the expressions as treats them as operands. This operator results in true (1) whenever at least one of the two operands is

true (1) and false (0) only when both of these are false (0).

You can simply remember this principle using this example.

Eg: expression1 || expression2

This whole expression is true whenever expression1 is true OR expression2 is true.

Example Expression 1 Expression 2 Result

3==1||4<1 0 0 0

1<=3||4>=7 1 0 1

5!=5 ||1==1 0 1 1

5>2 || 5 1 1 1

The OR operator has lower precedence than the relational operators and thus we do not need any brackets for the expressions to produce result first.

In the last example we have taken use of the fact that C++ considers 0 as false and any non zero as true.

NOTE: It is the symbol on the left of backspace, looks like a broken bar (¦).

Logical ANDThe logical AND (&&), also, combines the expressions as treats them as operands. This operator results in false (0) whenever at least one of the two

operands is false (0) and true only when both of these are true (1).

You can simply remember this principle using this example.

Eg: expression1 && expression2

This whole expression is true whenever expression1 is true AND expression2 is true.

Example Expression 1 Expression 2 Result

3==1&&4<1 0 0 0

1<=3&&4>=7 1 0 0

5!=5 &&1==1 0 1 0

5>2 && 5 1 1 1

Page 85: Cpp

The AND operator has lower precedence than the relational operators and thus we do not need any brackets for the expressions to produce result first.

We have used the same examples so you can clearly see the difference between OR and AND.

Logical NOTLogical NOT (!), unlike the others, works on a single expression/operand. Logical NOT operator simply reverses the result, i.e. turns true to false and vice

versa.

You can simply remember this principle using this example.

Eg: !(testexpression)

The whole expression results in true only when the testexpression is NOT true (false).

Examples Expression Result

!(5>2) 1 0

!(5) 1 0

!(1<3) 0 1

!(0) 0 1

You might have noticed that we have used brackets here. This is because logical NOT has one of the highest precedence, just behind post increment

and post decrement that we have learnt in the previous Cpp tutorial.

Eg: !(1<2) results in 0

while !1<2 results in 1

Let’s see how this works.

In the first example, the system reads it as (!(1<2)). So, it first evaluates 1<2 as 1 (true). Then the logical NOT converts 1 into 0.

In the second example, the system reads it ((!1)<2). So, it first converts 1 to 0 (false). Then it evaluates 0<2 as 1 (true).

You can also combine these operators together. But, you must remember that the precedence order is:

NOT>AND>OR

Eg:

1. !(1<2||2>3)

Solution: !(1<2||2>3)

=>!((1<2)||(2>3))

=>!(1||0)

=>!(1)

=>0

Thus, !(1<2||2>3) evaluates to 0.

2. int x=21, y=123, z=12;

x<12 || y<200 && z==12

Solution: x<12 || y<200 && z==12

=>(x<12)||((y<200)&&(z==12))

=>(0)||(1&&1)

=>(0)||(1)

=>1

C++ tutorialsSharing is caring

Page 86: Cpp

Operators- Relat ional- C++ tutorial Precedence of operators – C++ tutorial

AARYAN KAPOOR

LEAVE A REPLY

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

Name *

Email *

Website

Comment

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite><code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

Post Comment

Notify me of follow-up comments by email.

Notify me of new posts by email.

ARCHIVES

June 2015

May 2015

April 2015

March 2015

February 2015

January 2015

April 2013

META

Register

Search...

Page 87: Cpp

Log in

AlphaCpp.com All rights reserved. Theme by Colorlib Powered by WordPress

Page 88: Cpp

ALPHACPP.COM

Precedence of operators – C++ tutorial

March 15, 2015 Aaryan Kapoor

In this C++ tutorial we will learn about the precedence (importance) order is just similar to the BODMAS we learnt in school. Just like BODMAS, it specifies

the order in which the expression (no matter if it is logical, arithmetic, relational or a combination of these) will be executed.

The following table shows the precedence order:

++ (post increment), — (post decrement)

++ (pre increment), — (pre decrement), + (unary plus), – (unary minus), sizeof, ! (logical NOT)

* (multiplication), / (division), % (modulus/remainder)

+ (addition), – (subtraction)

< (less than), <= (less than or equal to), > (greater than), >= (greater than or equal to)

== (equal to), != (not equal to)

&& (logical AND)

|| (logical OR)

?: (conditional operator)

= (assignment operator), other assignment operators (like +=, -=)

, (comma operator)

Here, the precedence decreases from top to bottom. Also, the operators in same box have same precedence.

Let us look at a few examples to see how it works (try to solve them on your own before looking at the solutions).

1.

Output:

Solution:

12

y = 11 < 10 + 3 && 7 * 2>= 28 / 2;coutcout<<y;

1 1

123456789

y = ((11 < (10 + 3)) && ((7 * 2) >= (28 / 2))) y = ((11 < (10 + 3)) && (14>=14)) y = ((11 < 13) && 1) y = (1 && 1) y = 1

12

x = (y = 13, z=0, z != 10 + 3 > --y)coutcout<<x;

Page 89: Cpp

2.

Output:

Solution:

3.

Output:

Solution:

4.

Output:

Solution:

1 1

123456789101112131415

x = ((y = 13), (z=0) (z != ((10 + 3) > (--y))) //y becomes 13 and z becomes 0 x = (z != ((10 + 3) > (--y))) /*y becomes 12 and then used as pre increment is used*/ x = (0 != ((10 + 3)> 12)) x = (0 != (13 > 12) x = (0 != 1) x = 1

12

x = (y = 13, z=0, z != 10 + 3 > y--)coutcout<<x;

1

123456789101112131415

x = ((y = 13), (z=0) (z != ((10 + 3) > (y--))) //y becomes 13 and z becomes 0 x = (z != ((10 + 3) > (y--))) x = (0 != ((10 + 3) > 13)) /*after this, y becomes 12 as post increment is used*/ x = (0 != (13 > 13)) x = (0 != 0) x = 0

12

a = (b = 1, 30 + 93 - 26 == 90 || 8 - 63 / 9 > -b * 11 + b)coutcout<<!a;

1

123

a = ((b = 1), (((30 + 93 - 26) == 90) || ((8 - (63 / 9)) > (((-b) * 11) + b))) //b becomes 1 a = (((30 + 93 - 26) == 90) || ((8 - (63 / 9)) > (((-b) * 11) + b)))

Page 90: Cpp

5.

Output:

Solution:

C++ tutorialsSharing is caring

AARYAN KAPOOR

LEAVE A REPLY

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

Name *

Email *

Website

Comment

4567891011121314151617

a = (((30 + 93 - 26) == 90) || ((8 - (63 / 9)) > ((-1 * 11) + 1))) a = (((30 + 93 - 26) == 90) || ((8 - 7) > (-11 + 1))) a = ((97 == 90) || (1 > -10)) a = (0 || 1) a = 1 Since a = 1; Therefore, !a = 0;

1 s = (n = 1000, m = 450, n <= 1000 && ! (m == 1000) ? 1 : 0)

1 1

123456789101112131415

s = ((n = 1000), (m = 450), (((n <= 1000) && (! (m ==1000))) ? 1 : 0)) //n becomes 1000 and m becomes 450 s = (((1000 <= 1000) && (! (450 == 1000))) ? 1 : 0) s = (((1000 <= 1000) && (! 0)) ? 1 : 0) s = (((1000 <= 1000) && 1) ? 1 : 0) s = ((1 && 1) ? 1 : 0) s = (1 ? 1 : 0) s = 1

Page 91: Cpp

Operators- Logical – Cpp tutorial Understanding Funct ions – C++ tutorial

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite><code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

Post Comment

Notify me of follow-up comments by email.

Notify me of new posts by email.

ARCHIVES

June 2015

May 2015

April 2015

March 2015

February 2015

January 2015

April 2013

META

Register

Log in

AlphaCpp.com All rights reserved. Theme by Colorlib Powered by WordPress

Search...

Page 92: Cpp

ALPHACPP.COM

Understanding Functions – C++ tutorial

April 1, 2015 Udit Pandoh

Functions are very essential to any coding language. A function can be defined as a set of statement used to achieve a particular task. though we know

what it means lets understand what can we use a function for.

Why do I need functions ?Suppose you are running in a marathon at a point of time during the run you become thirsty and you stop running, take a sip of water and then start

running again .

similarly in c++when a program is being executed it is executed sequentially i.e line by line , now when compiler encounters a function call, it pauses the

execution (similar to stops running )at that point runs the new function (like drinking water )and when it is complete ,it returns to is original state (starts

running again).

Lets understand the body of a function first.

Declarationwhen we write a variable we write int x , where x is the name of the variable and int is its data type , declaration of a function is something similar first we

declare what will the data type of the return (to be covered shortly) – in this case int , and second is whatever name we want to give to the function.

Note – Ignore the parentheses for now we will cover it in next topic.

Defining

i – Body

If we consider the first function our aim is to drink water, the statements like

1) Take out the water bottle,

2) Open it and drink water from it.

3) Close the bottle.

are what constitute the body of the function – drinking water, therefore what is the body ? It is the set of statements we will use to direct the

function what we want to do.remember that all the function body is put between the brackets ‘{‘ and ‘}’

ii – Return

What is return ? Well after the statements in the function body are executed function uses return, to give out a value to the original function it was

called from ( drinking water function was called from running function).

when we will run this program, the function ‘anyname’ gives a value of 5 to the main where it is being used after ‘<<‘ operator therefore we will get an

output i.e 5 on the screen.

Note – return is also a part of the functions body hence comes under the curly brackets.

Sometimes if we do not want to return any value we simply return a value of 0 which means the function ran successfully for eg – we don’t want to

return any value in the hello world program so we return a value of 0.

12345

intint name ( ){bodyreturnreturn valuevalue}

123456789

intint anyname( ){returnreturn 5 ;} intint main( ){coutcout << anyname() ;}

123456

#include <iostream>usingusing namespacenamespace std; intint main(){coutcout <<" hello world " ;

Page 93: Cpp

int main ( )

One should remember that we have to write all our code inside the main function except the definition of other function.when the execution of the

program starts first the operating system send a call to function main form where the each statement is evaluated sequentially and returning 0 tells the

operating system that the program execution was successful.

Using Function In A Program

Once we have defined a function we need to use, simply write the name of the code followed by parentheses this will direct the compiler start that

function

Now that we have understood the basics of a function lets try to put it in use to ensure it, if we were making a program that asked your favorite number

and then display them.

First we will make it without using any function.

One thing that might confuse you is that in ‘ x + y + z ‘ we did not store their value in a variable because we simply didn’t need to store the sum in the

memory,just display it once.

We can see almost same code has been used thrice in the program therefore it will be better to use a function instead of this

repetition.

See the difference our code is much cleaner and understandable now !!

78

returnreturn 0 ;}

123456789101112131415161718192021

#include <iostream>usingusing namespacenamespace std;intint main( ){intint x , y , z ; coutcout <<" whats your favorite number ? " ;cin >>x ;coutcout <<endl <<"you said - " <<x <<endl; coutcout <<" whats your favorite number ? " ;cin >>y ;coutcout <<endl <<"you said - " <<y <<endl; coutcout <<" whats your favorite number ? " ;cin >>z ;coutcout <<endl <<"you said - " <<z <<endl; coutcout <<"and the sum is - " << x + y + zreturnreturn 0 ;}

1234567891011121314151617181920

#include <iostream>usingusing namespacenamespace std; intint getfavno( ){intint xcoutcout <<" whats your favorite number ? " ;cin >>x ;coutcout <<endl <<"you said - " <<x <<endl ;returnreturn x ;} intint main{intint a , b, c;intint a = getfavno( ) ;intint b = getfavno( ) ;intint c = getfavno( ) ;coutcout <<"sum is " <<a + b +c ;returnreturn 0;

123456789101112

//consider this program#include <iostream>usingusing namespacenamespace std;intint doA ( ){coutcout << " a is executed " <<endl ;returnreturn 0 ;} intint doB ( ){coutcout <<" b is executed " <<endl ;

Page 94: Cpp

Note – The program is simple when we run it first function ‘doB’ is executed and then since it is legal to use one function in another function ‘doA’

is executed and then ‘doC’ ,But when we run the program the compiler shows

[ error C3861: ‘doC': identifier not found ]

As we already discussed the compiler executes the program sequentially so when the compiler is at the line 10 till then function ‘doC’ is not declared and

since it is not declared it dose not know what ‘doC’ means. We must learn that whenever we are using function its declaration should be done

before any line it is being used on.

therefore in order to make this program work we will shift the declaration of ‘doC’ before the declaration of ‘doB’.

consider this program

And voila then function !! will run successfully !!

Understanding more about returnRemember that what function does when return is used , is that it gives out some value, we can then use this value in the main program , for example.

Well how is this happening ?? the author is treating the function call like it was a value well that is what it is, because when compiler runs add( ) it basically

evaluates to nothing but a simple value hence when we write something like this .

so all the statement given below can be used in int main ( )

131415161718192021222324252627

doA( );doC( );returnreturn 0 ;}intint doC ( ){coutcout <<" c is executed " <<endl ;returnreturn 0 ;} intint main( ){doB( ) ;returnreturn 0 ;}

12345678910111213141516171819202122232425262728

#include <iostream>usingusing namespacenamespace std; intint doA ( ){coutcout << " a is executed " <<endl ;returnreturn 0 ;} intint doC ( ){coutcout <<" c is executed " <<endl ;returnreturn 0 ;} intint doB ( ){coutcout <<" b is executed " <<endl ;doA( ) ;doC( ) ;returnreturn 0 ;} intint main( ){doB( ) ;returnreturn 0 ;}

12345678910

intint add ( ){intint c = 3 + 4 ;returnreturn c ;}voidvoid main ( ) {coutcout << add ( ) ;coutcout << add( ) + 5 ;}

1 add ( ) // for the compiler it is just a value 7.

123

intint main {coutcout << add( ) ;

Page 95: Cpp

Precedence of operators – C++ tutorial Parameters I – C++ tutorial

Note though we are using add( ) with operators we cannot say

//add ( ) = some expression ;

This is because add( ) already evaluates to a value that is 7 as we know we cannot keep a constant value at the left hand side of ‘ = ‘.

so from this tutorial we understood the merits of function and how to use them remember :

1) function help us when a task is being repeated.

2) It helps to make our code more organised by breaking it down to smaller parts.

We know it may be confusing at once, feel free to ask us and try reading it again.

C++ tutorialsSharing is caring

basics c++ coding compiler cpp funct ion introduct ion learn program t ips tutorial tutorials user visual studio

UDIT PANDOH

LEAVE A REPLY

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

Name *

Email *

Website

Comment

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite><code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

Post Comment

Notify me of follow-up comments by email.

Notify me of new posts by email.

456

intint a = add( ) - 5 ; intint c = add( ) * 4 ;}

Page 97: Cpp

ALPHACPP.COM

Parameters I – C++ tutorial

April 2, 2015 Udit Pandoh

From what we learned in the earlier C++ tutorial without going any further try to create a c++ program which adds two numbers and give the output.

You must have written the code like this.

Now there is a big problem here if I told u to add numbers 2 and 3 also in this function only what would you do ? We would have to create another

function which adds 2 and 3, but ! We already discussed a functions job is to make the code smaller but in this case it does not.

What if we could call the same function again and again to add different numbers ? It will be pretty cool if u ask me. In the function add( ) we kind of

hard wired it to add two particular numbers i.e 5 and 6 , all we need to do is we will make this part of the function flexible and therefore we can call this

function whenever we need to add any two numbers.

Lets be logical ,since the values we will pass to the function will not be fixed now i.e the new function that we will create does not already know what

value we will give it to add thus these values needs to be variables for the function that is the only way to achieve the flexibility.

But we do need to keep some things fixed in the function i.e the number of values to be added and their data types (for now we are only taking integers

we will cover data types in next chapter ).

Lets consider the first statement of the function first.

Well first two things are pretty much same , now inside the function we declared two variables, because we will be adding two numbers ( the reason was

discussed above ).

Now we specify that they both are integers , rest of the body will be same its just that we replace fixed values 5 and 6 in our first example with a and b

and voila !!

The next thing is how to declare this new function now in a program we will cover this in the next topic.

C++ tutorialSharing is caring

UDIT PANDOH

LEAVE A REPLY

12345678910111213

#include "stdafx.h"#include <iostream>usingusing namespacenamespace std ;intint add ( ){intint c ;c = 5 + 6 ;returnreturn c ;}voidvoid main ( ){coutcout << add( ) ;}

1 intint add (intint a , b)

12345

intint add (intint a , b){c = a + b ;returnreturn c}

Page 98: Cpp

Understanding Funct ions – C++ tutorial Parameters – II – C++ tutorial

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

Name *

Email *

Website

Comment

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite><code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

Post Comment

Notify me of follow-up comments by email.

Notify me of new posts by email.

ARCHIVES

June 2015

May 2015

April 2015

March 2015

February 2015

January 2015

April 2013

META

Register

Log in

Search...

Page 99: Cpp

AlphaCpp.com All rights reserved. Theme by Colorlib Powered by WordPress

Page 100: Cpp

ALPHACPP.COM

Parameters – II – C++ tutorial

April 3, 2015 Udit Pandoh

Lets revise, we learned that we can add parameters in a function which helps us to make our function flexible and the code more efficient lets write the

function once again.

here what we have in between the parentheses are the parameters by looking at the code we can say our function is taking two parameters both of

type integer.

Calling the functionnormally for a function named add , we would call the function like

Since we are taking parameters now we will call the function pretty much in the same way but this time we will do something like this

remember in the definition we did

Even in the functions body think it like the variable a was replaced by 3 and b will become 4

i.e

becomes

Note – this was just for your understanding the functions definition remains in the terms of variables only when we are writing the

program, we never change the function all we change is the way we call it in int main( ).

Lets consider a full example to make sure we have understood this topic well.

123456789

#include "stdafx.h"#include <iostream>usingusing namespacenamespace std ;intint add ( intint a , intint b ){intint c ;c = a + b ;returnreturn c ;}

1 add ( ) ;

1 add( 5 , 6 ) ;

1 intint add ( intint a , intint b )ifif you compare two we get that forfor the functionfunction will treat a asas 5 andand b asas 6 thus

12

add ( 3 , 4 )//for this call variable a will become and b will become 4

123456

intint add ( intint a , intint b ){intint cc = a + b ;returnreturn c ;}

123456

intint add ( 3 , 4){intint cc = 3 + 4 ;returnreturn c ;}

123456

#include "stdafx.h" // only to be used for visual studios.#include <iostream>usingusing namespacenamespace std ;voidvoid add ( intint a , intint b ){intint c ;

Page 101: Cpp

Parameters I – C++ tutorial Void – C++ tutorial

If we run this program it will give us the output

C++ tutorialSharing is caring

UDIT PANDOH

LEAVE A REPLY

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

Name *

Email *

Website

Comment

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite><code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

Post Comment

Notify me of follow-up comments by email.

Notify me of new posts by email.

78910111213141516

c = a + b ;coutcout << c <<endl ;}intint main ( ){add ( 3 , 4 ) ;add ( 1 , 9 ) ;add ( 4 , 2 ) ;add ( 5 , 6 ) ;}

1234

710611

Search...

Page 103: Cpp

ALPHACPP.COM

Void – C++ tutorial

April 4, 2015 Aaryan Kapoor

Remember when we are using functions , we always return some value , what if we do no want to return anything consider this function.

voidhere we did not really want to return anything to the main, here we use what is called Void, basically void means no value/ no type i.e no values can be

stored in identifiers of void data type.We could have written our first example like this.

Note – since void already means ‘no value’ we do not need to give a return type. lets try to understand its various uses.

1) It is used to indicate that a function does not return a value.

2) It is used to indicate that the function does not take any parameters.

The following code is equivalent in C++:

Thus, the use of keyword void to mean no parameters is not required in C++.

3) Because void means no type, you cannot declare variables of type void.

An important use of void is in void pointers. Since, you still don’t know what pointers are, so we will not discuss it here but in the later Cpp tutorial.

12345678910

intint hello( ){coutcout << " hello world" ;returnreturn 0 ;}intint main ( ){hello ( ) ;returnreturn 0 ;}

12345678

voidvoid hello( ){coutcout << " hello world " ;}voidvoid main ( ){hello ( ) ;}

12345

VoidVoid sum (intint a, intint b) \\declaration of a functionfunction named sum{intint c=a+b;coutcout<<“The Sum isis: ”<<c;}

1234567

intint apples(voidvoid) //void here means no parameter is required.{intint num;coutcout<<“Enter the number of apples: ”;cin>>num;returnreturn num; //Here the function returns a value to the place it was called}

1234567

intint apples() //void here means no parameter is required.{intint num;coutcout<<“Enter the number of apples: ”;cin >>num;returnreturn num; //Here the function returns a value to the place it was called}

1 voidvoid a; //This is wrong

Page 104: Cpp

Parameters – II – C++ tutorial Forward declarat ions – C++ tutorial

C++ tutorialSharing is caring

alphacpp basics c++ coding compiler cpp introduct ion learn program statements t ips tutorials user variable variables visual studio

void

AARYAN KAPOOR

LEAVE A REPLY

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

Name *

Email *

Website

Comment

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite><code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

Post Comment

Notify me of follow-up comments by email.

Notify me of new posts by email.

ARCHIVES

June 2015

May 2015

April 2015

March 2015

February 2015

Search...

Page 106: Cpp

ALPHACPP.COM

Forward declarations – C++ tutorial

April 5, 2015 Udit Pandoh

From what we have learned till now we can say that we may use functions in a program but main ( ) is the most important as it tells us what is actually

being done in our c++ program.

Consider this example here my friend Dhruv has created three functions for addition multiplication and some output ‘ hi ‘.

Though this program will ran successfully Dhruv keeps adding more function to the program , after some time he finds that it would be more cleaner

and convenient if the function main ( ) was declared first and the other functions later, so he rewrote the first function like this.

But this program did not compiled successfully and showed a lot of errors , well can u think of an explanation ?

Remember – In c++ the program is compiled line by line i.e compilation is done sequentially , which starts from function main ( ) in the

last example in line 5th compiler encountered a call to the function main , but till that line compiler has not encountered anything about

a function add , hence it shows an error.

Forward declarationsHence we can use something known as forward declarations which enables us to declare the function after the main ( ) .lets see how can we actually

use them in a program.

Remember when we were going we were studying functions they had two parts , declaration and definition i.e for the following function

void Alpha ( )

12345678910111213141516171819202122

#include <iostream>usingusing namespacenamespace std ;voidvoid add ( ){intint c = 6 + 7 ;coutcout << c ;}voidvoid multiply ( ){intint c = 6 * 7 ;coutcout << c ;}voidvoid alpha ( ) {coutcout << " hi " ;}voidvoid main ( ) {add ( ) ;multiply ( ) ;alpha ( ) ;}

12345678910111213141516171819202122232425

#include <iostream>usingusing namespacenamespace std ; voidvoid main ( ) {add ( ) ;multiply ( ) ;alpha ( ) ; } voidvoid alpha ( ) {coutcout << " hi " ; } voidvoid multiply ( ) { intint c = 6 * 7 ; coutcout << c ; } voidvoid add ( ) { intint c = 6 + 7 ; coutcout << c ; }

Page 107: Cpp

{

cout << x ;

}

void alpha ( int x ) is what we declaration of the function and the rest is its definition.

Using forward declaration.To enable forward declaration in a program we simply just write the declaration of the function before the main ( ) , if we do this we can then write the

function even after it is called , the compiler wont show any error.

Lets apply this and correct the program which Dhruv wrote wrong.

Now when we run this program though when a call to the function say add ( ) is made , because we gave the declaration before main ( ) compiler knows

about the function what it looks like also it has to look for this function in the later statements.

Forward declarations for functions with parameters.If the function multiply in above example had parameters and its declaration would have been like this.

Note – When write the forward declaration for a function with parameters we only write the data type of the parameters not their

name i.e for the above example the forward declaration would have been like this.

Here we only wrote the data type not the actual name in parameters.but while writing the complete function we would not do this.here

is a complete example.

Another important useIf i have written two function alpha and beta , the function alpha is required to call function beta to do some calculation and similarly function beta needs

to some calculation so it call function alpha but how will this happen since we studied that compilation is done sequentially this always cause an error

1234567891011121314151617181920212223242526272829

include <iostream> usingusing namespacenamespace std ; voidvoid add ( ) ; voidvoid multiply ( ) ;voidvoid alpha ( ) ; voidvoid main ( ) { add ( ) ; multiply ( ) ; alpha ( ) ; } voidvoid alpha ( ) { coutcout << " hi " ;} voidvoid multiply ( ) { intint c = 6 * 7 ; coutcout << c ; } voidvoid add ( ) { intint d = 6 + 7 ; coutcout << d ; }

1 voidvoid multiply (intint a , intint b )

1 voidvoid multiply (intint, intint)

123456789101112131415

include <iostream> usingusing namespacenamespace std ; voidvoid multiply (intint , intint ) ; voidvoid main ( ) { multiply (5,6) ; } voidvoid multiply (intint a , intint b) { intint c = a * b ; coutcout << c ; }

Page 108: Cpp

Void – C++ tutorial Local Variables – C++ Tutorial

hence forward declarations are useful in this case too.

C++ tutorialSharing is caring

UDIT PANDOH

LEAVE A REPLY

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

Name *

Email *

Website

Comment

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite><code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

Post Comment

Notify me of follow-up comments by email.

Notify me of new posts by email.

ARCHIVES

June 2015

May 2015

April 2015

March 2015

February 2015

Search...

Page 110: Cpp

ALPHACPP.COM

Local Variables – C++ Tutorial

May 1, 2015 Aaryan Kapoor

The scope means the place where the variable is accessible while duration refers to time for which the variable exists. These might seem similar but are a

little different.

Variables defined inside a block are called local variables.

Local variables are created when the block (they are part of) is entered, and destroyed when the block (they are part of) is exited. So, local variables

have block/ local scope. They are visible only within the block that they are defined in and so have the duration of the block (or exists only for the time

the block exists)

Consider this simple example:

Output:

So, the first output is as per expectations (from a1). Then, the variable a (a2) is again declared, but there will be no error as a2 is local to the block

whereas a1 acts similarly to a global variable (about which you will learn in next C++ tutorial) for a2. As preference is given to local variables, second

output is 2 (a2). As the block is exited, a2 is destroyed in the memory and a would only refer to a1 and so the final output.

Same rules apply for nested blocks and can be checked similarly using the above program and adding more and more nested list.

The same program with a small change works differently.

1234567891011121314151617181920212223242526272829

#include<iostream> voidvoid main() { usingusing namespacenamespace std; intint a=1; //will call it a1 in explanation coutcout<< “a= ”<<a<<endl; { intint a=2; //will call it a2 in explanation /*you might expect an error here as there are multiple declarations*/ coutcout<< “a= ”<<a<<endl; //local variable is given preference } coutcout<< “a= ”<<a; }

12345

a= 1 a= 2 a= 1

1234567891011121314

#include<iostream> voidvoid main() { usingusing namespacenamespace std; intint a=1; //variable a is declared coutcout<< “a= ”<<a<<endl; {

Page 111: Cpp

Here, the a declared initially acts as a global variable for the block. So, no new variable is declared in the memory. Also, the change of value is observed

even after the block ends.

Similarly, as each function has its own block, variables in one function cannot be seen from another function:

First of all a (a2) is declared and initialized as 2. Then, the function ‘func’ is called, which declares a variable named a (a1) but it is stored in a different

memory location. Variable a2 is local to main, while, a1 is local to func. So, when we output a in func 2 is displayed, and when we do it in main, 1 is

displayed.

This allows us to have same names for variables in different functions without showing any errors.

Eg:

15161718192021222324252627

a=2; //notice the change //value of the above a is changed coutcout<< “a= ”<<a<<endl; } coutcout<< “a= ”<<a; //changed value of a is displayed. }

1234567

Output: a= 1 a= 2 a= 2

1234567891011121314151617181920212223

Eg: voidvoid func() { intint a=1; //will call it a1 in explanation coutcout<< “a= ”<<a<<endl; } voidvoid main() { intint a=2; //will call it a2 in explanation func(); coutcout<< “a= ”<<a<<endl; }

12345

Output: a= 1 a= 2

1234567891011121314151617181920

#include<iostream> usingusing namespacenamespace std; intint add(intint num1, intint num2) { returnreturn num1+num2; } intint multiply(intint num1, intint num2) { returnreturn num1*num2; }

Page 112: Cpp

Here, the variables num1 and num2 are declared multiple times but since they are declared in different blocks and so are local to their respective blocks

and have no relation, whatsoever, with each other.

Also, here we have used the if-else if statement about which you learn later. It is sufficient to know that this checks whether a condition is true (using

relational operators) and if it is true, then it goes to its block of instructions, otherwise it, simply, skips them. So, as these loops have their own blocks,

they can have their local variables, like sum and product in the above example.

Note: Repetition of variable names, though allowed, should be avoided to avoid unexpected errors.

Variable should be declared in the least possible scope. This has multiple benefits, like reducing the complexity of the program by reducing the number of

active variables. Also, it makes the code easier to understand.

So, this also means that you should avoid the use of global variables as much as possible.

C++ tutorialSharing is caring

AARYAN KAPOOR

LEAVE A REPLY

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

Name *

Email *

212223242526272829303132333435363738394041424344454647484950515253545556575859606162

voidvoid main() { intint num1, num2, ch; coutcout<< “Enter two numbers: ”; cin>>num1>>num2; coutcout<< “Enter your choice: 1-Add, 2-Multiply”<<endl; cin>>ch; ifif(ch==1) { intint sum= add(num1, num2); coutcout<< “Sum = ”<<sum; } elseelse ifif(ch==2) { intint product = product(num1, num2); coutcout<< “Product= ”<<product; } elseelse {coutcout<< “Wrong choice”; } }

Page 113: Cpp

Forward declarat ions – C++ tutorial Global Variables – C++ tutorial

Website

Comment

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite><code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

Post Comment

Notify me of follow-up comments by email.

Notify me of new posts by email.

ARCHIVES

June 2015

May 2015

April 2015

March 2015

February 2015

January 2015

April 2013

META

Register

Log in

AlphaCpp.com All rights reserved. Theme by Colorlib Powered by WordPress

Search...

Page 114: Cpp

ALPHACPP.COM

Global Variables – C++ tutorial

May 2, 2015 Aaryan Kapoor

Now we know that Local variables have local/block scope. They are created when the block is entered and destroyed when the block is exited.

In this C++ tutorial we will learn about the variables declared outside all blocks, called global variables. Global variables have global scope which means

they can be used until the end of the file in which they are declared. Global variables are created when the program starts and are destroyed when it

ends i.e. global variables exist for its complete scope.

Defining global variables It is best to declare the global variables above all the codes to avoid any error. Rest, you define them similar to local variables.

Eg:

Output:

1

3

2

2

5

4

Local variables with the same name as a global variable are given preference in the block of the local variable. This is where global scope operator (::)

comes to the rescue. The use of this automatically means you are referring to the global counterpart.

Output:

Local variable: 2

Global variable: 1

1234567891011121314151617181920212223

#include<iostream> intint glob_a = 1;const glob_b = 2;intint functionfunction(){glob_a=3;returnreturn glob_b;}intint main(){UsingUsing namespacenamespace std;coutcout<<glob_a<<endl;intint x=functionfunction();coutcout<<glob_a<<endl;coutcout<<x<<endl;glob_a=4; x=5;coutcout<<glob_b<<endl;coutcout<<x<<endl;coutcout<<glob_a<<endl;returnreturn 0;}

1234567891011

#include <iostream> intint varvar=1;intint main(){usingusing namespacenamespace std;intint varvar= 2; // preferred over the global variable varcoutcout << "Local variable: " << varvar <<endl;coutcout << "Global variable: " << ::varvar <<endl;returnreturn 0;}

Page 115: Cpp

However, you should avoid naming the local and global variables with the same name as this might cause some unexpected errors.

Global symbolic constantsEarlier we introduced the concept of symbolic constants, and defined them like this:

Here, name is the name given to the constant value. What it actually does is that, it simply replaces the name of the constant with the constant from

compiling the program.

Eg:

While this seems simple but it has it is its own problems.We can avoid these problems by using constant global variables.

Now the symbolic constants will get initialized and can be used in all the functions without defining them again and again.

NOTE: It is tempting to use the global variables but it comes with its own set of cons, which we will discuss inlater tutorials

C++ tutorialSharing is caring

AARYAN KAPOOR

1 #define name constant

12

#define Pi 3.1415floatfloat area = Pi * r * r;

12

const floatfloat pi = 3.1415, G = 6.67e-11, g = 9.8;const longlong longlong intint c= 3e8;

1234567891011121314151617181920212223242526272829303132333435363738394041

#include<iostream> const floatfloat pi = 3.1415, G= 6.67e-11, g= 9.8;floatfloat vol (longlong intint r){floatfloat volume = (4 * pi * r * r) / 3;returnreturn volume;}floatfloat dens (floatfloat v, longlong intint m){floatfloat d = m / v;returnreturn d;}floatfloat acc (longlong intint r, longlong intint m){floatfloat g_app = (G * m) / (r * r);returnreturn g_app;}floatfloat rel_acc (intint g_app){floatfloat rel_g = g_app / g;returnreturn rel_g;}intint main(){usingusing namespacenamespace std;longlong intint rad, mass;floatfloat volume, density, accel, rel_accel;coutcout << “Enter the radius of the newnew planet (inin metres): ”<<endl;cin >> rad;coutcout << “Enter the mass of the newnew planet (inin kilograms): ”<<endl;cin >> mass;volume = vol (rad);density = dens (volume, mass);coutcout << “The density of the planet isis: ”<<density<<endl;accel = acc(rad, mass);coutcout << “ The acceleration due toto gravitation isis: ”<<accel<<endl;rel_accel = (accel);coutcout << “ Accelaration due toto gravity isis ”<< rel_accel <<“ times that on Earth”;returnreturn 0;}

Page 116: Cpp

Local Variables – C++ Tutorial More on global Variables

LEAVE A REPLY

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

Name *

Email *

Website

Comment

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite><code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

Post Comment

Notify me of follow-up comments by email.

Notify me of new posts by email.

ARCHIVES

June 2015

May 2015

April 2015

March 2015

February 2015

January 2015

April 2013

META

Register

Log in

Search...

Page 117: Cpp

AlphaCpp.com All rights reserved. Theme by Colorlib Powered by WordPress

Page 118: Cpp

ALPHACPP.COM

More on global Variables

May 3, 2015 Aaryan Kapoor

This C++ tutorial is basically about the problems we face by using global variables and thus why we should avoid their use, unless necessary.

As a new developer, you might find it easy to use global variables, as you don’t have to declare variables for different functions and link them as function

parameters etc.

Just one advice from our side: DON’T!

Mostly, we are talking about the non constant global variables, constant global variables are not as a mess as their non constant counterparts are. So,

whenever we say global variables in this tutorial, we would basically mean non constant global variables.

Why you must avoid global variables

The biggest issue with the global variables is that their value can be changed by any function. It gets difficult to track the value of the ‘same’ variable in

bigger programs. We will just use a simpler program so that we can explain it to you what is happening

Output:

Num= 0

Num= 1

Num= 2

Just like this program, when you link more and more functions, they might change the value of the variable before you want/know it and your program

showing run time errors (showing unexpected result) especially when you add loops or statements like the if statement.

eg:

12345678910111213141516171819202122

#include<iostream>intint num=0; usingusing namespacenamespace std;voidvoid main(){voidvoid make1();voidvoid make2();coutcout<<"Num= "<<num<<endl;make1;}voidvoid make1(){num=1;coutcout<<"Num= "<<num<<endl;make2;}voidvoid make2(){num=2;coutcout<<"Num= "<<num<<endl;}

1234567891011121314151617181920

#include<iostream> intint i=1;usingusing namespacenamespace std;voidvoid result(){ifif (i==1)coutcout<<"Success";elseelsecoutcout<<"Fail";}voidvoid change(){i=2;}voidvoid main(){change();result();}

Page 119: Cpp

Output:

Fail

In this program, it is clear that since value of the global variable can be changed so the program eventually ‘fail’ed.

So, local variables are much safer because other functions cannot change their values.

Another reason to avoid global variables is that it is difficult to track the use and changes made to/ from the variable. On the other hand, the role of local

variable is short and can easily be tracked.

Global variables make program less flexible and modular. Also, the program involving global variables tends to be less reusable.

Should you ever use global variables?

In most cases you can avoid the use of global variables and use other alternatives. But in some cases, global variables tend to perform equal (or rarely,

better) than other alternative ways.

Eg: your program requires a database of some sorts, like names, numbers etc. It is best to define them globally to use them and let them remain non

constant, if you have to change it during program run and otherwise let them remain as it is.

Still you want to use them? Go on!

A few pieces of advice if you really want to go ahead with global variables.

First of all (always, when dealing with multiple files, unless required otherwise) make the variable static, so that it can only be accessed from the file it is

declared in.

Next, if your function requires the global variable, pass it as a parameter, this makes the function more modular and reusable with other variables, if need

maybe.

Lastly, are you sure you want to go ahead we them? If you are, go ahead but be very careful and clearly see step by step what your program is doing.

Sharing is caring

AARYAN KAPOOR

LEAVE A REPLY

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

Name *

Email *

Website

Comment

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite><code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

Post Comment

Page 120: Cpp

Global Variables – C++ tutorial Stat ic Variables

Notify me of follow-up comments by email.

Notify me of new posts by email.

ARCHIVES

June 2015

May 2015

April 2015

March 2015

February 2015

January 2015

April 2013

META

Register

Log in

AlphaCpp.com All rights reserved. Theme by Colorlib Powered by WordPress

Search...

Page 121: Cpp

ALPHACPP.COM

Static Variables

May 4, 2015 Aaryan Kapoor

The static keyword is a very useful yet confusing keyword. What it basically does is very simple, it allows the variable to stay in the memory and but at

the same time, remain inaccessible. Confused? Check out these two examples (with their outputs) :

1)

Output:

1

2

3

1

2

3

2)

Output:

1

2

3

3

4

5

Let see what is happening. In the first example, the variables num and i are declared inside the function count and thus have local scope. So, when the

function is first called, they are created and initialized as 1. In the for loop, num and i are incremented so as to print 1, 2 and 3, after which the function

shifts command back to the for loop, destroying num and i from the memory. When the function is again called, it creates new variables by the name of

num and i and are again initialized as 1 and then the same procedure is followed.

In the second example, the variables num and i are declared inside the function but num is declared to be a static variable, so it does not get destroyed

even on exiting the loop. When the function count is called, it creates two variables by the name of num and i. Both are initialized as 1. Now, in the for

123456789101112

voidvoid count (){intint num=1, i=1;forfor(; i<3; i++, num++)coutcout<<num<<endl;} //num is destroyed//i is destroyedvoidvoid main(){count();count();}

12345678910111213

voidvoid count (){static intint num=1; //these lines are executed only onceintint i=1;forfor(; i<3; i++, num++)coutcout<<num<<endl;} //num becomes inaccessible but is still in memory//i is destroyed voidvoid main(){count();count();}

Page 122: Cpp

More on global Variables If and Else If – C++ tutorial

loop num and i are incremented, so as to print 1, 2 and 3. Then for loop is exited, destroying i but not num. The variable num stays in the memory, but

cannot be accessed outside for loop, as it is declared inside the for loop. Next time the function is called, the static declaration statement is skipped, i is

created and initialized as 1. So, now num is 3 and i is 1 when for loop is started. This leads to printing of 3, 4 and 5.

Simply, this is how a static variable works.

Static variables provide the best of global and local variables. Just like global variables, they remain in memory till the end of program and just like local

variables, they cannot be edited by other functions.

Static global variables

You might be thinking what purpose do static keyword play in case of global variables, they remain in the memory anyway? In case of the programs we

have done till now, you are right. But actually it does serve a purpose. As you may or may not know, files can be related (called from one another) (to be

taught in future C++ tutorial).

You just need to know now that by default global variables can be used in other files. To avoid this, you can declare it as static. Static variables, as you

might know by now are inaccessible outside the place they are declared. So, static global variables have file scope only.

Sharing is caring

AARYAN KAPOOR

LEAVE A REPLY

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

Name *

Email *

Website

Comment

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite><code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

Post Comment

Notify me of follow-up comments by email.

Notify me of new posts by email.

1 intint multiple=0; //accessible in all files

1 static intint single=0; //accessible in only the file it is declared

Page 124: Cpp

ALPHACPP.COM

If and Else If – C++ tutorial

May 5, 2015 Aaryan Kapoor

In this C++ tutorial, we will learn about the one of the selection statements, namely if statement.

My friend Alex goes out every Sunday morning for a nice walk, lets say he can make a robot do the same job, if it starts raining outside he would take

an umbrella with him, but robot does not posses a sense of his own so we would have to program it for the condition but since it is not going to rain

always how do you do it ? Well we would program the robot to take the umbrella only if it is raining outside , yes you gave a certain condition.

Similarly in C++ if we are making a calculator program, what if we let the user decide if he wants to add two numbers or subtract them ? we tell the user

to input the symbol of the operation , and then if he clicks ‘+’ symbol we add numbers if he click ‘-‘ we subtract the two numbers.

An if statement tests a particular condition (or multiple conditions). If the condition it true, it starts its own block of (or single) statement(s) and if not it

simply skips these statement(s).

Syntax

where test expression is a relational operator or a combination of relational and logical operators (you might revise them from our C++ tutorial, as their

knowledge is important to learn if)

NOTE : The statements inside the brackets ‘ { } ‘ comprise the body of if statements.

NOTE : You must be clear that there is no semicolon (;) after the test expression and/or its bracket.

Eg:

Here, the statement runs, no matter, a is 1 or not. This is because it considers a blank statement (called null statement) as the statement of if and simply

continues after that to the statement.

Null statements are nothing but a semicolon (;). It does nothing. These do find use about which you will find use in the loops (which you will learn in later

C++ tutorial).

Eg:

123456789101112

ifif(test expression){statement; //for single statement}//OR ifif(test expression) { statements; //for multiple statements}

1234

ifif(a==1);{statement;}

12345678910111213141516171819

#include<iostream> voidvoid main() { intint a, b, c, max; coutcout<< “Enter three numbers: ”; cin>>a>>b>>c; max=a; ifif(max<b) max=b; ifif(max<c)

Page 125: Cpp

This program allows the user to find the greatest integers out of the given three set of integers.

Let us assume the given values to be 5, 4 and 7. Initially, max is assigned the value of a i.e. 5. Then the computer checks whether max (5) is less than b

(4) which is not true, so the associated statement is not executed and max is still 5. Now, the computer checks whether max (5) is lesser than c (7)

which is true. So, the next statement is executed, assigning the value of c (7) to max. Finally, the output displayed against max will be 7.

You might already have seen the use of the if statement in our C++ tutorial about local variables.

See another example of if statement.

Eg:

This simple program runs on the basics of if statement, relational & logical operators and the knowledge that the characters are stored as integers in

memory. Let us suppose that the user enters 3. Then, the computer first checks for the first three if statements (none of which are true) and so the

statements associated with them are not executed. Then, the computer checks whether the entered value (‘3’) lies between ‘0’ and ‘9’ which is true, so

the cout statement associated with this if is executed.

Output in this case:

But what happens when a space is entered by the user, the computer after displaying the statement associated with first if statement goes on to check

whether any of the rest of the if statements is true. This is not (and cannot be) the case. So, it wastes a lot of CPU time and consumes extra memory.

This can be avoided the else if statement.

But first, what is an else statement?

In simple words, it is the opposite of if. So, if the statement is not true, then the statement(s) associated with else is/are executed. It is always preceded

by an if statement and works as a negation of that if statement.

Eg:

2021222324

max=c; coutcout<< “The greatest numbers out of ”<<a<< “, ”<<b<< “, ”<<c<< “ isis ”<<max;}

12345678910111213141516171819202122232425262728

voidvoid main() { UsingUsing namespacenamespace std; charchar ch; coutcout<< “Enter a character: ”<<endl; cin>>ch; ifif(ch== ‘ ’) coutcout<< “You have entered space”; ifif(ch>= ‘a’ && ch<= ‘z’) coutcout<< “You have entered a lowercase letter”; ifif(ch>= ‘A’ && ch<= ‘Z’) coutcout<< “You have entered an uppercase letter”; ifif(ch>= ‘0’ && ch<= ‘9’) coutcout<< “You have entered a digit”;}

12345

Enter a character: 3 You have entered a digit

12345678910111213

ifif (test expression) { Statement(s)1; } elseelse { Statement(s)2;

Page 126: Cpp

The computer only goes to the else statement only when the if statement is not executed (due to failed test expression).

Nested if

Nesting of if can be done in

a) the if part

b) the else part

c) both parts

NOTE – In case of nesting of if’s, the else statements pairs with the last if in the same block. So, to avoid unnecessary it is best to add

nested if’s in blocks.

Here, you want the computer to know the number of three/ four digits entered. So, you want the computer to check whether the number is less than

1000. If yes, then it must proceed to check if the number is greater than 99 and if not it must check whether the number is less than 10000 and

increment accordingly. So, we want the compiler to compile the code as:

But what is happening is quite different. The compiler translates it as

So, the compiler reads the else as a part of the initial if. So, if the users enters a value, such as, 1234, it would completely skip the code and move

forwards. As said earlier, to avoid this we must use brackets as:

1415

}

12345678910111213

Eg: ifif (num<1000) ifif(num>99) threedig++; elseelse ifif(num<10000) fourdig++;

12345678910111213141516171819

ifif (num<1000) { ifif(num>99) threedig++; } elseelse { ifif(num<10000) fourdig++; }

1234567891011121314151617

ifif (num<1000) { ifif(num>99) threedig++; elseelse ifif(num<10000) fourdig++; }

123456

ifif (num<1000) { ifif(num>99)

Page 127: Cpp

If – else if ladderAlso, as you might have noticed something similar to else if in the previous program, that we had mentioned earlier. It is nothing but if nested in an else

part. So, the second program becomes.

Now, whenever one of the conditions is met by the entered value, the computer would display corresponding output and stop checking in other else if

statements.

This if- else if ladder is very useful as it saves CPU time and memory and also quickens things up.

Question – what is the difference between if use multiple if statements or if and else if statements ?

Solution – If there are multiple if statements is a ladder compiler checks for all of them , even if some of them turn out to be true, whereas in an if – else

if statements , as soon as the compiler finds one of the statements turning true it stops checking other condition and skips them.

C++ tutorialSharing is caring

AARYAN KAPOOR

LEAVE A REPLY

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

Name *

789101112131415161718192021222324252627

{ threedig++; } } elseelse { ifif(num<10000) { fourdig++; } }

12345678910111213141516171819202122232425262728

voidvoid main() { UsingUsing namespacenamespace std; charchar ch; coutcout<< “Enter a character: ”<<endl; cin>>ch; ifif(ch== ‘ ’) coutcout<< “You have entered space”; elseelse ifif(ch>= ‘a’ && ch<= ‘z’) coutcout<< “You have entered a lowercase letter”; elseelse ifif(ch>= ‘A’ && ch<= ‘Z’) elseelse coutcout<< “You have entered an uppercase letter”; elseelse ifif(ch>= ‘0’ && ch<= ‘9’) coutcout<< “You have entered a digit”;}

Page 128: Cpp

Stat ic Variables The Sw itch Statement – C++ Tutorial

Email *

Website

Comment

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite><code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

Post Comment

Notify me of follow-up comments by email.

Notify me of new posts by email.

ARCHIVES

June 2015

May 2015

April 2015

March 2015

February 2015

January 2015

April 2013

META

Register

Log in

AlphaCpp.com All rights reserved. Theme by Colorlib Powered by WordPress

Search...

Page 129: Cpp

ALPHACPP.COM

The Switch Statement – C++ Tutorial

May 6, 2015 Udit Pandoh

C++ like the if statement also has a selection statement known as switch , the statements tests the value of the expression provided to it with a list of

integer or character constants, as soon as a match is found , the statements corresponding to the constant is executed.

Syntax

when a expression is provided its value is compared with the constants in each case as soon as a match is found the statement in that particular case is

executed, break is used after each case to get out of the switch , default statement is executed when no match is found it optional to provide a default

statement but is is highly recommended to ensure that program runs even if a wrong expression is provided,

lets consider an example for our understanding.

if we give the input as 2 the word red is shown on the screen because that was what we told the compiler to give as the output if the case i.e the

expression entered is 2 , if we gave an expression rather than 2 , 4 or 6 , the default statement would have executed.

NOTE – If the statement of a case does not include a break statement then the control continues to the next case statements until a break is

encountered or the the switch case is terminated, this is termed as a fall through

Difference between if-else and switch

cons-When compared with the if-else , switch is similar in the basic objective , but there is a lot of difference between the both , while switch compares

expression, if can check for logical expressions, the switch works basically on the given expression while if can be used for totally unrelated complex

expressions,the switch can only handle case labels of type integer while there is no type of such limitation on if statements, switch case label must be

constant therefore unlike if statements two variables cannot be compared.

12345678910111213141516

switchswitch ( expression ) { casecase ( some constant 1 ) : statement forfor constant 1 ;breakbreak ; casecase ( some constant 2 ) :statement forfor constant 2 ;breakbreak ; defaultdefault :statement forfor defaultdefault;breakbreak; }

12345678910111213141516171819202122232425

intint main( ){coutcout << " Enter number of the ball " ;intint ball ;cin >> ball ;switchswitch (ball){casecase 2 : coutcout << " red " ;breakbreak ; casecase 4 : coutcout << " yellow " ;breakbreak ; casecase 6 : coutcout << " blue " ;breakbreak ; defaultdefault :coutcout << " wrong numbers 2 , 4 or 6 only. "breakbreak;}returnreturn 0 ;}

Page 130: Cpp

If and Else If – C++ tutorial Goto Statement – C++ Tutorial

pro-Though it has many limitations if switch case is more efficient when compared to the if-else statement given the task of the program can be achieved

using switch.

C++ tutorialSharing is caring

UDIT PANDOH

LEAVE A REPLY

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

Name *

Email *

Website

Comment

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite><code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

Post Comment

Notify me of follow-up comments by email.

Notify me of new posts by email.

ARCHIVES

June 2015

May 2015

April 2015

March 2015

Search...

Page 132: Cpp

ALPHACPP.COM

Goto Statement – C++ Tutorial

May 7, 2015 Udit Pandoh

See this statement – Hey if you cant find the laptop in my room , go-to the other room and check there for it.

What was the purpose of the word goto in the above statement ? It was used to make the person go somewhere else

Similarly Goto statements are used to transfer the program control i.e it causes the C.P.U to jump somewhere else in the code. we use something called

as a label to direct the program to the target destination.

Syntax

Note – A label is identified with the use of the ‘ : ‘ after its name.

In the above example the program would compile normally up-to statement 5 , but as soon as it encounters the goto statement

instead of executing statement 6 it will start executing the statement after label that is statement 1

lets consider an example.

Points to remember1 – The label and the goto statement must be present inside the same function i.e they have a function scope.

2 – You can jump forward using goto statements too, given there is no variable definition in-between , consider this example

Note – All being said there is a way you can still skip forward with variable definition in between, this can be done if the variable definition is occurring

inside blocks, in that case the whole block is skipped, here is an example for you

123456789

//Syntax nameofthelabel :statement 1 ...statement 5gotogoto NameOfTheLabel ;

12345678910111213141516

#include <iostream>usingusing namespacenamespace std;intint main(){usingusing namespacenamespace std;again : // label ;coutcout << "enter a number between 1 and 10"; intint number ;cin >> number ; ifif ((number > 10 )||( number < 1)) {gotogoto again; //this is the goto statement }returnreturn 0 ;}

1234567891011121314

{.gotogoto alpha ; // correct..alpha: gotogoto beta:intint x = 5 ;beta: // incorrect variable definition is coming in between }

1 .

Page 133: Cpp

3- A backward jump over a variable definition is valid.

4- A label cannot immediately precede a closing right brace i.e the following is wrong

to fix we insert a null statement , therefore only in this case we use semicolon ‘;’ after the label.the correct version of the above example would be

5 When you will start practice programming, you will notice that loops can be used to do what you are doing using goto statements and that is a better

option, since goto statements jump forward and backward in a code it can cause a lot of confusion which often termed as a spaghetti code. therefore

try to avoid goto statements until necessary

C++ tutorialSharing is caring

UDIT PANDOH

LEAVE A REPLY

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

Name *

Email *

Website

Comment

234567891011

gotogoto beta:..{intint x = 5 ;..}beta: // correct }

1234567

{gotogoto alpha ;...alpha :} //wrong

123456789

{gotogoto alpha ;...alpha : ; } //right

Page 134: Cpp

The Sw itch Statement – C++ Tutorial Introduct ion to loops

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite><code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

Post Comment

Notify me of follow-up comments by email.

Notify me of new posts by email.

ARCHIVES

June 2015

May 2015

April 2015

March 2015

February 2015

January 2015

April 2013

META

Register

Log in

AlphaCpp.com All rights reserved. Theme by Colorlib Powered by WordPress

Search...

Page 135: Cpp

ALPHACPP.COM

Introduction to loops

May 8, 2015 Udit Pandoh

From the next topic we are going to start with loops , loops are very important to c++ , loops helps us to run a set of statements again and again with

no change or a small change in the statements.

There are three basic loops

1 – For loop2 – While loop3 – Do-While loopAll these three loops will be discussed in this chapter, but before moving on you must understand the basics of a loop, a loop is used to check for a

certain condition, while the condition is true the loop works.

Here are some examples of programs for which loops be useful.

1) If we had to show a program counting form 100 to 0 , how would you do that ? we can use a loop starting a variable with value 100 start the loop

and provide a condition to end it when a variable reaches 0.

2)Check which number is largest form a given set of variables. Instead of doing the comparison one by one we can use a loop to do it.

3)If we are to display something again again until a certain key is pressed a loop can be used.

There are endless examples to explain the importance of loops whether it be with arrays , pointers or classes you will learn about all of these in the later

examples, after reaching each of the loop remember to go the coding station and practice some codes.

Sharing is caring

UDIT PANDOH

LEAVE A REPLY

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

Name *

Email *

Website

Comment

Page 136: Cpp

Goto Statement – C++ Tutorial While Loop – C++ Tutorials

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite><code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

Post Comment

Notify me of follow-up comments by email.

Notify me of new posts by email.

ARCHIVES

June 2015

May 2015

April 2015

March 2015

February 2015

January 2015

April 2013

META

Register

Log in

AlphaCpp.com All rights reserved. Theme by Colorlib Powered by WordPress

Search...

Page 137: Cpp

ALPHACPP.COM

While Loop – C++ Tutorials

May 9, 2015 Aaryan Kapoor

A while loop works ‘while’ the condition/s is/are true.

Syntax

Here, if the test_expression (using relational operators) is true, then the statement is executed otherwise not, just like if. But, unlike if, the control just

does not simply go outside the block and rather to the top of the block (to the test_expression) and this loop goes on as long as the test_expression is

true.

Here comes the biggest benefit of the while loop, it can run as long as the user wants or as long as the programmer wants or a mix of both. In case of

the For loop (about which you will learn in future C++ tutorial), the user cannot decide (alone) if s/he wants to continue the loop or not and in case of

Do-while loop (about which you will learn in next C++ tutorial), the user has to enter the loop at least once, even if s/he does not want to.

Let us look at one basic example of while loop and see how it works (This is an example of programmer deciding the number of times while loop is

executed).

Eg:

Firstly, i is declared and initialized as 1 and then it is checked whether it is lesser than or equal to 10, which is true, so it executes the statements i.e. cout

and increment in i. It again go to the test expression which again is true, so the statements are executed, this loop goes on till the test expression is true

and stops once i=11. So, the output will be:

1

2

3

4

5

6

7

8

9

10

Let us take another example where the user decides the number of times while loop is executed.

In this example as long as the user enters y to the last question, the loop continues, otherwise the loop is exited.

In the next example it is mixture of user and programmer’s choice.

12

whilewhile (test_expression)statement;

123456

intint i=1;whilewhile(i<=10){coutcout<<i <<endl;i++;}

1234567

charchar ch= ‘y’;whilewhile(ch== ‘y’){statements;coutcout<< “DoDo you want toto continuecontinue (y/n): ”;cin>>ch}

Page 138: Cpp

In this example, user decides the value of num, while the programmer decides the number of times the loop works on the basis of this value of num.

Infinite loopIf the expression always evaluates to true, the while loop will go on forever. This generally happens when we forget to add an update statement.

Eg:

This is an infinite loop as the a will always remain 1 and thus will always satisfy the condition and enters the loop indefinitely.

The only way to exit an infinite loop is through return or break statement or the user killing the program.

An important point to note here (as in other loops/conditions) is that there is no semicolon after the while statement.

In this case, the condition is true (4 is not equal to 0), so it enters the while loop. The only statement in the while loop is a semicolon (;) or a null

statement. So, there is no change in value of num leading to infinite nature of loop.

Adding of semicolon, though mostly a mistake, but can be used by the programmer to pause the loop for some time. Eg: This can be used to make an

important message stay on the screen before it goes off. Such a loop is called a time loop.

Sharing is caring

AARYAN KAPOOR

LEAVE A REPLY

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

Name *

Email *

Website

Comment

12345678910

intint num;longlong fact=1;coutcout<< “Enter the number, whose factorial you want toto find: ”;cin>>num;whilewhile(num!=0){fact=*num;num--;}coutcout<<endl<<fact;

12345

intint a=1;whilewhile (a<=10){coutcout<<a<<endl;}

123456

intint num= 4;whilewhile (num!=0);{coutcout<<num<<endl;num--;}

12

longlong varvar=0;whilewhile (++varvar < 10000) ; //use of pre increment to avoid infinite loop

Page 139: Cpp

Introduct ion to loops Do-While Loop – C++ Tutorial

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite><code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

Post Comment

Notify me of follow-up comments by email.

Notify me of new posts by email.

ARCHIVES

June 2015

May 2015

April 2015

March 2015

February 2015

January 2015

April 2013

META

Register

Log in

AlphaCpp.com All rights reserved. Theme by Colorlib Powered by WordPress

Search...

Page 140: Cpp

ALPHACPP.COM

Do-While Loop – C++ Tutorial

May 10, 2015 Udit Pandoh

We have already studies about while loops, but you must have noticed something, if the given condition is false at the first place the loop is not executed

even once, but that is not what we want sometimes, in some cases we may want the loop to execute at least once.Where while loop checks the

condition and then executes the code inside the loop , the do-while loop first runs the code and then checks the condition.

Syntax

The most common use of do-while loo- is in menu selection routine, where the menu is flashed at least once, then depending on users response it is

either repeated or terminated.

Here the menu is displayed on the screen once and then depending on the users input , we decide what to do next.

While and do-while loops are very similar to each other if you know how to use one it is not difficult to understand the other.

Another important lesson you get from the above example is about the scope, why did not we keep the choice variable in the do statement ? the

answer is that do statement is contained inside a block ‘[ ]’ if we keep the choice variable there , it will have a block scope and hence it will be destroyed

as soon as the do statement ends, but we are using choice inside the while condition , so we declare the variable outside to overcome this problem. This

is what scope is all about understanding where are variables created and destroyed, this is the type of mistakes new programmers generally do and you

should be careful about it.

C++ tutorialSharing is caring

UDIT PANDOH

LEAVE A REPLY

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

Name *

12345

dodo{statement ;}whilewhile (condition);

123456789101112131415161718

#include <iostream>usingusing namespacenamespace std;intint main(){alpha:intint choice;dodo{coutcout << option 1 - start " ;cout << option 2 - load" ; cin >> choice ;}whilewhile ((choice != 1 ) && (choice != 2))gotogoto alpha ; returnreturn 0;}

Page 141: Cpp

While Loop – C++ Tutorials For Loop – C++ Tutorial

Email *

Website

Comment

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite><code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

Post Comment

Notify me of follow-up comments by email.

Notify me of new posts by email.

ARCHIVES

June 2015

May 2015

April 2015

March 2015

February 2015

January 2015

April 2013

META

Register

Log in

AlphaCpp.com All rights reserved. Theme by Colorlib Powered by WordPress

Search...

Page 142: Cpp

ALPHACPP.COM

For Loop – C++ Tutorial

May 12, 2015 Aaryan Kapoor

The for loop means a loop ‘for’ fixed number of time.

The for loop is one of the most important and most often used. It is used to loop a set of statements a fixed number of times, according to the

programmer or the user.

Syntax

As the names suggests, the initialize statement initializes variable(s) , the test expression tests whether those variables satisfy the test condition (using

relational operator), while the update expression updates the variables by increment/ decrements.

Let’s take a look at an example of a for loop:

Let us see how it works. Firstly, a variable by the name i is declared and initialized as 1. Next the test condition is checked, which comes out to be true.

Next it goes to the cout statement and not the update statement, this is important to understand that the update statement works after the loop

statement/s are executed. Now, it prints 1 and then goes to update statement and now i becomes 2. The loop begins again, but this time initializing step

does not run. So, it goes to the test expression which, yet again is true. So, it prints 2 and goes to update expression to change i to 3. This goes on till i

becomes 11 (which is not <= 10), when it goes out of the loop and goes on to execute the statements after that.

The output will be:

1

2

3

4

5

6

7

8

9

10

The above for loop in case of while loop looks like this.

Now you see how convenient for loop is in comparison to while loop, by doing these three steps (initialization, test and update) at one place.

Now, as it goes for other loops, never put a semicolon (;) just after the for statement.

Eg:

12

forfor(initialize; test; update)statement;

12

forfor(intint i=1; i<=10; i++)coutcout<< i<<endl;

123456

intint i=1;whilewhile(i<=10){coutcout<<i <<endl;i++;}

12

forfor(intint i=1; i<=10; i++);coutcout<<i<<endl;

Page 143: Cpp

Here, the output is:

11

Instead of the previous output for the same reason that the for loop only executes the semicolon

(or the null statement) and the cout statement is out of the loop and works only after the loop ends, which happens when i=11.

Variations in For LoopUsing user entered values for test expression

eg:

Multiple initialization and/or update expression

Omission of expression

Omission of initialization expression

Note: We must initialize the variable, otherwise it will store some garbage value and might never even enter the loop.

Omission of update expression

Note: we still need to write an updation expression (that too in the test expression), otherwise it will turn into an infinite loop as the condition once

satisfied will always remain so and it can never exit the loop.

Omission of initialization and update expression

Omission of test expression

Note: Whenever we omit the test expression it automatically turns into an infinite loop.

1234567

//program to find sum of user entered number of natural numbersintint i,sum=0, num;coutcout<< “Enter the number of terms whose sum you want toto find”<<endl;cin>>num;forfor(i=1; i<=num; i++)sum=+i;coutcout<< “Sum= ”<<sum;

1234567

intint i,sum, num;coutcout<< “Enter the number of terms whose sum you want toto find”<<endl;cin>>num;forfor(i=1, sum=0; i<=num; sum=+i, i++); //see the use of comma operator /*also notice that we have used the null statement to our benefit */coutcout<< “Sum= ”<<sum;

12345678

intint i =1,sum=0, num;coutcout<< “Enter the number of terms whose sum you want toto find”<<endl;cin>>num; forfor( ; i<=num; sum=+i, i++); /*notice that although we might have skipped the initialization expression but we still need to add a semicolon before we start the test expression */coutcout<< “Sum= ”<<sum;

123456789

intint i,sum, num;coutcout<< “Enter the number of terms whose sum you want toto find”<<endl;cin>>num;forfor(i=1, sum=0; i<=num; ){sum=+i;i++;}coutcout<< “Sum= ”<<sum;

123456789

intint i =1,sum=0, num;coutcout<< “Enter the number of terms whose sum you want toto find”<<endl;cin>>num; forfor( ; i<=num; ){sum=+i;i++;}coutcout<< “Sum= ”<<sum;

12

forfor (intint i = 1; ; i++)//this is an infinite loop

Page 144: Cpp

Do-While Loop – C++ Tutorial Break And Continue – C++ Tutorial

c++ tutorialsSharing is caring

AARYAN KAPOOR

LEAVE A REPLY

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

Name *

Email *

Website

Comment

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite><code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

Post Comment

Notify me of follow-up comments by email.

Notify me of new posts by email.

ARCHIVES

June 2015

May 2015

April 2015

March 2015

February 2015

January 2015

April 2013

Search...

Page 145: Cpp

META

Register

Log in

AlphaCpp.com All rights reserved. Theme by Colorlib Powered by WordPress

Page 146: Cpp

ALPHACPP.COM

Break And Continue – C++ Tutorial

May 13, 2015 Udit Pandoh

The break statement enables a program to skip over a part of the code, it terminates the smallest enclosing of any loop or switch statement, the

execution is immediately resumed from the point following the body of the terminated statement. Simply speaking break is used to exit the loop or

to finish a case in switch

Lets understand the working of a break statement first.

In the above case if the program encounters a certain condition ( given in if ) it breaks the loop immediately and instead of executing statement 2, it

starts to execute statement 3.

here the loop would execute a hundred times if user enters anything except 0 , but if at any point the user enters 0 the loop stops immediately and

“program over ” will be displayed on the screen.

Continuecontinue is another jump statement, like the break statement both serve the purpose of skipping a part of code, but the continue statement is

somewhat different from , instead of terminating the loop like the break, it forces the next iteration to take place, skipping any code in between

For the the while and do-while loops, the program passes control to the conditional tests whereas for the for loop the next iteration is done by first

updating the variable and then checking the test-values expression.

here the output will be

1

3

4

5

1234567891011

whilewhile (expression/condition){statement 1 ; ifif (some-condition)breakbreak; statement 2; }statement 3;

12345678910111213141516

intint main(){forfor (intint i = 0 ; i < 100 ; i++)coutcout <<icin >>count ;ifif ( count == 0)breakbreak ;elseelse{.further statements ; }coutcout <<"program over " ;returnreturn 0 ;}

1234567891011

intint main( ){forfor (intint i = 0 ; i < 6 ; i++ ){ifif (i == 2 )continuecontinue ; //brackets not used for if condition since only one statement is contained in it.elseelse coutcout << i <<endl ;}returnreturn 0 ;}

Page 147: Cpp

5

What did the continue do ? according to the loop when variable i acquired a value of two , the if statement directed it to the continue , which updated

the value of i to three and then made the loop start the next iteration.

Difference between break and continueLets apply break to the previous example, but this time we will use break instead of continue

here the output will be

1

What happened here was that where continue caused the next iteration the break caused the termination of the for loop immediately, hence stopping

any further output

C++ tutorial

Sharing is caring

UDIT PANDOH

LEAVE A REPLY

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

Name *

Email *

Website

Comment

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite><code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

Post Comment

Notify me of follow-up comments by email.

Notify me of new posts by email.

1234567891011

intint main( ){forfor (intint i = 0 ; i < 6 ; i++ ){ifif (i == 2 )breakbreak;elseelse coutcout << i <<endl ;}returnreturn 0 ;}

Page 149: Cpp

ALPHACPP.COM

Arrays – C++ Tutorial

May 14, 2015 Udit Pandoh

ArraysArrays are very helpful in a c++ program , like we store a variable in our program we use array to store a set of variables at the same time, given they

are all of the same type. Lets take a look at an example , suppose we are creating a program to create a data base for the weather report , and we

storing the temperature for seven days, as you know we will first need to create variables that can be used to store the values.

doesn’t that suck ? what if we could have done what we did above in a much simpler way ? And here comes the need for arrays, as discussed above we

use arrays to store a set of variables of same type (in the above example integer)at once. Lets take a look at how we declare an array.

First we declare the data type of the variables then we give a name to the array followed by the number of variable we want to .In example 1 we

declare 12 variables , all of type integer , in example two we are declaring 10 variable of type char.

Now that we have declared the variables the next thing is how to access the individual variables and initialize them, one thing you must know is that in an

array counting starts from 0 , so if you declare 10 variables, the first one will be given the position 0 and the 10th variable , position 9.

NOTE -The position of nth variable will be n – 1 in an array.Lets understand this with the help of an example

here a value of 1 is given the first variable in the array.

One should understand that though they are part of an array , we can treat them in operations and loops like a normal variable.

will give an output 10 as rollnumber[0] holds the value 1 and rollnumber[1] value 9.

Initializer listBut what is the fun we if we have to give the values to each variable one by one, another way of giving values to the variables in the array is at the time

of declaring the array only.

Lets say we are declaring an array for storing marks three students. we would do something like this

consider this.

1234567

intint day1;intint day2;intint day3;intint day4;intint day5;intint day6;intint day7;

123456

data-type name[size of the arrayarray] eg. intint weatherdata[12] ;charchar classclass[10] ;

123456

//first we declare an array that stores roll numbers of 10 students.intint rollnumber [10] ; //This declares 10 variables , now lets give a value of 5 to the variable 1.// This done by first writing name of the array followed by position of the variable.rollnumber [o] = 1 ;

123456

forfor egintint rollnumber [10] ;rollnumber [o] = 1 ;rollnumber [1] = 9 ; coutcout <<rollnumber [0] + rollnumber[1];

1 intint marks[3] = {80,67,90} ;

Page 150: Cpp

What happens if i declare an array but do not initialize all the variables ? Well any variable declared in an array which is not initialized has

a default value of 0.

Therefore in the above example int marks[4] and int marks[5] hold a value of 0.

doing this we give a value 80 to the first variable in the array and 90 to the third.this covers our basics lets go to the part two.

Omitted SizeIf we are initializing an array of elements using an initializer list, the compiler can figure out the size of the array for us.

Important

keep in mind that the size of an array cant vary it has to constant i.e the following is wrong.

but when initializing a variable you can do this

C++ tutorialsSharing is caring

UDIT PANDOH

LEAVE A REPLY

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

Name *

Email *

Website

Comment

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite><code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

Post Comment

1 intint marks[5] = {80,67,90} ;

1 intint marks[] = { 19, 21, 37, 46, 4 }; // here we declared an array of 5 elements.

12

intint size = 3;intint alpha[size] = {0,1,2} //wrong size needs to be constant

123

intint number = 0;intint alpha[3] = {0,1,2} // correct because number of variables are constant.alpha[number] = 6 ; //valid

Page 151: Cpp

Comma and condit ional operators – Cpp tutorial Guess the output – ++

Notify me of follow-up comments by email.

Notify me of new posts by email.

ARCHIVES

June 2015

May 2015

April 2015

March 2015

February 2015

January 2015

April 2013

META

Register

Log in

AlphaCpp.com All rights reserved. Theme by Colorlib Powered by WordPress

Search...

Page 152: Cpp

ALPHACPP.COM

Arrays and loops

May 24, 2015 Aaryan Kapoor

Arrays and loops, often, go hand in hand. Arrays allow you to store multiple variables of same type while loops allow you to input, output and manipulate

these variables with minimum effort/code.

We will simply do a few examples to understand this concept better.

1.

In this program, the user is asked to enter 10 digits using the for loop. Next, the value of each of these numbers is compared (using relational operators)

with the greatest number before them in the numbers, again, using for loop. Finally, the program outputs the greatest number out of the user entered

numbers.

2.

In this program, the computer firstly asks for the e(employee)code, salary and experience of the 1st employee and then the second and then finally the

3. Using the for loop with arrays allows us to do the same thing without writing the code three times. The same goes for the output.

3.

1234567891011

//finding the greatest integerintint ar[10], great=0;coutcout<<"Enter 10 numbers: ">>endl;forfor(intint i=0; i<10; i++)cin>>ar[i]; //takes input from ar[0] to ar[9]forfor(intint j=0; j<10; j++){ifif(ar[j]>great) //checks for all the values in arraysgreat= ar[j]; //stores the greatest value in the loop}coutcout<<"Greatest number: "<<great;

12345678910111213141516171819

//input and output data of three employeesintint ecode[3], salary[3], exp[3];forfor(intint i =0; i<3; i++){coutcout<<"Enter the data of "<<i+1<<" employee"<<endl;coutcout<<"Enter ecode: ";cin>>ecode[i];coutcout<<"Enter salary: ";cin>>salary[i];coutcout<<"Enter experience: ";cin>>exp[i]}forfor(intint j=0; j<3; j++){coutcout<<j+1<<" employee"<<endl;coutcout<<"Ecode: "<<ecode[j]<<endl;coutcout<<"Salary: "<<salary[j]<<endl;coutcout<<"Experience: "<<exp[j]<<endl;}

12345678910111213141516171819202122

//Makes the user enter a sentence using multidimensional array.charchar ch[15][20];intint i=0, j=0;coutcout<<"Enter a sentence (ending by full stop/period)"<<endl;dodo{ dodo { cin>>ch[i][j];j++; }whilewhile(ch[i][j-1]!=32 || ch[i][j-1]!=46); //32 is ASCII code for spacei++;}whilewhile(ch[i-1][j-1]!=46); //ASCII code for full stop/ period//for printing the sentencei=0;j=0;coutcout<<"You entered: ";dodo{ dodo { coutcout<<" "<<ch[i][j];

Page 153: Cpp

Float and Double History of java

This program allows the user to enter a sentence of any length (here, we have limited it to 15 but you can use as much as you like) with words of any

length (again we have limited them to 20 but you can increase them to as much as you like). To understand this, you must have an idea about the

multidimensional arrays. We have used the do-while loop here, so that it enters both the loops without us initializing the test conditions. You could still use

the while loop but do not forget to initialize the ch[0][0] to anything but space or full stop/ period. The inner do-while loop goes on till the user enters a

space (marking end of the word) and this increases the i (used as word number indicator here). When the user finally enters the full stop/ period both

the loops are exited. The output statement works in the same way.

Sharing is caring

AARYAN KAPOOR

LEAVE A REPLY

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

Name *

Email *

Website

Comment

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite><code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

Post Comment

Notify me of follow-up comments by email.

Notify me of new posts by email.

23242526

j++; }whilewhile(ch[i][j-1]!=32 || ch[i][j-1] = 46); i++;}whilewhile(ch[i-1][j-1]!=46);

ARCHIVES

June 2015

Search...

Page 155: Cpp

ALPHACPP.COM

Enumerated Type – C++ Tutorial

May 29, 2015 Udit Pandoh

Let’s consider that I am making a program based on astrology, in the program there comes a point at which I am using an if statement like this.

Introduction.

Here I have told the user that the integer 1 stands for ‘Aquarius’, what if I could do the same and tell this to the compiler too? Wouldn’t that be

awesome!

Then I could have written the above program like this

Well, this is exactly how enumerated type helps a programmer. We create a database for the data, then an integer is assigned to each symbolic constant

in the database also called an enumerator.

Syntax

let’s consider an example for let’s say the mood of a person.

NOTE – Declaring an enumeration does not allocate any memory. When a variable of the enumerated type is defined (such as variable Udit in the

example above), memory is allocated for that variable at that time, aslo each enumerator is separated by a comma, and the entire enumeration is ended

with a semicolon.

Here we have created a database for mood, which comprises of three enumerators. You can compare this to an integer data type, like an integer

comprises of all non-decimal positive and negative numbers, the enum mood comprises of happy, sad and lonely.

Now when we declare a data type like, say integer we also give a name to the variable and then give it a value

similarly, we will say

Giving integral values to each enumerator

1234567

...intint starsign ;coutcout << " 1 is for aquarius " ;cin >> starsign ; ifif ( starsign == 1 )coutcout << aquarius ;...

12345678

...intint starsign ;coutcout << " 1 is for aquarius " ;cin >> starsign ; ifif ( starsign == aquarius )coutcout << aquarius ;...

12345

enumenum nameofdatabase{enumerators eacheach separated with a comma} ;nameofdatabase nameofvariable ;

1234567

enumenum mood{happy ,sad ,lonely // for maximum compatibility, the last enumerator should not have a comma} ;mood Udit = happy ;

1 intint something = 1 ;

1 mood udit = happy ;

Page 156: Cpp

most of the times we don’t even need to do this since compiler automatically assigns integral values starting from 0 to each enumerator.

Still sometimes we may need to change the integer values, we could do it like this

Note – Since we did not provide a value to color blue, the next value of previous enumerator is given t it automatically, therefore the value of red was 3

so its next value i.e 4 was given to blue automatically.

Note – It is possible to explicitly define the value of enumerator. These integer values can be positive or negative and can be non-unique. Any non-

defined enumerators are given a value one greater than the previous enumerator.

I do not want to throw so much information at once, so we will learn about the next part i.e using enum effectively in a program, In the next tutorial.

Sharing is caring

UDIT PANDOH

LEAVE A REPLY

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

Name *

Email *

Website

Comment

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite><code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

Post Comment

Notify me of follow-up comments by email.

Notify me of new posts by email.

123456

enumenum color{red , // aggigned value 0 by defaultblue , // aggigned value 1 by defaultgreen // aggigned value 2 by default};

123456

enumenum color{red = 3, // aggigned value 3blue , // aggigned value 4 automaticallygreen = 5 // aggigned value 5};

Page 158: Cpp

ALPHACPP.COM

Using Enumerated Type

May 29, 2015 Udit Pandoh

Since you are now familiar with the concept, consider the eg. and guess itsoutput.

The output of the program will be 1

Another caseLet’s use an enumerator type in another program. Let’s say I have created a text adventure game here is how I can start it.

See ? using enum made my code more neat and understandable to a human, instead of writing

Thus, Enumerated types are incredibly useful for code documentation and readability purposes.

Memory AllocationEnum types are considered part of the integer family of types, and it’s up to the compiler to determine how much memory to allocate for an enum

variable. The C++ standard says the enum size needs to be large enough to represent all of the enumerator values. Most often, it will make enum

variables the same size as a standard int.

Let’s consider some more examples to make sure you have understoodeverything.1 ) In this example, I am adding two numbers but indirectly using enum.

1234567891011121314151617181920

#include "stdafx.h" // only to be used for visual studios.#include <iostream>usingusing namespacenamespace std;voidvoid main(){enumenum color{COLOR_BLACK , COLOR_RED ,COLOR_BLUE ,COLOR_GREEN , COLOR_WHITE , COLOR_CYAN , COLOR_YELLOW, }; color color;color = COLOR_RED ; // will cause compiler errorcoutcout << color;}

1234567891011121314

enumenum option{play ,stop ,pause} ;coutcout << " Enter the option" ;intint option ;cin >>option ;ifif (option == play ){..the game codes}

12345

ifif (option == 0) //I used ifif (option == play )

1 #include "stdafx.h" // only to be used for visual studios.

Page 159: Cpp

Since three and four meant numbers 3 and 4 respectively due to use of enum, writing this

was valid.

2)Printing an enumerated value using cout results in the integral value of the enumerator being printed. So how can you print the enumerator itself as

text? One way to do so is to write a function and use an if statement:

Here, we have also used the concept of parameters, if you have any doubts click the link and go through it once again.

Sharing is caring

UDIT PANDOH

LEAVE A REPLY

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

Name *

Email *

Website

123456789101112131415161718

#include "stdafx.h" // only to be used for visual studios.#include <iostream>usingusing namespacenamespace std;voidvoid main(){enumenum numbers{zero ,one ,two ,three,four ,five }; intint sum = three + four;coutcout << sum ;}

1 intint sum = three + four ;

12345678910111213141516171819202122232425

#include "stdafx.h" // only to be used for visual studios.#include <iostream>usingusing namespacenamespace std;enumenum mood{ happy, sad, }; voidvoid alpha(mood udit) { ifif (udit == happy) coutcout << "Happy"; elseelse ifif (udit == sad) coutcout << "Sad"; elseelse coutcout << "Who knows!";} voidvoid main(){alpha(happy ); }

Page 160: Cpp

Enumerated Type – C++ Tutorial Typedef – C++ Tutorial

Comment

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite><code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

Post Comment

Notify me of follow-up comments by email.

Notify me of new posts by email.

ARCHIVES

June 2015

May 2015

April 2015

March 2015

February 2015

January 2015

April 2013

META

Register

Log in

AlphaCpp.com All rights reserved. Theme by Colorlib Powered by WordPress

Search...

Page 161: Cpp

ALPHACPP.COM

Introduction to String – C++ tutorial

May 29, 2015 Udit Pandoh

The first program that we wrote was ” hello world ”

We studied about characters in previous c++ tutorials, a character is typically interpreted as an ASCII character, thus ‘h’ is a character and so are other

alphabets and symbols.

So in the above statement

What is a string?” Hello, world.” is what we call a string, As you can see a string is nothing but a collection of sequential characters.In C++, we use strings to represent

text such as names, addresses, words, phrases and sentences. String literals are placed between double quotes ( ” ” ) to tell the compiler that it is string.

Because of their common use, modern languages include a built-in data type for string. C++ includes it as part of the standard library.

<string>Since string is a part of the standard library, we need to include the string header file before using it in a program, like this.

Just like your normal variables, you can initialize strings and change its value at any time, even add them !

The output of the above program will be

InputWhen you try to use cin >> with string, it sometimes gives us unexpected results, hence cin >> works with strings as long as there is no whitespace (

space) in the string

” Alpha Cpp ” // There is a whitespace after ha and before c.

The reason being that when using operator >> to extract a string, operator ‘>>’ only returns characters up to the first whitespace it encounters. Any

other characters are left inside, wait for the next extraction.

Note – You can include numbers in a string but they are treated as a character not an integer or any other data-type

Adding two strings

You can put the operator ‘ + ‘ between two strings to add them, let’s use this in a program.

1234567

#include <iostream>usingusing namespacenamespace std ;intint main(){std::coutcout << "Hello, world " << std::endl;returnreturn 0;}

1 coutcout << " Hello world " ;

1 #include <string>

12345

stringstring name ;name = " Alpha Cpp - c++ tutorial rocks " ;coutcout << name ;name = " It is really awesome " ;coutcout <<endl <<name ;

12

Alpha Cpp - c++ tutorial rocks It isis realy awesome

12345

#include "stdafx.h" // only to be used for visual studio.#include <iostream>#include <string>usingusing namespacenamespace std;voidvoid main()

Page 162: Cpp

Using getlineAs we learned above using cin can be dangerous as it gives no error while using cin to extract string with whitespace, so a better alternative is to use

getline . what is getline? getilne take two parameters in first one you enter ‘cin’ and in the other you enter the name of the variable of data type string.

Using getline ensures no error is caused also whitespaces are identified in a string whereas they are ignored if you use cin.

Length of a stringSometimes it is useful if we could know the length of a string, it can be determined by using the following function

let’s use this in an example

We will cover more on string in later tutorials.

Sharing is caring

UDIT PANDOH

LEAVE A REPLY

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

Name *

Email *

Website

Comment

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite><code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-

6789101112

{stringstring firstname, lastname, fullname;firstname = " Udit";lastname = " Pandoh ";fullname = firstname + lastname;coutcout << fullname;}

123

stringstring name ;name = " Alpha Cpp - c++ tutorial rocks " ;getline(cin,name) ;

1 stringname.length()

123456

usingusing namespacenamespace std ;voidvoid main( ){stringstring name = " Udit " ;coutcout << name << " has " << myName.length() <<" characters";}

Page 163: Cpp

Typedef – C++ Tutorial Next Post

url=""> <span class="" title="" data-url="">

Post Comment

Notify me of follow-up comments by email.

Notify me of new posts by email.

ARCHIVES

June 2015

May 2015

April 2015

March 2015

February 2015

January 2015

April 2013

META

Register

Log in

AlphaCpp.com All rights reserved. Theme by Colorlib Powered by WordPress

Search...

Page 164: Cpp

ALPHACPP.COM

Typedef – C++ Tutorial

May 29, 2015 Udit Pandoh

Why use typedef?Suppose I am writing a program which declares a fraction, we know that we need to use data-type float for this purpose.Therefore, our statement would

be like this.

Well, since we know C++, we know that float stands for ‘fraction’ , but what if someone else views the program wouldn’t it better if we could say.

This is can be done with the help of a typedef.Thus, we can say that typedefs allow the programmer to create an alias for a data type and use the

aliased name instead of the actual type name.

Syntax

To declare a typedef, simply use the typedef keyword, followed by the type to alias, followed by the alias name

Let’s consider an example.

Note that typedef does not create a new data type but simply created another name for an existing data type.

Using typedef effectively in a programTypedefs are very useful in a number of cases. Though data type are useful, they are not able to indicate what purpose the program actually serves

consider this example.

The above program is not able to indicate what is it about the bike, that we are talking about.Instead, we could have done this.

Making the editing easierWhen we make very large programs, sometimes the need to change the data type of the variables may arise, in this case, we would have to

change data type of each variable separately, not only is this a lot of work but also , it would time to know what are the variable which needs to

be changed.

but if we had used typedef we would only need to change very few statements. Also use typedefs would have made it clear the exact purpose of each

variable.

Consider the following statements.

first let’s type the better version of above statements using typedef

1 floatfloat pi = 3.145

1 fraction pi = 3.145

1 typedeftypedef typetoalias alias ;

123

typedeftypedef floatfloat fraction ; // define fraction as an alias for type floatdoubledouble pi = 3.145 ; // The following statements are same:fraction pi = 3.145 ;

1 intint bike ;

12

typedeftypedef intint bike ;bike speed = 110 ;

123456

//example 1intint day 1 = 10 ;intint day 2 = 11 ;intint day 3 = 9.8 ;intint day 7 = 50 ;intint day 5 = 6.5 ;

Page 165: Cpp

Using the typedef it becomes very easy now to edit the code1)Not only instead of replacing each int with float, I could simply write float instead of integer once in the typedef definition.

2)Simply by looking at the code I can say that day 7 is not for temperature but for making attendance hence, I need not change it.

Thus instead of editing example 1 like this.

We could have edited the code in example 2 like this,

Sharing is caring

UDIT PANDOH

LEAVE A REPLY

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

Name *

Email *

Website

Comment

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite><code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-

12345678910

//example 2typedeftypedef intint temp ;typedeftypedef intint attendance ; temp day 1 = 10.7 ;temp day 2 = 11.8 ;temp day 3 = 9.8 ;attendance day 7 = 50 ;temp day 5 = 6.5 ;

123456

//example 1intint day 1 = 10 ;intint day 2 = 11 ;intint day 3 = 9.8 ;intint day 7 = 50 ;intint day 5 = 6.5 ;

12345678910

//example 2typedeftypedef intint temp ;typedeftypedef intint attendance ; temp day 1 = 10.7 ;temp day 2 = 11.8 ;temp day 3 = 9.8 ;attendance day 7 = 50 ;temp day 5 = 6.5 ;

Page 166: Cpp

Using Enumerated Type Introduct ion to String – C++ tutorial

url=""> <span class="" title="" data-url="">

Post Comment

Notify me of follow-up comments by email.

Notify me of new posts by email.

ARCHIVES

June 2015

May 2015

April 2015

March 2015

February 2015

January 2015

April 2013

META

Register

Log in

AlphaCpp.com All rights reserved. Theme by Colorlib Powered by WordPress

Search...