Вы находитесь на странице: 1из 166

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, lets 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="" dataurl=""> <span class="" title="" data-url="">

Post Comment

Notify me of follow-up comments by email.


Notify me of new posts by email.

2.1 Welcome to the w orld of variables C++ tutorial

Introduction to programming languages C++ tutorial

Search...

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 Pow ered by WordPress

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 CPUs, 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

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="" dataurl=""> <span class="" title="" data-url="">
Post Comment

Notify me of follow-up comments by email.


Notify me of new posts by email.

Starting w ith the tutorials C++ tutorial

Search...

ARCHIVES
June 2015
May 2015
April 2015
March 2015
February 2015
January 2015
April 2013

META
Register
Log in

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

AlphaCpp.com All rights reserved. Theme by Colorlib Pow ered by WordPress

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. Richies 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>

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

Notify me of follow-up comments by email.


Notify me of new posts by email.

Introduction to programming languages C++ tutorial

Introduction to basics of a program C++ tutorial

Search...

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 Pow ered by WordPress

ALPHACPP.COM

Introduction to basics of a program C++ tutorial


February 1, 2015 Udit Pandoh

Our First program


A 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:
1 int x;
2 x = 5;
3 std::cout << x;

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,
1 int y;
2
3 y = x 3;

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.

Functions
Functions 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.

Library
A 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.

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:
1
2
3
4
5
6
7

#include <iostream>
int main()
{
std::cout <<Hello world! ;
return 0;
}

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 its the first big step in
the journey.

C++ tutorials
Sharing is caring
basics

c++

coding

function

hello w orld

introduction

learn

UDIT PANDOH

LEAVE A REPLY
Your email address will not be published. Required fields are marked *
Name *

Email *

Website

Comment

program

statements

tutorial

tutorials

variables

visual studio

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="" dataurl=""> <span class="" title="" data-url="">
Post Comment

Notify me of follow-up comments by email.


Notify me of new posts by email.

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

Comments C++ tutorial

Search...

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 Pow ered by WordPress

ALPHACPP.COM

Comments C++ tutorial


February 2, 2015 Udit Pandoh

Significance
A 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.
1 int x = 10 ;

and the other one like this


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

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 statements 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
1

//int x ;

In the above example since int x ; is written after // the compiler ignore it code and hence stores a variable named x.
1 std::cout <<"using comments"; //whatever we write now will be ignored by the compiler

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.
1
2
3
4
5
6
7

/*
To check whether a number is even number or not
1)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.
*/

One of the most important thing to learn is to use good comment that actually help the person understand the code;
for example:
1 int marks = 0 ; // marks set to zero

Clearly, this is a bad comment as we can obviously see the marks variable is set to 0.
1 int marks = 0 ; //initial marks are set to zero before we start adding numbers to them.

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 doesnt 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.
1
2
3
4
5

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

Comment out code


There is another important use of codes. It is called commenting out, which implies that there might be times when you dont 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 !!
1 cout <<"hello world " ; // normal statement;
2
3 //cout <<"hello world";

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 glance
To 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 .
1 // std::cout << "1"; //single line comment
2 // std::cout << "2";
3 // std::cout << "3";

1
2
3
4
5

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

c++ tutorial

Sharing is caring
c++

coding

comment

comments

compiler

cpp

learn

program

tips

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="" dataurl=""> <span class="" title="" data-url="">
Post Comment

Notify me of follow-up comments by email.


Notify me of new posts by email.

Introduction to basics of a program C++ tutorial

Search...

ARCHIVES
June 2015
May 2015
April 2015
March 2015
February 2015
January 2015

Hello Variables C++ tutorial

April 2013

META
Register
Log in

AlphaCpp.com All rights reserved. Theme by Colorlib Pow ered by WordPress

ALPHACPP.COM

Hello Variables C++ tutorial


February 3, 2015 Udit Pandoh

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

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

Variables
A 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

Declaration
Now question arises how to declare an integer variable in a C++ coding?
Heres an example of it:
1 int x;

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)
1 x = 20;

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.
1 int x ;
2 x = 10 ;

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

L-value & R-value


In 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 thats 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
2
3
4
5
6

int
x =
x =
int
y =
y =

x; //OK Mr.compiler allocates the memory


5; //x now possesses the value 5
10+20; //x now equals 30
y; //declare variable y
50; // y = 50
x; // y = x i.e. y = 30

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

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
1 int x;
2 cout <<x; //wrong x has no value to display

Uninitialized variable
A 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++ tutorial
Sharing is caring
alphacpp

basics

c++

coding

compiler

cpp

introduction

learn

program

statements

tips

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="" dataurl=""> <span class="" title="" data-url="">
Post Comment

Notify me of follow-up comments by email.


Notify me of new posts by email.

Comments C++ tutorial

Output- C++ tutorial

Search...

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 Pow ered by WordPress

ALPHACPP.COM

Output- C++ tutorial


February 4, 2015 Udit Pandoh

Show me the screen


1
2
3
4
5
6
7

#include <iostream>
int main()
{
int x = 10 ;
std::cout << x;
return 0 ;
}

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 whats 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;
1
2
3
4
5
6
7

int main()
{
int x =10 ;
int y = 20;
std::cout <<x <<y ;
return 0;
}

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 ).

String
Second 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.
1 std::cout << "this is a string we can even include numbers and other symbols 123@" ;

Also one more thing, when you write something like this
1 std::cout <<"hello";
2 std::cout <<"world";

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::endl
1)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.
1 std::cout <<" hello " <<std::endl ;
2 std:cout <<"world " ;

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.
1 std::cout <<"hello" <<std::endl <<"world";

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.
1 std::cout <<"hello /n world ";

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++ tutorial
Sharing is caring
<<

basics

c++

change line

coding

display

learn

output

UDIT PANDOH

LEAVE A REPLY
Your email address will not be published. Required fields are marked *
Name *

Email *

Website

tips

tutorial

tutorials

visual studio

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="" dataurl=""> <span class="" title="" data-url="">
Post Comment

Notify me of follow-up comments by email.


Notify me of new posts by email.

Hello Variables C++ tutorial

Input C++ tutorial

Search...

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 Pow ered by WordPress

ALPHACPP.COM

Input C++ tutorial


February 5, 2015 Udit Pandoh

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

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.
1
2
3
4
5
6
7
8
9

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

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 using namespace std;

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
1
2
3
4
5
6

#include <iostream>
int main()
{
std::cout << "Hello world! ";
return 0;
}

now adding the using namespace std the program becomes


1
2
3
4
5
6
7

#include <iostream>
using namespace std;
int main()
{
cout << "Hello world! ";
return 0;
}

c++ tutorial
Sharing is caring
>>

basics

c++

coding

control

input

learn

program

tips

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="" dataurl=""> <span class="" title="" data-url="">
Post Comment

Notify me of follow-up comments by email.


Notify me of new posts by email.

Output- C++ tutorial

Starting w ith operators C++ tutorial

Search...

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 Pow ered by WordPress

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

#include <iostream>
using namespaces std;
int main()
{
//1) We will declare three integers
int x , y , z ;

//2)take input from user


cin >>x >>y;
//3)add x and y and store their value in z
z = x + y ;
//4)output the value of z to the screen
cout <<"the sum of " <<x <<" and " <<y <<" is " <<z;
return 0 ;
}

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 :
1 int x = 12 ;
// x is a variable 12 is a literal.
2 cout << "hello world" ; //even "hello world" is a literal.
3 int y = 10 + 2 ;
//y is a variable 10 and 2 are literals.

Expression
An expression is the combination of literals , expression and operators,every statement in the previous example were expressions.
1 int y = 15 + 10 ;

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

C++ tutorials
Sharing is caring
add

basics

tutorials

user

c++

coding

varibale

cpp

epression

equal

learn

literal

operand

operator

operators

output

program

subtract

tips

tutorial

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="" dataurl=""> <span class="" title="" data-url="">
Post Comment

Notify me of follow-up comments by email.


Notify me of new posts by email.

Input C++ tutorial

Search...

ARCHIVES

Keyw ords & Identifiers C++ tutorial

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 Pow ered by WordPress

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.

1
2

int 1subject ; // illegal identifier cannot start with a number.


int subject1 ; //legal as the identifier is not starting with a number.

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


1 int Name,name

; // considered as two different identifiers

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

int
int
int
int
int
int

name
;
name1
;
name_1
;
nAmE_1 2 ;
$name
;
name_%
;

//legal it contains only letters.


//legal it contains letters and a number.
//legal it also contains an underscore.
//illegal it contains a whitespace after 1.
//illegal a symbol is used.
//illegal a symbol is used.

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

1
2
3
4
5
6
7
8

#include <iostream>
using namespace std;
void main()
{
int
class , roll number, percentage%
cin
>>class >>roll number >> percentage%
cout <<class <<roll number <<percentage%
}

;
;
;

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.

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

Sharing is caring

