C++ Tutorials
C++ Tutorials
else
In this article, you will learn to create decision making statements in a C++
program using different forms of if..else statement.
C++ if Statement
if (testExpression)
// statements
Flowchart of if Statement
#include <iostream>
using namespace std;
int main()
{
int number;
cout << "Enter an integer: ";
cin >> number;
Output 1
Enter an integer: 5
Enter a number: -5
C++ if...else
The if else executes the codes inside the body of if statement if the test
expression is true and skips the codes inside the body of else.
If the test expression is false, it executes the codes inside the body of else statement
and skips the codes inside the body of if.
#include <iostream>
using namespace std;
int main()
{
int number;
cout << "Enter an integer: ";
cin >> number;
if ( number >= 0)
{
cout << "You entered a positive integer: " << number << endl;
}
else
{
cout << "You entered a negative integer: " << number << endl;
}
Output
Enter an integer: -4
The nested if...else statement allows you to check for multiple test expressions
and execute different codes for more than two conditions.
Syntax of Nested if...else
if (testExpression1)
else if(testExpression2)
else if (testExpression 3)
else
}
Example 3: C++ Nested if...else
// Program to check whether an integer is positive, negative or zero
#include <iostream>
using namespace std;
int main()
{
int number;
cout << "Enter an integer: ";
cin >> number;
if ( number > 0)
{
cout << "You entered a positive integer: " << number << endl;
}
else if (number < 0)
{
cout<<"You entered a negative integer: " << number << endl;
}
else
{
cout << "You entered 0." << endl;
}
Output
Enter an integer: 0
You entered 0.
Conditional/Ternary Operator ?:
A ternary operator operates on 3 operands which can be used instead of
a if...elsestatement.
if ( a < b ) {
a = b;
else {
a = -b;
a = (a < b) ? b : -b;
The ternary operator is more readable than a if...else statement for short
conditions.
C++ Functions
In this article, you'll learn everything about functions in C++; what type of functions
are there, how to use them with examples.
In programming, function refers to a segment that groups code to perform a specific
task.
1. Library Function
2. User-defined Function
Library Function
Library functions are the built-in function in C++ programming.
Programmer can use library function by invoking function directly; they don't need to
write it themselves.
int main()
{
double number, squareRoot;
cout << "Enter a number: ";
cin >> number;
Output
Enter a number: 26
In the example above, sqrt() library function is invoked to calculate the square root
of a number.
Notice code #include <cmath> in the above program. Here, cmath is a header file.
The function definition of sqrt()(body of that function) is present in the cmath header
file.
You can use all functions defined in cmath when you include the content of
file cmath in this program using #include <cmath> .
Every valid C++ program has at least one function, that is, main() function.
User-defined Function
C++ allows programmer to define their own function.
A user-defined function groups code to perform a specific task and that group of
code is given a name(identifier).
When the function is invoked from any part of program, it all executes the codes
defined in the body of function.
How user-defined function works in C Programming?
When a program begins running, the system calls the main() function, that is, the
system starts executing codes from main() function.
Then, control of the program moves back to the main function where the code after
the call to the function_name() is executed as shown in figure above.
#include <iostream>
using namespace std;
int main()
{
int num1, num2, sum;
cout<<"Enters two numbers to add: ";
cin >> num1 >> num2;
// Function call
sum = add(num1, num2);
cout << "Sum = " << sum;
return 0;
}
// Function definition
int add(int a, int b)
{
int add;
add = a + b;
// Return statement
return add;
}
Output
-4
Sum = 4
Function prototype (declaration)
If a user-defined function is defined after main() function, compiler will show error. It
is because compiler is unaware of user-defined function, types of argument passed
to function and return type.
You can see that, there is no body of function in prototype. Also, there are only
return type of arguments but no arguments. You can also declare function prototype
as below but it's not necessary to write arguments.
Function Call
To execute the codes of function body, the user-defined function needs to be
invoked(called).
In the above program, add(num1,num2); inside main() function calls the user-defined
function.
Function Definition
The function itself is referred as function definition. Function definition in the above
program is:
// Function definition
int add(int a,int b)
int add;
add = a + b;
return add;
When the function is called, control is transferred to the first statement of the function
body.
When all codes inside function definition is executed, control of program moves to
the calling program.
In the above example, two variables, num1 and num2 are passed to function during
function call. These arguments are known as actual arguments.
The value of num1 and num2 are initialized to variables a and b respectively. These
arguments a and b are called formal arguments.
The numbers of actual arguments and formals argument should be the same.
(Exception: Function Overloading)
The type of first actual argument should match the type of first formal argument.
Similarly, type of second actual argument should match the type of second formal
argument and so on.
You may call function a without passing any argument. The number(s) of argument
passed to a function depends on how programmer want to solve the problem.
You may assign default values to the argument. These arguments are known
as default arguments.
In the above program, both arguments are of int type. But it's not necessary to have
both arguments of same type.
Return Statement
A function can return a single value to the calling program using return statement.
In the above program, the value of add is returned from user-defined function to the
calling program using statement below:
return add;
Notice that the variable returned, i.e., add is of type int and sum is also of int type.
Also, notice that the return type of a function is defined in function declarator int
add(int a, int b). The int before add(int a, int b) means the function should return a
value of type int.
C++ Structures
In this article, you'll learn about structures in C++ programming; what is it, how to
define it and use it in your program.
Structure is a collection of variables of different data types under a single name. It is
similar to a class in that, both holds a collecion of data of different data types.
For example: You want to store some information about a person: his/her name,
citizenship number and salary. You can easily create different variables name, citNo,
salary to store these information separately.
However, in the future, you would want to store information about multiple persons.
Now, you'd need to create different variables for each information per person: name1,
citNo1, salary1, name2, citNo2, salary2
You can easily visualize how big and messy the code would look. Also, since no
relation between the variables (information) would exist, it's going to be a daunting
task.
A better approach will be to have a collection of all related information under a single
name Person, and use it for every person. Now, the code looks much cleaner,
readable and efficient as well.
This collection of all related information under a single name Person is a structure.
Then inside the curly braces, you can declare one or more members (declare
variables inside curly braces) of that structure. For example:
struct Person
char name[50];
int age;
float salary;
};
Here a structure person is defined which has three members: name, age and salary.
The structure definition is only the blueprint for the creating of variables. You can
imagine it as a datatype. When you define an integer as below:
int foo;
The int specifies that, variable foo can hold integer element only. Similarly, structure
definition only specifies that, what property a structure variable holds when it is
defined.
Person bill;
When structure variable is defined, only then the required memory is allocated by the
compiler.
Considering you have either 32-bit or 64-bit system, the memory of float is 4 bytes,
memory of int is 4 bytes and memory of char is 1 byte.
Suppose, you want to access age of structure variable bill and assign it 50 to it. You
can perform this task by using following code below:
bill.age = 50;
#include <iostream>
using namespace std;
struct Person
{
char name[50];
int age;
float salary;
};
int main()
{
Person p1;
Output
Enter age: 27
Displaying Information.
Age: 27
Salary: 1024.4
Here a structure Person is declared which has three members name, age and salary.
Inside main() function, a structure variable p1 is defined. Then, the user is asked to
enter information and data entered by user is displayed.
C++ Arrays
In this article, you will learn to work with arrays. You will learn to declare, initialize
and, access array elements in C++ programming.
In programming, one of the frequently arising problem is to handle numerous data of
same type.
Consider this situation, you are taking a survey of 100 people and you have to store
their age. To solve this problem in C++, you can create an integer array having 100
elements.
An array is a collection of data that holds fixed number of values of same type. For
example:
int age[100];
Here, the age array can hold maximum of 100 elements of integer type.
The size and type of arrays cannot be changed after its declaration.
For example,
float mark[5];
Here, we declared an array, mark, of floating-point type and size 5. Meaning, it can
hold 5 floating-point values.
Suppose you declared an array mark as above. The first element is mark[0], second
element is mark[1] and so on.
Few key notes:
Arrays have 0 as the first index not 1. In this example, mark[0] is the first element.
If the size of an array is n, to access the last element, (n-1) index is used. In this
example, mark[4] is the last element.
Suppose the starting address of mark[0] is 2120d. Then, the next address, a[1], will
be 2124d, address of a[2] will be 2128d and so on. It's because the size of float is 4
bytes.
Here,
mark[0] is equal to 19
mark[1] is equal to 10
mark[2] is equal to 8
mark[3] is equal to 17
mark[4] is equal to 9
int main()
{
int numbers[5], sum = 0;
cout << "Enter 5 numbers: ";
return 0;
}
Output
Enter 5 numbers: 3
Sum = 18
Things to remember when working with arrays in C++
Suppose you declared an array of 10 elements. Let's say,
int testArray[10];
If you try to access array elements outside of its bound, let's say testArray[14], the
compiler may not show any error. However, this may cause unexpected output
(undefined behavior).
C++ supports object-oriented (OO) style of programming which allows you to divide
complex problems into smaller sets by creating objects.
Object is simply a collection of data and functions that act on those data.
C++ Class
Before you create an object in C++, you need to define a class.
We can think of class as a sketch (prototype) of a house. It contains all the details
about the floors, doors, windows etc. Based on these descriptions we build the
house. House is the object.
As, many houses can be made from the same description, we can create many
objects from a class.
The body of class is defined inside the curly brackets and terminated by a semicolon
at the end.
class className
// some data
// some functions
};
public:
void function1()
{ data1 = 2; }
float function2()
{
data2 = 3.5;
return data2;
}
};
This class has two data members: data1 and data2 and two member
functions: function1()and function2().
The private keyword makes data and functions private. Private data and functions
can be accessed only from inside the same class.
The public keyword makes data and functions public. Public data and functions can
be accessed out of the class.
Here, data1 and data2 are private members where as function1() and function2()
are public members.
If you try to access private data from outside of the class, compiler throws error. This
feature in OOP is known as data hiding.
C++ Objects
When class is defined, only the specification for the object is defined; no memory or
storage is allocated.
To use the data and access functions defined in the class, you need to create
objects.
You can create objects of Test class (defined in above example) as follows:
class Test
{
private:
int data1;
float data2;
public:
void function1()
{ data1 = 2; }
float function2()
{
data2 = 3.5;
return data2;
}
};
int main()
{
Test o1, o2;
}
In the above class Test, data1 and data2 are data members
and function1() and function2() are member functions.
o2.function1();
This will call the function1() function inside the Test class for objects o2.
o1.data2 = 5.5;
It is important to note that, the private members can be accessed only from inside
the class.
So, you can use o2.function1(); from any function or class in the above example.
However, the code o1.data2 = 5.5; should always be inside the class Test.
class Test
{
private:
int data1;
float data2;
public:
void insertIntegerData(int d)
{
data1 = d;
cout << "Number: " << data1;
}
float insertFloatData()
{
cout << "\nEnter data: ";
cin >> data2;
return data2;
}
};
int main()
{
Test o1, o2;
float secondDataOfObject2;
o1.insertIntegerData(12);
secondDataOfObject2 = o2.insertFloatData();
Number: 12
In this program, two data members data1 and data2 and two member
functions insertIntegerData() and insertFloatData() are defined under Test class.
o1.insertIntegerData(12);
Then, the insertFloatData() function for object o2 is called and the return value from
the function is stored in variable secondDataOfObject2 using:
secondDataOfObject2 = o2.insertFloatData();
In this program, data2 of o1 and data1 of o2 are not used and contains garbage
value.
C++ Inheritance
In this article, you'll learn everything about inheritance in C++. More specifically, what
is inheritance and different ways to implement it with examples.
Inheritance is one of the key features of Object-oriented programming in C++. It
allows user to create a new class (derived class) from an existing class(base class).
The derived class inherits all the features from the base class and can have
additional features of its own.
Since, all of the characters are persons, they can walk and talk. However, they also
have some special skills. A maths teacher can teach maths, a footballer can play
football and a businessman can run a business.
You can individually create three classes who can walk, talk and perform their
special skill as shown in the figure below.
In each of the classes, you would be copying the same code for walk and talk for
each character.
If you want to add a new feature - eat, you need to implement the same code for
each character. This can easily become error prone (when copying) and duplicate
codes.
It'd be a lot easier if we had a Person class with basic features like talk, walk, eat,
sleep, and add special skills to those features as per our characters. This is done
using inheritance.
Using inheritance, now you don't implement the same code for walk and talk for each
class. You just need to inherit them.
So, for Maths teacher (derived class), you inherit all features of a Person (base
class) and add a new feature TeachMaths. Likewise, for a footballer, you inherit all
the features of a Person and add a new feature PlayFootball and so on.
... .. ...
};
... .. ...
};
.... .. ...
};
The derived class appears with the declaration of a class followed by a colon, the
keyword public and the name of base class from which it is derived.
Since, MathsTeacher and Footballer are derived from Person, all data member and
member function of Person can be accessible from them.
class Person
{
public:
string profession;
int age;
int main()
{
MathsTeacher teacher;
teacher.profession = "Teacher";
teacher.age = 23;
teacher.display();
teacher.teachMaths();
Footballer footballer;
footballer.profession = "Footballer";
footballer.age = 19;
footballer.display();
footballer.playFootball();
return 0;
}
Output
My age is: 23
I can walk.
I can talk.
My age is: 19
I can walk.
I can talk.
In this program, Person is a base class, while MathsTeacher and Footballer are
derived from Person.
Person class has two data members - profession and age. It also has two member
functions - walk() and talk().
Both MathsTeacher and Footballer can access all data members and member
functions of Person.
Since, it has access to Person's data members, profession and age of teacher is set.
This data is displayed using the display() function defined in the Person class. Also,
the teachMaths() function is called, defined in the MathsTeacher class.
In the above example, the base class Person has been inherited public-ly
by MathsTeacherand Footballer.
C++ Pointers
In this article, you'll learn everything about pointers. You'll learn how values are
stored in the computer and how to access them using pointers.
Pointers are powerful features of C++ that differentiates it from other programming
languages like Java and Python.
Pointers are used in C++ program to access the memory and manipulate the
address.
Address in C++
To understand pointers, you should first know how data is stored on the computer.
Each variable you create in your program is assigned a location in the computer's
memory. The value the variable stores is actually stored in the location assigned.
To know where the data is stored, C++ has an & operator. The & (reference)
operator gives you the address occupied by a variable.
int main()
{
int var1 = 3;
int var2 = 24;
int var3 = 17;
cout << &var1 << endl;
cout << &var2 << endl;
cout << &var3 << endl;
}
Output
0x7fff5fbff8ac
0x7fff5fbff8a8
0x7fff5fbff8a4
Note: You may not get the same result on your system.
Notice that first address differs from second by 4-bytes and second address differs
from third by 4-bytes.
This is because the size of integer (variable of type int) is 4 bytes in 64-bit system.
Pointers Variables
C++ gives you the power to manipulate the data in the computer's memory directly.
You can assign and de-assign any space in the memory as you wish. This is done
using Pointer variables.
Pointers variables are variables that points to a specific address in the memory
pointed by another variable.
How to declare a pointer?
int *p;
OR,
int* p;
The statement above defines a pointer variable p. It holds the memory address
To get the value stored in the memory address, we use the dereference operator (*).
For example: If a number variable is stored in the memory address 0x123, and it
contains a value 5.
The reference (&) operator gives the value 0x123, while the dereference
(*) operator gives the value 5.
Note: The (*) sign used in the declaration of C++ pointer is not the dereference
pointer. It is just a similar notation that creates a pointer.
#include <iostream>
using namespace std;
int main() {
int *pc, c;
c = 5;
cout << "Address of c (&c): " << &c << endl;
cout << "Value of c (c): " << c << endl << endl;
*pc = 2;
cout << "Address of c (&c): " << &c << endl;
cout << "Value of c (c): " << c << endl << endl;
return 0;
}
Output
Value of c (c): 5
Value of c (c): 2
Explanation of program