UDIT PANDOH

2 thoughts on Keywords & Identifiers C++ tutorial


MOON
March 20, 2015 at 5:49 am

I loved the tutorials very good job


REPLY

UDIT PANDOH
March 20, 2015 at 6:35 am

Thanks mate
REPLY

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="" dataurl=""> <span class="" title="" data-url="">
Post Comment

Notify me of follow-up comments by email.


Notify me of new posts by email.

Starting w ith operators C++ tutorial

W riting a neat code C++ tutorial

Search...

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 Pow ered by WordPress

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.

1
2
3
4
5
6
7
8

int x ;
int
int

x;
x

int
x ;

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.
1 cout <<"hello" <<"world"
; // prints 'helloworld'
2 cout <<"hello world"
; // prints 'hello world'
3 cout <<"hello
world" ; // prints 'hello world'

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
1 int main() {
2 int x,y,z;

3 cout <<x<<y ;
4 cin>>x>>y; }

1
2
3
4
5
6

int main()
{
int x,y,z
;
cout <<x <<y ;
cin >>x >>y ;
}

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.
1 int x = 80 ;
2
3 //and the other one wrote.
4 int strength = 80 ;

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.
1
2
3
4
5
6
7
8
9
10

#include <iostream>
using namespace std;
void main()
{
int a,b,c,d;
cout <<" Enter marks for maths physics and chemistry resp. " ;
cin>>a>>b>>c ;
avg=(a+b+c)/3;
cout <<avg;
}

And lets rewrite the code now in a better way.


1
2
3
4
5
6
7
8
9
10
11
12

#include <iostream>
using namespace std;
void main()
{
int avg,sub_1,sub_2,sub_3
;
cout <<" Enter marks for each subject " ;
cout <<endl
;
cin >>sub_1 >>sub_2 >>sub_3
;
avg =(sub_1 + sub_2 + sub_3 ) / 3 ; // divide by three for average
cout <<endl <<endl <<" Average = " ;
cout <<avg
;
}

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

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="" dataurl=""> <span class="" title="" data-url="">
Post Comment

Notify me of follow-up comments by email.


Notify me of new posts by email.

Keyw ords & Identifiers C++ tutorial

Search...

ARCHIVES
June 2015
May 2015
April 2015
March 2015
February 2015
January 2015
April 2013

META
Register
Log in

0.2 Introduction to programming languages C++ tutorial

AlphaCpp.com All rights reserved. Theme by Colorlib Pow ered by WordPress

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 dont 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.
1

int strength = 10 ;

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.
1 int x ;
2 cin >> x ;
3 cout << x ;

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.
1
2
3
4

int
x =
y =
z =

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

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

C++ tutorials
Sharing is caring
alphacpp

basics

c++

c++ problem

coding

cpp

introduction

UDIT PANDOH

LEAVE A REPLY
Your email address will not be published. Required fields are marked *
Name *

learn

program

recap

tips

variable

variables

visual studio

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="" dataurl=""> <span class="" title="" data-url="">
Post Comment

Notify me of follow-up comments by email.


Notify me of new posts by email.

Multiplication table

Countdow n

Search...

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 Pow ered by WordPress

ALPHACPP.COM

Definition and Initialization C++ tutorial


March 2, 2015 Udit Pandoh

Defining
We 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.
1 //the general from is
2 Datatype name ;

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 .
1 //For example
2 int population ;

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.

Initialization
Initialization 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.
1 int x = 5 ;

1 int x ;
2 x = 5 ;

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.
1 int apples = 5 ;

2)Implicit Initialization
In this method we simple write the value we want to assign between two round brackets ( ) .
1 int apples(5) ;

C++ tutorials
Sharing is caring

alphacpp

basics

c++

coding

compiler

cpp

defination

define

intialization

intialize

introduction

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="" dataurl=""> <span class="" title="" data-url="">
Post Comment

Notify me of follow-up comments by email.


Notify me of new posts by email.

Store ow ners problem

Search...

ARCHIVES
June 2015
May 2015
April 2015
March 2015
February 2015
January 2015
April 2013

Function Parameters C++ tutorial

META
Register
Log in

AlphaCpp.com All rights reserved. Theme by Colorlib Pow ered by WordPress

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.
1 int x , y , z ,a ,b ,c ;

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 ;
1 int x , y
; // correct they all are of the same data i.e integer ;
2
3 int x , char y ; // wrong x is of type integer whereas y is a char (character) ;

consider this
1 int x ,y;

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
1
2
3
4
5

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

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
1
2
3
4

int x , y
cin >> x
y = x + 5
cout << y

;
;
;
;

but a more better way is :


1
2
3
4
5

int x
cin >> x
int y
y = x + 5
cout <<y

;
;
;
;
;

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++ 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="" dataurl=""> <span class="" title="" data-url="">
Post Comment

Notify me of follow-up comments by email.


Notify me of new posts by email.

Function Parameters C++ tutorial

Search...

ARCHIVES
June 2015
May 2015
April 2015
March 2015
February 2015
January 2015
April 2013

META
Register
Log in

Size of variables C++ tutorial

AlphaCpp.com All rights reserved. Theme by Colorlib Pow ered by WordPress

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
Value 1
Value 2
Value 3
Value 4
4 values.

1231
0
0
1
1

1232
0
1
0
1

To generalize, a variable with n bits can hold 2n (2 to the power of n) possible values. Since a byte is 8 bits, a byte can store 2 8 (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 isnt 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 types


You 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
boolean
character
integer

Type
Minimum Size
bool
1 byte
char
1 byte
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 operator
In 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)

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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

#include <iostream>
int main()
{
using namespace std;
cout <<Size
cout <<Size
cout <<Size
cout <<Size
cout <<Size
cout <<Size
cout <<Size
cout <<Size
cout <<Size
return 0;

of
of
of
of
of
of
of
of
of

bool : <<sizeof (bool )<< bytes<<endl;


char : <<sizeof (char )<< bytes<<endl;
short : <<sizeof (short )<< bytes<<endl;
int : <<sizeof (int )<< bytes<<endl;
long : <<sizeof (long )<< bytes<<endl;
float : <<sizeof (float )<< bytes<<endl;
long long : <<sizeof (long long )<< bytes<<endl;
double : <<sizeof (double )<< bytes<<endl;
long double : <<sizeof (long double )<< bytes<<endl;

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:
1
2
3
4

int num;
float fl;
cout <<Size of int : <<sizeof num;
cout <<Size of float : <<sizeof fl;

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="" dataurl=""> <span class="" title="" data-url="">
Post Comment

Notify me of follow-up comments by email.


Notify me of new posts by email.

Using Variables C++ tutorial

Integers Basics C++ tutorial

Search...

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 Pow ered by WordPress

ALPHACPP.COM

Integers Basics C++ tutorial


March 5, 2015 Aaryan Kapoor

Integers
An 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. Well 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 integers
The various types of integers are declared the following way.
1. Char
1 char ch;

2. Short
1 short int num;

OR
1 short num;

//both are equivalent

3. Int
1 int i;

4. Long
1 long int lnum;

OR
1 long lnum;

//both are equivalent

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:
1 long long int llnum;

OR
1 long long llnum;

//both are equivalent

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 integers


Now under this Cpp tutorial section we will learn signed and unsigned intgers. A variable with n bits can store 2n 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.

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.
1
2
3
4
5

signed
signed
signed
signed
signed

char ch;
short sh;
int num;
long lnum;
long long llnum;

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 n-1 to 2n-1-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.
1
2
3
4
5

unsigned
unsigned
unsigned
unsigned
unsigned

char ch;
short sh;
int num;
long lnum;
long long llnum;

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 n-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 practices


All 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

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="" dataurl=""> <span class="" title="" data-url="">
Post Comment

Notify me of follow-up comments by email.


Notify me of new posts by email.

Size of variables C++ tutorial

Search...

ARCHIVES
June 2015
May 2015
April 2015
March 2015
February 2015
January 2015
April 2013

Integers-Overflow C++ tutorial

META
Register
Log in

AlphaCpp.com All rights reserved. Theme by Colorlib Pow ered by WordPress

ALPHACPP.COM

Integers-Overflow C++ tutorial


March 6, 2015 Aaryan Kapoor

Avoiding integers overflow


If we try to put a number outside of the data types 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 examples
Consider 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, lets take a look at an example using actual code, assuming a new data type for integers (newint) which is 8 bits:
1
2
3
4
5
6
7
8
9
10
11

#include <iostream>
int main()
{
using namespace std;
unsigned newint x = 255;
cout << "x was: " << x << endl;
x = x + 1;
cout << "x is now: " << x << endl;
return 0;
}

//initial value of x
// 128 is out of range
//final value of x

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 dont 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.
1
2
3
4
5
6
7
8
9
10
11

#include <iostream>
int main()
{
using namespace std;
unsigned newint x = 0;
cout << "x was: " << x << endl;
x = x - 1;
cout << "x is now: " << x << endl;
return 0;
}

//initial value of x
// -1 is out of range
//final value of x

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++ tutorials
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="" dataurl=""> <span class="" title="" data-url="">
Post Comment

Notify me of follow-up comments by email.


Notify me of new posts by email.

Integers Basics C++ tutorial

Search...

ARCHIVES
June 2015
May 2015

2.7 Boolean Values C++ tutorial

April 2015
March 2015
February 2015
January 2015
April 2013

META
Register
Log in

AlphaCpp.com All rights reserved. Theme by Colorlib Pow ered by WordPress

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
1 float f=1.1;

2. double
1 double db=1.21;

3. long double
1 long double ldb=1.321;

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 Notation


But 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 10p 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 -31 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
2
3
4
5
6
7

#include<iomanip>
.
.
.
using namespace std;
float fl=121.121;
cout <<"Without scientific: "<<fl<<endl;

8 cout <<scientific; // adding scientific command


9 cout <<"With scientific: "<<fl;

Output:
Without scientific: 121.121
With scientific: 1.12121e2
You can clearly see how scientific command works.

Precision
While 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:
1 //without setprecision()
2 float fl=98765432.1;
3 cout <<fl;

Output:
9.87654e7
Notice, it automatically converts the number into scientific notation, in order to convert it into the precision limit.
1
2
3
4
5
6
7
8

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

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

Rounding errors
As 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:
1
2
3
4
5

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

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

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="" dataurl=""> <span class="" title="" data-url="">
Post Comment

Notify me of follow-up comments by email.


Notify me of new posts by email.

sw itch statement

Search...

ARCHIVES
June 2015
May 2015
April 2015
March 2015
February 2015
January 2015
April 2013

META

Arrays and loops

Register
Log in

AlphaCpp.com All rights reserved. Theme by Colorlib Pow ered by WordPress

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.
1 bool abc;

When assigning values to boolean variables, we use the keywords true and false.
1 bool tr = true ;
2 bool fa(false );

The logical NOT operator (!) can be used to the convert the value from true to false and vice versa.
1 bool tr=true ;
2 bool fa=!tr;

//evaluates tr as true
//evaluates fa as opposite of tr i.e. false

When we print the values with cout, it prints 0 for false, and 1 for true:
1
2
3
4
5
6
7
8
9
10
11
12
13

#include <iostream>
int main()
{
using namespace std;
bool tr(true );
cout << tr << endl;
cout << !tr << endl;
bool fa=!tr;
cout << fa << endl;
cout << !fa << endl;
return 0;
}

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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

#include <iostream>
#include <iomanip>
int main()
{
using namespace std;
bool b=true ;
cout << b << endl;
cout << !b << endl;
cout << boolalpha;
cout << b << endl;
cout << !b << endl;
return 0;
}

Output will be:


1
0
true

// print all bools from now on as true or false

false

Boolean in if-statement
If statements are of the form:
1 if (condition) if -statement;

OR
1 if (condition) if -statement;
2
3 else else -statement;

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.
1 bool b(false );
2 if (b)
3
cout << "b is true" << endl;
4 else
5
cout << "b is false" << endl;

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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

#include<iostream>
bool isfunc(int x)
{
return x;

/*Since function is of bool type so it


will return 1 when true and 0 when false*/

}
int main()
{
using namespace std;
int num;
cout << Enter a number: ;
cin>>num;
bool chck=isfunc(num);
if (chck)
cout <<The number <<num<< is nonzero;
else
cout <<The number <<num<< is zero;
return 0;
}

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="" dataurl=""> <span class="" title="" data-url="">
Post Comment

Notify me of follow-up comments by email.


Notify me of new posts by email.

Integers-Overflow C++ tutorial

Char C++ tutorial

Search...

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 Pow ered by WordPress

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.
1 char num(1)
2
3 char ch(1)

//stores the value in num as 1


//stores the value as ASCII code for 1 (49)

Printing char
When using cout to print a char, cout outputs the char variable as an ASCII characters instead of a number.
1
2
3
4
5
6
7
8
9
10

#include <iostream>
int main()
{
using namespace std;
char ch(65);
//initializing ch with an integer
cout <<ch;
//cout prints a character
return 0;
}

This output will be:


A
rather than the expected 65.
We can also output char literals directly:
1 cout <<A

This output will be:


A

Inputting char
You can input the char simply by using cin:
1 cin>>ch;

The following program asks the user to input a character and then display the character as well as its ASCII code:
1
2
3
4
5
6
7
8
9
10
11
12

#include <iostream>
int main()
{
using namespace std;
char ch;
cout <<Input a character: ;
cin>>ch;
int num=ch;
cout <<ch<< has ASCII code <<num<< endl;
return 0;
}

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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

#include <iostream>
int main()
{
using namespace std;
char ch;
cout << "Input a character: "; //assume the user enters ABC
cin >> ch;
// ch = 'A', BC enters input buffer
int num= ch;
cout << 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;
cout <<ch<<" has ASCII code "<<num<<endl;
return 0;
}

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 sign


Char is defined by C++ to always be one byte in size. By default, a char may be signed or unsigned (though its usually signed). If youre using char to
hold ASCII characters, you dont need to specify a sign.
If youre 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 sequences
As 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.
1 cout << Start\nend;

Another commonly used escape sequence is \t, which simply does the job of tab key.
1 cout <<Working of\ttab;

Heres 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

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 string
Text 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++ tutorials
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="" dataurl=""> <span class="" title="" data-url="">
Post Comment

Notify me of follow-up comments by email.


Notify me of new posts by email.

2.7 Boolean Values C++ tutorial

Constants C++ tutorial

Search...

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 Pow ered by WordPress

ALPHACPP.COM

Constants C++ tutorial


March 9, 2015 Aaryan Kapoor

Symbolic constants
A 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.
1 #define name constant

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:
1 #define Pi 3.1415
2 float area = Pi * r * r;
3 float Perimeter = 2 * Pi * r;

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
1 #define Pi 3.1415
2 float area = 3.1415 * r * r;
3 float Perimeter = 2 * 3.1415 * r;

But we would still see it as


1 #define Pi 3.1415
2 float area = Pi * r * r;
3 float Perimeter = 2 * Pi * r;

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:
1
2
3
4
5
6
7
8
9

#include<iostream>
#define A 12
int main()
{
using namespace std;
int A= 1;
cout <<A;
}

This program will show error. This is because preprocessor replaces this
int A=1; with int 12=1;

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:
1 const <data_type> <name> = <value >;

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:
1 const float Pi = 3.1415;

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


Eg:
1 const float Pi;
2 Pi = 3.1415;

This will show an error.


Also, value of const cannot be changed; neither by the programmer nor by the user.
Eg: (by programmer)
1 const int a = 1;
2 a=2;

This will show an error suggesting that you cannot change the value of a constant.
(by user)
1 const int a = 1;
2 cin>>a;
3 cout <<a;

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.
1 const float Pi = 3.1415
2 float area = Pi * r * r;
3 float Perimeter = 2 * Pi * r;

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++ tutorials
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="" dataurl=""> <span class="" title="" data-url="">
Post Comment

Notify me of follow-up comments by email.


Notify me of new posts by email.

Char C++ tutorial

Search...

ARCHIVES
June 2015
May 2015
April 2015
March 2015
February 2015
January 2015
April 2013

META
Register
Log in

Operators Arithmetic C++ tutorial

AlphaCpp.com All rights reserved. Theme by Colorlib Pow ered by WordPress

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 eithers 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)
long cannot represent all the values of the unsigned int)

7.

long

long

8.

unsigned

unsigned

unsigned int (if

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 /

fl

ldb)

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 *

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="" dataurl=""> <span class="" title="" data-url="">
Post Comment

Notify me of follow-up comments by email.


Notify me of new posts by email.

compare the tw o strings

Explicit Type Conversion

Search...

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 Pow ered by WordPress

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:
1 (type) expression

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:
//We want to completely divide two integers
int a = 5, b = 2;
cout << a/b<<endl;
cout << (float )a/ b;

1
2
3
4

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

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="" dataurl=""> <span class="" title="" data-url="">
Post Comment

Notify me of follow-up comments by email.


Notify me of new posts by email.

Implicit type conversion

Search...

ARCHIVES
June 2015
May 2015
April 2015
March 2015
February 2015
January 2015
April 2013

META
Register
Log in

comments in java

AlphaCpp.com All rights reserved. Theme by Colorlib Pow ered by WordPress

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
1 a + b ;

1 a - b ;

1 c * d ;

1 c / d ;

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
1 21 % 5

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

simply activate endl


when the following expression results in 0.
1 number of words already printed % 5

Though we dont 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++ 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="" dataurl=""> <span class="" title="" data-url="">
Post Comment

Notify me of follow-up comments by email.


Notify me of new posts by email.

Constants C++ tutorial

Search...

ARCHIVES
June 2015
May 2015
April 2015

Operator Increment and Decrement C++ tutorial

March 2015
February 2015
January 2015
April 2013

META
Register
Log in

AlphaCpp.com All rights reserved. Theme by Colorlib Pow ered by WordPress

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 .
1 x = x + 1
2 //or
3 x = x - 1

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

The Increment operator


In 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
1 ++x ;

One should Note there is no difference between writing


1 ++x ;
2 //or
3 x = x + 1 ;

But thats 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
1 int
2 y
3 cout

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

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.
1
2
3
4
5

int
cout
cout
cout
cout

x = 8 , y = 4
<< x <<y
<<++x <<y
<<x
<<++y
<<x ++ <<y ++

;
;
;
;
;

//
//
//
//

1 statement
2
3
4

6 cout

<<x

<<y

; // 5

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 operator
In 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="" dataurl=""> <span class="" title="" data-url="">
Post Comment

Notify me of follow-up comments by email.


Notify me of new posts by email.

Operators Arithmetic C++ tutorial

Search...

Operators- Relational- 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 Pow ered by WordPress

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

<

Less than

3<5

>

Greater than

3>5

<=

Less than or equal to

3 <= 5

>=

Greater than or equal to

3 >= 5

!=

Not equal to

3 != 5

NOTE: A very common mistake is to use the assignment operator (=) in place of relational operator (==). You should not be confused
between them.
Eg:
1 a==12;
2 a=12;

//checks whether a is equal to 12


//assigns 12 to a;

See this program to clarify any further doubts.


1
2
3
4
5
6
7
8
9

#include<iostream>
int main()
{
Using namespace std;
int num=3;
cout <<num==2 prints <<num==2<<endl;
cout <<num=2 prints <<num=2;
return 0;
}

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

(a+2)<(b+3)
Rather than
a+(2<b)+3
So, you must be careful.

Relational operators between signed and unsigned


We 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:
1 int a=-1;
2 unsigned b=3;
3 cout << a<b;

Output:
0
This is completely unexpected. Lets 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:
1 a<(signed int )b;

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:
1 int num1=-3;
2 unsigned num2=123;
3 cout <<num1<num2 = <<(signed long )num1<(signed long )num2;

Relational operators for floating point


You 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++ tutorials
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="" dataurl=""> <span class="" title="" data-url="">
Post Comment

Notify me of follow-up comments by email.


Notify me of new posts by email.

Operator Increment and Decrement C++ tutorial

Search...

Operators- Logical Cpp 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 Pow ered by WordPress

ALPHACPP.COM

Comma and conditional operators Cpp tutorial


May 13, 2015 Aaryan Kapoor

The Comma Operator


A 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:
1 int a= (b=1, c=b+1, c+1);

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

See another example:


1
2
3
4
5

int x, y;
x= (1, 2);
y= 1, 2;
cout << x = <<x<<endl;
cout << y= <<y;

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:
1
2
3
4
5

int func (int x, int y) //this is not an operator


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

The comma used when two or more variables are declared is also a separator and not an operator.
Eg:
1 int x, y, z;

//this is not an operator

so this point leads to another example:


1 int x= 1, 2, 3;

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

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:
1 cin>>marks;
2 char result = marks>=50? P: F;

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:
1 int base=10;
2 int disc=base + bill>5000?10:0;

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:
1 int base=10;
2 int disc=base + (bill>5000?10:0);

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:
1 int grt, lsr, num;
2 cin>>num;
3 num>100?grt:lsr=1;

You can also nest two or more conditional operators.


Eg:
1 cin>>marks;
2 char grade= marks>=75?(marks>=90? A: B): C;

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++ tutorials
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="" dataurl=""> <span class="" title="" data-url="">
Post Comment

Notify me of follow-up comments by email.


Notify me of new posts by email.

Break And Continue C++ Tutorial

Arrays C++ Tutorial

Search...

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 Pow ered by WordPress

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 doesnt satisfy the condition (are not correct) the emails wont 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 OR
The 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

1<=3||4>=7

5!=5 ||1==1

5>2 || 5

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 AND
The 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

1<=3&&4>=7

5!=5 &&1==1

5>2 && 5

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 NOT
Logical 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)

!(5)

!(1<3)

!(0)

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:
while

!(1<2) results in 0
!1<2 results in 1

Lets 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++ tutorials
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="" dataurl=""> <span class="" title="" data-url="">
Post Comment

Notify me of follow-up comments by email.


Notify me of new posts by email.

Operators- Relational- C++ tutorial

Search...

ARCHIVES
June 2015
May 2015
April 2015
March 2015
February 2015
January 2015
April 2013

META
Register

Precedence of operators C++ tutorial

Log in

AlphaCpp.com All rights reserved. Theme by Colorlib Pow ered by WordPress

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 y = 11 < 10 + 3 && 7 * 2>= 28 / 2;


2 cout <<y;

1.

Output:
1 1

Solution:
1
2
3
4
5
6
7
8
9

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


y = ((11 < (10 + 3)) && (14>=14))
y = ((11 < 13) && 1)
y = (1 && 1)
y = 1

1 x = (y = 13, z=0, z != 10 + 3 > --y)


2 cout <<x;

2.

Output:
1 1

Solution:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

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

1 x = (y = 13, z=0, z != 10 + 3 > y--)


2 cout <<x;

3.

Output:
1

Solution:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

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

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

4.

Output:
1

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

4
5
6
7
8
9
10
11
12
13
14
15
16
17

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)

5.

Output:
1 1

Solution:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

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

C++ tutorials
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="" dataurl=""> <span class="" title="" data-url="">
Post Comment

Notify me of follow-up comments by email.


Notify me of new posts by email.

Operators- Logical Cpp tutorial

Understanding Functions C++ tutorial

Search...

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 Pow ered by WordPress

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.
1
2
3
4
5

int name ( )
{
body
return value
}

Declaration
when 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).
1
2
3
4
5
6
7
8
9

int anyname( )
{
return 5 ;
}
int main( )
{
cout << anyname() ;
}

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 dont want to
return any value in the hello world program so we return a value of 0.
1
2
3
4
5
6

#include <iostream>
using namespace std;
int main()
{
cout <<" hello world " ;

7 return 0 ;
8 }

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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

#include <iostream>
using namespace std;
int main( )
{
int x , y , z ;
cout <<" whats your favorite number ? " ;
cin >>x ;
cout <<endl <<"you said - " <<x <<endl;
cout <<" whats your favorite number ? " ;
cin >>y ;
cout <<endl <<"you said - " <<y <<endl;
cout <<" whats your favorite number ? " ;
cin >>z ;
cout <<endl <<"you said - " <<z <<endl;
cout <<"and the sum is - " << x + y + z
return 0 ;
}

One thing that might confuse you is that in x + y + z we did not store their value in a variable because we simply didnt 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

#include <iostream>
using namespace std;
int getfavno( )
{
int x
cout <<" whats your favorite number ? " ;
cin >>x
;
cout <<endl <<"you said - " <<x <<endl ;
return x ;
}
int main
{
int a , b, c;
int a = getfavno( ) ;
int b = getfavno( ) ;
int c = getfavno( ) ;
cout <<"sum is " <<a + b +c ;
return 0;

See the difference our code is much cleaner and understandable now !!
1
2
3
4
5
6
7
8
9
10
11
12

//consider this program


#include <iostream>
using namespace std;
int doA ( )
{
cout << " a is executed " <<endl ;
return 0 ;
}
int doB ( )
{
cout <<" b is executed " <<endl ;

13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

doA( );
doC( );
return 0 ;
}
int doC ( )
{
cout <<" c is executed " <<endl ;
return 0 ;
}
int main( )
{
doB( )
;
return 0 ;
}

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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

#include <iostream>
using namespace std;
int doA ( )
{
cout << " a is executed " <<endl ;
return 0 ;
}
int doC ( )
{
cout <<" c is executed " <<endl ;
return 0 ;
}
int doB ( )
{
cout <<" b is executed " <<endl ;
doA( ) ;
doC( ) ;
return 0 ;
}
int main( )
{
doB( ) ;
return 0 ;
}

And voila then function !! will run successfully !!

Understanding more about return


Remember 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.
1
2
3
4
5
6
7
8
9
10

int add ( )
{
int c = 3 + 4
;
return c
;
}
void main ( )
{
cout << add ( )
;
cout << add( ) + 5 ;
}

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 .
1 add ( )

// for the compiler it is just a value 7.

so all the statement given below can be used in int main ( )


1 int main
2 {
3 cout << add( )

4 int a = add( ) - 5 ;
5 int c = add( ) * 4 ;
6 }

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++ tutorials
Sharing is caring
basics

c++

coding

compiler

cpp

function

introduction

learn

program

tips

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="" dataurl=""> <span class="" title="" data-url="">
Post Comment

Notify me of follow-up comments by email.


Notify me of new posts by email.

Precedence of operators C++ tutorial

Parameters I C++ tutorial

Search...

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 Pow ered by WordPress

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.
1
2
3
4
5
6
7
8
9
10
11
12
13

#include "stdafx.h"
#include <iostream>
using namespace std ;
int add ( )
{
int c
;
c = 5 + 6 ;
return c ;
}
void main ( )
{
cout << add( ) ;
}

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.
1 int add (int a , b)

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 !!
1
2
3
4
5

int add (int a , b)


{
c = a + b ;
return c
}

The next thing is how to declare this new function now in a program we will cover this in the next topic.

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="" dataurl=""> <span class="" title="" data-url="">
Post Comment

Notify me of follow-up comments by email.


Notify me of new posts by email.

Understanding Functions C++ tutorial

Search...

ARCHIVES
June 2015
May 2015
April 2015
March 2015
February 2015
January 2015
April 2013

META
Register
Log in

Parameters II C++ tutorial

AlphaCpp.com All rights reserved. Theme by Colorlib Pow ered by WordPress

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.
1
2
3
4
5
6
7
8
9

#include "stdafx.h"
#include <iostream>
using namespace std ;
int add ( int a , int b )
{
int c
;
c = a + b ;
return c ;
}

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 function


normally for a function named add , we would call the function like
1 add ( ) ;

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
1 add( 5 , 6 ) ;

remember in the definition we did


1 int add ( int a , int b )if you compare two we get that for the function will treat a as 5 and b as 6 thus

1 add ( 3 , 4 )
2 //for this call variable a will become and b will become 4

Even in the functions body think it like the variable a was replaced by 3 and b will become 4
i.e
1
2
3
4
5
6

int add ( int a , int b )


{
int c
c = a + b ;
return c ;
}

becomes
1
2
3
4
5
6

int add ( 3 , 4)
{
int c
c = 3 + 4 ;
return c ;
}

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.
1
2
3
4
5
6

#include "stdafx.h"
// only to be used for visual studios.
#include <iostream>
using namespace std ;
void add ( int a , int b )
{
int c
;

7
8
9
10
11
12
13
14
15
16

c = a + b ;
cout << c <<endl ;
}
int main ( )
{
add ( 3 , 4 ) ;
add ( 1 , 9 ) ;
add ( 4 , 2 ) ;
add ( 5 , 6 ) ;
}

If we run this program it will give us the output


1
2
3
4

7
10
6
11

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="" dataurl=""> <span class="" title="" data-url="">
Post Comment

Notify me of follow-up comments by email.


Notify me of new posts by email.

Parameters I C++ tutorial

Search...

Void 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 Pow ered by WordPress

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.
1
2
3
4
5
6
7
8
9
10

int hello( )
{
cout << " hello world"
return 0
}
int main ( )
{
hello ( ) ;
return 0 ;
}

;
;

void
here 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.
1
2
3
4
5
6
7
8

void hello( )
{
cout << " hello world " ;
}
void main ( )
{
hello ( ) ;
}

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.
1
2
3
4
5

Void sum (int a, int b)


{
int c=a+b;
cout <<The Sum is : <<c;
}

\\declaration of a function named sum

2) It is used to indicate that the function does not take any parameters.
1
2
3
4
5
6
7

int apples(void )
//void here means no parameter is required.
{
int num;
cout <<Enter the number of apples: ;
cin>>num;
return num;
//Here the function returns a value to the place it was called
}

The following code is equivalent in C++:


1
2
3
4
5
6
7

int apples()
//void here means no parameter is required.
{
int num;
cout <<Enter the number of apples: ;
cin >>num;
return num;
//Here the function returns a value to the place it was called
}

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.
1 void a;

//This is wrong

An important use of void is in void pointers. Since, you still dont know what pointers are, so we will not discuss it here but in the later Cpp tutorial.

C++ tutorial
Sharing is caring
alphacpp

basics

c++

coding

compiler

cpp

introduction

learn

program

statements

tips

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="" dataurl=""> <span class="" title="" data-url="">
Post Comment

Notify me of follow-up comments by email.


Notify me of new posts by email.

Parameters II C++ tutorial

Search...

ARCHIVES
June 2015
May 2015
April 2015
March 2015
February 2015

Forw ard declarations C++ tutorial

January 2015
April 2013

META
Register
Log in

AlphaCpp.com All rights reserved. Theme by Colorlib Pow ered by WordPress

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 .
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

#include <iostream>
using namespace std ;
void add ( )
{
int c =
6 + 7 ;
cout << c
;
}
void multiply ( )
{
int c =
6 * 7 ;
cout << c
;
}
void alpha ( )
{
cout << " hi " ;
}
void main ( )
{
add ( )
;
multiply ( )
;
alpha ( )
;
}

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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

#include <iostream>
using namespace std ;
void main ( )
{
add
( )
multiply ( )
alpha
( )
}

;
;
;

void alpha ( )
{
cout << " hi "
}
void multiply ( )
{
int c =
6 * 7
cout << c
}
void add ( )
{ int c =
cout << c
}

;
;

6 + 7 ;
;

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 declarations
Hence 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 ( )

{
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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

include <iostream>
using namespace std ;
void add
( ) ;
void multiply ( ) ;
void alpha
( ) ;
void main ( )
{
add
( )
multiply ( )
alpha
( )
}

;
;
;

void alpha ( )
{
cout << " hi "
}
void multiply ( )
{
int c =
6 * 7
cout << c
}
void add ( )
{ int d =
cout << d
}

;
;

6 + 7 ;
;

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.
1

void multiply (int a , int b )

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.
1

void multiply (int , int )

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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

include <iostream>
using namespace std ;
void multiply (int , int ) ;
void main ( )
{
multiply (5,6)
}

void multiply (int a , int b)


{
int c = a * b
;
cout << c
;
}

Another important use


If 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

hence forward declarations are useful in this case too.

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="" dataurl=""> <span class="" title="" data-url="">
Post Comment

Notify me of follow-up comments by email.


Notify me of new posts by email.

Void C++ tutorial

Search...

ARCHIVES
June 2015
May 2015
April 2015
March 2015
February 2015

Local Variables C++ Tutorial

January 2015
April 2013

META
Register
Log in

AlphaCpp.com All rights reserved. Theme by Colorlib Pow ered by WordPress

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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

#include<iostream>
void main()
{
using namespace std;
int a=1;

//will call it a1 in explanation

cout << a= <<a<<endl;


{
int a=2;

//will call it a2 in explanation

/*you might expect an error here


as there are multiple declarations*/
cout << a= <<a<<endl;

//local variable is given preference


}
cout << a= <<a;
}

Output:
1 a= 1
2
3 a= 2
4
5 a= 1

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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14

#include<iostream>
void main()
{
using namespace std;
int a=1;
cout << a= <<a<<endl;
{

//variable a is declared

15
16
17
18
19
20
21
22
23
24
25
26
27

1
2
3
4
5
6
7

a=2;

//notice the change

//value of the above a is changed


cout << a= <<a<<endl;
}
cout << a= <<a;

//changed value of a is displayed.


}

Output:
a= 1
a= 2
a= 2

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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

Eg:
void func()
{
int a=1;

//will call it a1 in explanation

cout << a= <<a<<endl;


}
void main()
{
int a=2;

//will call it a2 in explanation

func();
cout << a= <<a<<endl;
}

1 Output:
2
3 a= 1
4
5 a= 2

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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

#include<iostream>
using namespace std;
int add(int num1, int num2)
{
return num1+num2;
}
int multiply(int num1, int num2)
{
return num1*num2;
}

21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62

void main()
{
int num1, num2, ch;
cout << Enter two numbers: ;
cin>>num1>>num2;
cout << Enter your choice: 1-Add, 2-Multiply<<endl;
cin>>ch;
if (ch==1)
{
int sum= add(num1, num2);
cout << Sum = <<sum;
}
else if (ch==2)
{
int product = product(num1, num2);
cout << Product= <<product;
}
else
{
cout << Wrong choice;
}
}

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++ 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="" dataurl=""> <span class="" title="" data-url="">
Post Comment

Notify me of follow-up comments by email.


Notify me of new posts by email.

Forw ard declarations C++ tutorial

Global Variables C++ tutorial

Search...

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 Pow ered by WordPress

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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

#include<iostream>
int glob_a = 1;
const glob_b = 2;
int function ()
{
glob_a=3;
return glob_b;
}
int main()
{
Using namespace std;
cout <<glob_a<<endl;
int x=function ();
cout <<glob_a<<endl;
cout <<x<<endl;
glob_a=4;
x=5;
cout <<glob_b<<endl;
cout <<x<<endl;
cout <<glob_a<<endl;
return 0;
}

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.
1
2
3
4
5
6
7
8
9
10
11

#include <iostream>
int var =1;
int main()
{
using namespace std;
int var = 2; // preferred over the global variable var
cout << "Local variable: " << var <<endl;
cout << "Global variable: " << ::var <<endl;
return 0;
}

Output:
Local variable: 2
Global variable: 1

However, you should avoid naming the local and global variables with the same name as this might cause some unexpected errors.

Global symbolic constants


Earlier we introduced the concept of symbolic constants, and defined them like this:
1 #define name constant

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:
1 #define Pi 3.1415
2 float area = Pi * r * r;

While this seems simple but it has it is its own problems.We can avoid these problems by using constant global variables.
1 const float pi = 3.1415, G = 6.67e-11, g = 9.8;
2 const long long int c= 3e8;

Now the symbolic constants will get initialized and can be used in all the functions without defining them again and again.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41

#include<iostream>
const float pi = 3.1415, G= 6.67e-11, g= 9.8;
float vol (long int r)
{
float volume = (4 * pi * r * r) / 3;
return volume;
}
float dens (float v, long int m)
{
float d = m / v;
return d;
}
float acc (long int r, long int m)
{
float g_app = (G * m) / (r * r);
return g_app;
}
float rel_acc (int g_app)
{
float rel_g = g_app / g;
return rel_g;
}
int main()
{
using namespace std;
long int rad, mass;
float volume, density, accel, rel_accel;
cout << Enter the radius of the new planet (in metres): <<endl;
cin >> rad;
cout << Enter the mass of the new planet (in kilograms): <<endl;
cin >> mass;
volume = vol (rad);
density = dens (volume, mass);
cout << The density of the planet is : <<density<<endl;
accel = acc(rad, mass);
cout << The acceleration due to gravitation is : <<accel<<endl;
rel_accel = (accel);
cout << Accelaration due to gravity is << rel_accel << times that on Earth;
return 0;
}

NOTE: It is tempting to use the global variables but it comes with its own set of cons, which we will discuss in
later tutorials

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="" dataurl=""> <span class="" title="" data-url="">
Post Comment

Notify me of follow-up comments by email.


Notify me of new posts by email.

Local Variables C++ Tutorial

Search...

ARCHIVES
June 2015
May 2015
April 2015
March 2015
February 2015
January 2015
April 2013

META
Register
Log in

More on global Variables

AlphaCpp.com All rights reserved. Theme by Colorlib Pow ered by WordPress

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 dont have to declare variables for different functions and link them as function
parameters etc.
Just one advice from our side: DONT!
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

#include<iostream>
int num=0;
using namespace std;
void main()
{
void make1();
void make2();
cout <<"Num= "<<num<<endl;
make1;
}
void make1()
{
num=1;
cout <<"Num= "<<num<<endl;
make2;
}
void make2()
{
num=2;
cout <<"Num= "<<num<<endl;
}

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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

#include<iostream>
int i=1;
using namespace std;
void result()
{
if (i==1)
cout <<"Success";
else
cout <<"Fail";
}
void change()
{
i=2;
}
void main()
{
change();
result();
}

Output:
Fail
In this program, it is clear that since value of the global variable can be changed so the program eventually failed.
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="" dataurl=""> <span class="" title="" data-url="">
Post Comment

Notify me of follow-up comments by email.


Notify me of new posts by email.

Global Variables C++ tutorial

Static Variables

Search...

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 Pow ered by WordPress

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)
1
2
3
4
5
6
7
8
9
10
11
12

void count ()
{
int num=1, i=1;
for (; i<3; i++, num++)
cout <<num<<endl;
} //num is destroyed
//i is destroyed
void main()
{
count();
count();
}

Output:
1
2
3
1
2
3
2)
1
2
3
4
5
6
7
8
9
10
11
12
13

void count ()
{
static int num=1; //these lines are executed only once
int i=1;
for (; i<3; i++, num++)
cout <<num<<endl;
} //num becomes inaccessible but is still in memory
//i is destroyed
void main()
{
count();
count();
}

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

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.
1 int multiple=0; //accessible in all files

1 static int single=0; //accessible in only the file it is declared

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="" dataurl=""> <span class="" title="" data-url="">
Post Comment

Notify me of follow-up comments by email.


Notify me of new posts by email.

More on global Variables

If and Else If C++ tutorial

Search...

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 Pow ered by WordPress

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
1
2
3
4
5
6
7
8
9
10
11
12

if (test expression)
{
statement;
//for single statement
}
//OR
if (test expression)
{
statements;
}

//for multiple statements

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:
1
2
3
4

if (a==1);
{
statement;
}

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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

#include<iostream>
void main()
{
int a, b, c, max;
cout << Enter three numbers: ;
cin>>a>>b>>c;
max=a;
if (max<b)
max=b;
if (max<c)

20
21 max=c;
22
23 cout << The greatest numbers out of <<a<< , <<b<< , <<c<< is <<max;
24 }

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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

void main()
{
Using namespace std;
char ch;
cout << Enter a character: <<endl;
cin>>ch;
if (ch== )
cout << You have entered space;
if (ch>= a && ch<= z)
cout << You have entered a lowercase letter;
if (ch>= A && ch<= Z)
cout << You have entered an uppercase letter;
if (ch>= 0 && ch<= 9)
cout << You have entered a digit;
}

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:
1 Enter a character:
2
3 3
4
5 You have entered a digit

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:
1
2
3
4
5
6
7
8
9
10
11
12
13

if (test expression)
{
Statement(s)1;
}
else
{
Statement(s)2;

14
15 }

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 ifs, the else statements pairs with the last if in the same block. So, to avoid unnecessary it is best to add
nested ifs in blocks.
1
2
3
4
5
6
7
8
9
10
11
12
13

Eg:
if (num<1000)
if (num>99)
threedig++;
else
if (num<10000)
fourdig++;

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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

if (num<1000)
{
if (num>99)
threedig++;
}
else
{
if (num<10000)
fourdig++;
}

But what is happening is quite different. The compiler translates it as


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

if (num<1000)
{
if (num>99)
threedig++;

else
if (num<10000)
fourdig++;
}

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:
1 if (num<1000)
2
3 {
4
5 if (num>99)
6

7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

{
threedig++;
}
}
else
{
if (num<10000)
{
fourdig++;
}
}

If else if ladder
Also, 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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

void main()
{
Using namespace std;
char ch;
cout << Enter a character: <<endl;
cin>>ch;
if (ch== )
cout << You have entered space;
else if (ch>= a && ch<= z)
cout << You have entered a lowercase letter;
else if (ch>= A && ch<= Z)
else cout << You have entered an uppercase letter;
else if (ch>= 0 && ch<= 9)
cout << You have entered a digit;
}

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++ 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="" dataurl=""> <span class="" title="" data-url="">
Post Comment

Notify me of follow-up comments by email.


Notify me of new posts by email.

Static Variables

The Sw itch Statement C++ Tutorial

Search...

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 Pow ered by WordPress

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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

switch ( expression )
{
case ( some constant 1 ) :
statement for constant 1 ;
break ;
case ( some constant 2 ) :
statement for constant 2 ;
break ;
default :
statement for default ;
break ;
}

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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

int main( )
{
cout << " Enter number of the ball " ;
int
ball
;
cin >> ball ;
switch (ball)
{
case 2 :
cout << " red " ;
break ;
case 4 :
cout << " yellow " ;
break ;
case 6 :
cout << " blue " ;
break ;
default :
cout << " wrong numbers 2 , 4 or 6 only. "
break ;
}
return 0 ;
}

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


consWhen 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.

proThough 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++ 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="" dataurl=""> <span class="" title="" data-url="">
Post Comment

Notify me of follow-up comments by email.


Notify me of new posts by email.

If and Else If C++ tutorial

Search...

ARCHIVES
June 2015
May 2015
April 2015
March 2015

Goto Statement C++ Tutorial

February 2015
January 2015
April 2013

META
Register
Log in

AlphaCpp.com All rights reserved. Theme by Colorlib Pow ered by WordPress

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
1
2
3
4
5
6
7
8
9

//Syntax
nameofthelabel
statement 1
.
.
.
statement 5
goto NameOfTheLabel ;

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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

#include <iostream>
using namespace std;
int main()
{
using namespace std;
again :
cout << "enter a number between 1 and 10";
int
number
;
cin
>> number ;
if ((number > 10 )||( number < 1))
{
goto again;
}
return 0 ;
}

// label ;

//this is the goto statement

Points to remember
1 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
1
2
3
4
5
6
7
8
9
10
11
12
13
14

{
.
goto alpha ;
.
.
alpha:

goto beta:
int x = 5 ;
beta:

example

// correct

// incorrect variable definition is coming in between

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
1 .

2
3
4
5
6
7
8
9
10
11

goto beta:
.
.
{
int x = 5 ;
.
.
}
beta:
}

// correct

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
1
2
3
4
5
6
7

{
goto alpha ;
.
.
.
alpha :
}

//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
1
2
3
4
5
6
7
8
9

{
goto alpha ;
.
.
.
alpha :
;

//right

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++ 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="" dataurl=""> <span class="" title="" data-url="">
Post Comment

Notify me of follow-up comments by email.


Notify me of new posts by email.

The Sw itch Statement C++ Tutorial

Introduction to loops

Search...

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 Pow ered by WordPress

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
loop
2 While
loop
3 Do-While loop
All 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

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="" dataurl=""> <span class="" title="" data-url="">
Post Comment

Notify me of follow-up comments by email.


Notify me of new posts by email.

Goto Statement C++ Tutorial

W hile Loop C++ Tutorials

Search...

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 Pow ered by WordPress

ALPHACPP.COM

While Loop C++ Tutorials


May 9, 2015 Aaryan Kapoor

A while loop works while the condition/s is/are true.

Syntax
1 while (test_expression)
2 statement;

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:
1
2
3
4
5
6

int i=1;
while (i<=10)
{
cout <<i <<endl;
i++;
}

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.
1
2
3
4
5
6
7

char ch= y;
while (ch== y)
{
statements;
cout << Do you want to continue (y/n): ;
cin>>ch
}

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 programmers choice.

1
2
3
4
5
6
7
8
9
10

int num;
long fact=1;
cout << Enter the number, whose factorial you want to find: ;
cin>>num;
while (num!=0)
{
fact=*num;
num--;
}
cout <<endl<<fact;

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 loop
If 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:
1
2
3
4
5

int a=1;
while (a<=10)
{
cout <<a<<endl;
}

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.
1
2
3
4
5
6

int num= 4;
while (num!=0);
{
cout <<num<<endl;
num--;
}

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.
1 long var =0;
2 while (++var < 10000) ; //use of pre increment to avoid infinite loop

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="" dataurl=""> <span class="" title="" data-url="">
Post Comment

Notify me of follow-up comments by email.


Notify me of new posts by email.

Introduction to loops

Do-W hile Loop C++ Tutorial

Search...

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 Pow ered by WordPress

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
1
2
3
4
5

do
{
statement ;
}
while (condition);

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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

#include <iostream>
using namespace std;
int main()
{
alpha:
int choice;
do
{
cout << option 1 - start " ;
cout << option 2 - load" ;
cin >> choice
;
}
while ((choice != 1 ) && (choice != 2))
goto alpha ;
return 0;
}

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++ 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="" dataurl=""> <span class="" title="" data-url="">
Post Comment

Notify me of follow-up comments by email.


Notify me of new posts by email.

W hile Loop C++ Tutorials

For Loop C++ Tutorial

Search...

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 Pow ered by WordPress

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
1 for (initialize; test; update)
2 statement;

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.
Lets take a look at an example of a for loop:
1 for (int i=1; i<=10; i++)
2 cout << i<<endl;

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.
1
2
3
4
5
6

int i=1;
while (i<=10)
{
cout <<i <<endl;
i++;
}

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:
1 for (int i=1; i<=10; i++);
2 cout <<i<<endl;

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 Loop


Using user entered values for test expression
eg:
1
2
3
4
5
6
7

//program to find sum of user entered number of natural numbers


int i,sum=0, num;
cout << Enter the number of terms whose sum you want to find<<endl;
cin>>num;
for (i=1; i<=num; i++)
sum=+i;
cout << Sum= <<sum;

Multiple initialization and/or update expression


1
2
3
4
5
6
7

int i,sum, num;


cout << Enter the number of terms whose sum you want to find<<endl;
cin>>num;
for (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 */
cout << Sum= <<sum;

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.
1
2
3
4
5
6
7
8

int i =1,sum=0, num;


cout << Enter the number of terms whose sum you want to find<<endl;
cin>>num;
for ( ; 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 */
cout << Sum= <<sum;

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.
1
2
3
4
5
6
7
8
9

int i,sum, num;


cout << Enter the number of terms whose sum you want to find<<endl;
cin>>num;
for (i=1, sum=0; i<=num; )
{
sum=+i;
i++;
}
cout << Sum= <<sum;

Omission of initialization and update expression


1
2
3
4
5
6
7
8
9

int i =1,sum=0, num;


cout << Enter the number of terms whose sum you want to find<<endl;
cin>>num;
for ( ; i<=num; )
{
sum=+i;
i++;
}
cout << Sum= <<sum;

Omission of test expression


Note: Whenever we omit the test expression it automatically turns into an infinite loop.
1 for (int i = 1; ; i++)
2 //this is an infinite loop

c++ tutorials
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="" dataurl=""> <span class="" title="" data-url="">
Post Comment

Notify me of follow-up comments by email.


Notify me of new posts by email.

Do-W hile Loop C++ Tutorial

Search...

ARCHIVES
June 2015
May 2015
April 2015
March 2015
February 2015
January 2015
April 2013

Break And Continue C++ Tutorial

META
Register
Log in

AlphaCpp.com All rights reserved. Theme by Colorlib Pow ered by WordPress

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.
1
2
3
4
5
6
7
8
9
10
11

while (expression/condition)
{
statement 1 ;
if
(some-condition)
break ;
statement 2;
}
statement 3;

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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

int main()
{
for (int i = 0 ; i < 100 ; i++)
cout <<i
cin >>count ;
if ( count == 0)
break ;
else
{
.
further statements ;
}
cout <<"program over " ;
return 0 ;
}

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.

Continue
continue 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.
1
2
3
4
5
6
7
8
9
10
11

int main( )
{
for (int i = 0 ; i < 6 ; i++ )
{
if (i == 2 )
continue ;
//brackets not used for if condition since only one statement is contained in it.
else
cout << i <<endl ;
}
return 0 ;
}

here the output will be


1
3
4
5

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 continue


Lets apply break to the previous example, but this time we will use break instead of continue
1
2
3
4
5
6
7
8
9
10
11

int main( )
{
for (int i = 0 ; i < 6 ; i++ )
{
if (i == 2 )
break ;
else
cout << i <<endl ;
}
return 0 ;
}

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="" dataurl=""> <span class="" title="" data-url="">
Post Comment

Notify me of follow-up comments by email.


Notify me of new posts by email.

For Loop C++ Tutorial

Comma and conditional operators Cpp tutorial

Search...

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 Pow ered by WordPress

ALPHACPP.COM

Arrays C++ Tutorial


May 14, 2015 Udit Pandoh

Arrays
Arrays 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.
1
2
3
4
5
6
7

int
int
int
int
int
int
int

day1;
day2;
day3;
day4;
day5;
day6;
day7;

doesnt 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.
1
2
3
4
5
6

data-type name[size of the array ]


eg.
int
weatherdata[12] ;
char class [10]

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
1
2
3
4
5
6

//first we declare an array that stores roll numbers of 10 students.


int 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 ;

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.
1
2
3
4
5
6

for eg
int rollnumber [10] ;
rollnumber [o] = 1 ;
rollnumber [1] = 9 ;
cout <<rollnumber [0] + rollnumber[1];

will give an output 10 as rollnumber[0] holds the value 1 and rollnumber[1] value 9.

Initializer list
But 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
1 int marks[3] = {80,67,90} ;

consider this.

1 int marks[5] = {80,67,90} ;

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 Size
If we are initializing an array of elements using an initializer list, the compiler can figure out the size of the array for us.
1 int marks[] = { 19, 21, 37, 46, 4 }; // here we declared an array of 5 elements.

Important
keep in mind that the size of an array cant vary it has to constant i.e the following is wrong.
1 int size = 3;
2 int alpha[size] = {0,1,2}

//wrong size needs to be constant

but when initializing a variable you can do this


1 int number
= 0;
2 int alpha[3]
= {0,1,2} // correct because number of variables are constant.
3 alpha[number] = 6 ;
//valid

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="" dataurl=""> <span class="" title="" data-url="">
Post Comment

Notify me of follow-up comments by email.


Notify me of new posts by email.

Comma and conditional operators Cpp tutorial

Search...

Guess the output ++

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 Pow ered by WordPress

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.
1
2
3
4
5
6
7
8
9
10
11

//finding the greatest integer


int ar[10], great=0;
cout <<"Enter 10 numbers: ">>endl;
for (int i=0; i<10; i++)
cin>>ar[i]; //takes input from ar[0] to ar[9]
for (int j=0; j<10; j++)
{
if (ar[j]>great) //checks for all the values in arrays
great= ar[j]; //stores the greatest value in the loop
}
cout <<"Greatest number: "<<great;

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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

//input and output data of three employees


int ecode[3], salary[3], exp[3];
for (int i =0; i<3; i++)
{
cout <<"Enter the data of "<<i+1<<" employee"<<endl;
cout <<"Enter ecode: ";
cin>>ecode[i];
cout <<"Enter salary: ";
cin>>salary[i];
cout <<"Enter experience: ";
cin>>exp[i]
}
for (int j=0; j<3; j++)
{
cout <<j+1<<" employee"<<endl;
cout <<"Ecode: "<<ecode[j]<<endl;
cout <<"Salary: "<<salary[j]<<endl;
cout <<"Experience: "<<exp[j]<<endl;
}

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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

//Makes the user enter a sentence using multidimensional array.


char ch[15][20];
int i=0, j=0;
cout <<"Enter a sentence (ending by full stop/period)"<<endl;
do
{
do
{
cin>>ch[i][j];
j++;
}while (ch[i][j-1]!=32 || ch[i][j-1]!=46); //32 is ASCII code for space
i++;
}while (ch[i-1][j-1]!=46); //ASCII code for full stop/ period
//for printing the sentence
i=0;
j=0;
cout <<"You entered: ";
do
{
do
{
cout <<" "<<ch[i][j];

23 j++;
24 }while (ch[i][j-1]!=32 || ch[i][j-1] = 46);
25 i++;
26 }while (ch[i-1][j-1]!=46);

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="" dataurl=""> <span class="" title="" data-url="">
Post Comment

Notify me of follow-up comments by email.


Notify me of new posts by email.

Float and Double

Search...

ARCHIVES
June 2015

History of java

May 2015
April 2015
March 2015
February 2015
January 2015
April 2013

META
Register
Log in

AlphaCpp.com All rights reserved. Theme by Colorlib Pow ered by WordPress

ALPHACPP.COM

Enumerated Type C++ Tutorial


May 29, 2015 Udit Pandoh

Lets 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.
1
2
3
4
5
6
7

...
int
cout
cin
if
cout
...

starsign ;
<< " 1 is for aquarius " ;
>> starsign ;
( starsign == 1 )
<< aquarius ;

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? Wouldnt that be
awesome!
Then I could have written the above program like this
1
2
3
4
5
6
7
8

...
int
starsign ;
cout << " 1 is for aquarius " ;
cin
>> starsign ;
if
( starsign == aquarius )
cout << aquarius ;
...

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
1
2
3
4
5

enum nameofdatabase
{
enumerators each separated with a comma
} ;
nameofdatabase nameofvariable ;

lets consider an example for lets say the mood of a person.


1
2
3
4
5
6
7

enum mood
{
happy ,
sad ,
lonely // for maximum compatibility, the last enumerator should not have a comma
} ;
mood Udit = happy ;

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
1 int something = 1 ;

similarly, we will say


1 mood udit = happy ;

Giving integral values to each enumerator

most of the times we dont even need to do this since compiler automatically assigns integral values starting from 0 to each enumerator.
1
2
3
4
5
6

enum color
{
red , // aggigned value 0 by default
blue , // aggigned value 1 by default
green
// aggigned value 2 by default
};

Still sometimes we may need to change the integer values, we could do it like this
1
2
3
4
5
6

enum color
{
red = 3, // aggigned value 3
blue ,
// aggigned value 4 automatically
green = 5 // aggigned value 5
};

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 nondefined 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="" dataurl=""> <span class="" title="" data-url="">
Post Comment

Notify me of follow-up comments by email.


Notify me of new posts by email.

Concept of java interpreters and compilers

Using Enumerated Type

Search...

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 Pow ered by WordPress

ALPHACPP.COM

Using Enumerated Type


May 29, 2015 Udit Pandoh

Since you are now familiar with the concept, consider the eg. and guess its
output.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

#include "stdafx.h" // only to be used for visual studios.


#include <iostream>
using namespace std;
void main()
{
enum color
{
COLOR_BLACK ,
COLOR_RED ,
COLOR_BLUE ,
COLOR_GREEN ,
COLOR_WHITE ,
COLOR_CYAN ,
COLOR_YELLOW,
};
color color;
color = COLOR_RED ; // will cause compiler error
cout << color;
}

The output of the program will be 1

Another case
Lets use an enumerator type in another program. Lets say I have created a text adventure game here is how I can start it.
1
2
3
4
5
6
7
8
9
10
11
12
13
14

enum option
{
play ,
stop ,
pause
} ;
cout << " Enter the option" ;
int
option ;
cin
>>option ;
if
(option == play )
{
..
the game codes
}

See ? using enum made my code more neat and understandable to a human, instead of writing
1 if (option == 0)
2
3 //I used
4
5 if (option == play )

Thus, Enumerated types are incredibly useful for code documentation and readability purposes.

Memory Allocation
Enum types are considered part of the integer family of types, and its 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.

Lets consider some more examples to make sure you have understood
everything.
1 ) In this example, I am adding two numbers but indirectly using enum.
1 #include "stdafx.h" // only to be used for visual studios.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

#include "stdafx.h" // only to be used for visual studios.


#include <iostream>
using namespace std;
void main()
{
enum numbers
{
zero ,
one ,
two ,
three,
four ,
five
};
int sum = three + four;
cout << sum ;
}

Since three and four meant numbers 3 and 4 respectively due to use of enum, writing this
1 int sum = three + four ;

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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

#include "stdafx.h" // only to be used for visual studios.


#include <iostream>
using namespace std;
enum mood
{
happy,
sad,
};
void alpha(mood udit)
{
if (udit == happy)
cout << "Happy";
else if (udit == sad)
cout << "Sad";
else
cout << "Who knows!";
}
void main()
{
alpha(happy );
}

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

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="" dataurl=""> <span class="" title="" data-url="">
Post Comment

Notify me of follow-up comments by email.


Notify me of new posts by email.

Enumerated Type C++ Tutorial

Typedef C++ Tutorial

Search...

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 Pow ered by WordPress

ALPHACPP.COM

Introduction to String C++ tutorial


May 29, 2015 Udit Pandoh

The first program that we wrote was hello world


1
2
3
4
5
6
7

#include <iostream>
using namespace std ;
int main()
{
std::cout << "Hello, world " << std::endl;
return 0;
}

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
1 cout << " Hello world " ;

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.
1 #include <string>

Just like your normal variables, you can initialize strings and change its value at any time, even add them !
1
2
3
4
5

string
name =
cout
name =
cout

name ;
" Alpha Cpp - c++ tutorial rocks " ;
<< name ;
" It is really awesome " ;
<<endl <<name ;

The output of the above program will be


1 Alpha Cpp - c++ tutorial rocks
2 It is realy awesome

Input
When 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, lets use this in a program.
1
2
3
4
5

#include "stdafx.h" // only to be used for visual studio.


#include <iostream>
#include <string>
using namespace std;
void main()

6
7
8
9
10
11
12

{
string firstname, lastname, fullname;
firstname = " Udit";
lastname = " Pandoh ";
fullname = firstname + lastname;
cout << fullname;
}

Using getline
As 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.
1 string name ;
2 name = " Alpha Cpp - c++ tutorial rocks " ;
3 getline(cin,name) ;

Length of a string
Sometimes it is useful if we could know the length of a string, it can be determined by using the following function
1 stringname.length()

lets use this in an example


1
2
3
4
5
6

using namespace std ;


void main( )
{
string name = " Udit " ;
cout << name << " has " << myName.length() <<" characters";
}

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-

url=""> <span class="" title="" data-url="">


Post Comment

Notify me of follow-up comments by email.


Notify me of new posts by email.

Typedef C++ Tutorial

Next Post

Search...

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 Pow ered by WordPress

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.
1 float pi = 3.145

Well, since we know C++, we know that float stands for fraction , but what if someone else views the program wouldnt it better if we could say.
1 fraction pi = 3.145

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
1 typedef typetoalias alias ;

To declare a typedef, simply use the typedef keyword, followed by the type to alias, followed by the alias name
Lets consider an example.
1 typedef float fraction ; // define fraction as an alias for type float
2 double pi = 3.145 ;
// The following statements are same:
3 fraction pi = 3.145 ;

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 program


Typedefs 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.
1 int bike ;

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.
1 typedef int bike ;
2 bike speed = 110 ;

Making the editing easier


When 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.
1
2
3
4
5
6

//example 1
int day 1
int day 2
int day 3
int day 7
int day 5

=
=
=
=
=

10
11
9.8
50
6.5

;
;
;
;
;

first lets type the better version of above statements using typedef

1
2
3
4
5
6
7
8
9
10

//
example 2
typedef int temp ;
typedef int attendance ;
temp day 1
=
temp day 2
=
temp day 3
=
attendance day 7 =
temp day 5
=

10.7
11.8
9.8
50
6.5

;
;
;
;
;

Using the typedef it becomes very easy now to edit the code
1)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.
1
2
3
4
5
6

//example 1
int day 1
int day 2
int day 3
int day 7
int day 5

=
=
=
=
=

10
11
9.8
50
6.5

;
;
;
;
;

We could have edited the code in example 2 like this,


1
2
3
4
5
6
7
8
9
10

//
example 2
typedef int temp ;
typedef int attendance ;
temp day 1
=
temp day 2
=
temp day 3
=
attendance day 7 =
temp day 5
=

10.7
11.8
9.8
50
6.5

;
;
;
;
;

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.

Using Enumerated Type

Introduction to String C++ tutorial

Search...

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 Pow ered by WordPress

Вам также может понравиться