C++ is one of the most versatile languages in the world. It is used nearly everywhere for everything… systems programming (operating systems, device drivers, database engines, embedded, Internet of Things, etc.)

Enter Header Image Headline Here

Monday, 24 April 2017

C++ Function Prototype (declaration)

                        C++ 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-defines function, types of argument passed to function and return type.

In C++, the function prototype is a declaration of function without its body to give compiler information about the user-defined function. Function prototype in the above example is : 


int add(int , int);


You can see that, there is no body of the 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.


 int add(int a, int b);

Note: It is not necessary to define prototype if the user- defined function exixts before main() function.

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.

The function returns an integer which is stored in variable add.


Function Defination


The function itself is referred as function definition. Function definition in the above program is : 
























When the function is called, control is transfered to the first statement of the function body.

Then, other statements in function body are executed sequentially.

When all codes insides function is executed , control of program moves to the calling program.


Passing Arguments to Function

In programming , argument (parameter) refer to the data which is passed to a function (function definition) while calling it.

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 initilized to variables a and b respectively. These arguments a and b called formal arguments.

This is demonstrated in figure below : 


























Notes on passing arguments

The numbers of actual arguments and formals 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 program.

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 ahve 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 returned from user-defined function to the calling program using statement below:

return add;  

The figur below demonstrates the working of return statement.


























In  the above program, the value of add inside user-defined function is returned to the calling function. The value is then stored to a variable sum.

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 value of type int.

If no Value is returned to thr calling function then, void should be used.


Saturday, 22 April 2017

C++ Functions

                                         C++  Functions


In Programming, function refers ti a segment that groups code to perform a specific task. 


Depending on whether a function is predefined or created by the programmer, there are two types of function: 

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.


Example :   Library  Function



















Output :



In the example above , squrt() library function is invoked to calculate the square root of number.


Notice code #include<cmath> in the above program,Here, cmath is a header file. The function definition of Sqrt() (body type function) is present in the cmat   header file. 


You can use all function defined in cmath when you include hte 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 group code to perform a specific task and that group of codes defined in the body of function.


How user-defined function works in C Programming ?


When  a program begins runnung, the system calls the main() function, that is, the system Starts executing codes from main() function.  

When control of the program reaches to function name() inside main(), it moves to void function name() and all codes inside void function name () is executed.

Then, control of the program moves back to the main function where the code after the call to the function name () is executed .


Example User Defined Function  :

C++ program to add two integers, Make a function add()     to add integers and display sum in       main () function.






















Output  :






Sunday, 16 April 2017

C++ Inheritance

                                                          C++  INHERITANCE


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.

Why inheritance should be used?

Suppose in your game, you want three characters - a maths teacher, a footballer, and a businessman.
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 a 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, new you don,t implement the same code for the walk and talk for each class. You just need to inherit them.

So, for Maths teacher (derived class), You inherit all feature os a Person (base class ) and add a new feature Teach Maths. Likewise., for a footballer, you inherit all the features of a person and add a new feature Play Football and so on.

This makes your code cleaner, understandable and extendable.


Implementation of inheritance in C++ Programming:

















In above ex. , class Person is a base class and classes Maths Teacher and Footballer are the derived from Person.


The derived class appears with the declaration of a class followed by a colon, the keyword public and name of a base class from which it is derived.

Since Maths Teacher and Footballer are derived from Person, all data member and a member function of Person can be accessible from them.


Access specifiers in Inheritance:

When creating a derived class from a base class, you can use different access specifiers to inherit the data member of the base class.

These can be public, protected or private.

in the above example, the base class Person has been inherited public-ly by MathsTeacher and Footballer.


Member Function Overriding Inheritance:


Suppose, a base class and derived class has a member function with same name and arguments.

If you create an object of the derived class and try to access that member function, the function in derived is only invoked.

The member function of derived class overrides the member function of the base class.





Saturday, 15 April 2017

C++ Multidimensional Arrays

                              C++ Multidimensional Arrays


In C++, you can create an array of an array known as multidimensional array. 

For Example : 


int   x [3] [4];

Here, x is two dimensionall array . it can hold a maximum of 12 elements.

You can think this array as table with  3 rows and each rows has 4 columns .

for example. :

Three-dimensional array also works in a similar way. For example :


float x [2][4][3];

This array x can hold a maximum of 24 elements. You can think this example as : Each of the 2 elements can hold 4 elements, which makes 8 elements and each of those 8 elements can hold 3 elements. Hence, total number of elements this array can hold is 24.


Multidimensional Array Initialisation :

you can initialise a multidimmensional array in more than one way.

Initialisation of two dimensional array:


int test[2][3] = { 2, 4, -5, 9, 0, 9};

Better way to initialise this array with same array elements as above.

int  test[2][3]  = { { 2, 4, 5,},{9, 0, 0}};

Initialisation of  three  dimensional  array

int test [2][3][4] = {3, 4, 2, 3, 0,, -3, 9, 11, 23, 2, 13, 4, 56, 3, 5, 9, 3, 5, 5, 1, 4, 9};

Better way to initialise this array with same elements as above.

Example - Two Dimensional Array

C++ program to store temperature of two different cities for a week and display it.




































Output :

































Example - Three Dimensional Array

C++ Program to store value entered by user in three dimensional 
array and display it.





































Output :

Enter 12 value:











































C++ Pointer and Arrays

                                 C++ Pointer and Arrays


Pointers are the variables that hold address. Not only can pointers store address of a single variable,it can also store address of cells of an array.

Consider this example. :



























Suppose, pointer needs to point to the fourth element of an array, that is hold address of fourth array element in above case.

Since ptr points to the third element in the above example, ptr. + 1 will point to the fourth element.

You may think , ptr +1 gives you the address of next byte to the ptr. But it's not correct.

This is because pointer ptr is a pointer to an int and size of int is fixed for a operating system (size in int is 4 byte of 64-bit operating system). Hence, the address between ptr and ptr+1 differs by 4 bytes.

If pointer ptr was pinter to char then, the address between ptr+1 would have differed by 1 byte since size of a character is 1 byte.

Example : Pointer and Arrays

C++ Program to display address of elements of an array using both array and pointers


           #include <iostream>


























Output :
In the above program, a different pointer ptr is used for display the address of array elements arr.

But, array element can be accessed using pointer notation by using same array name arr.                  

 For example : 















Example : Pointer and Arrays

C++ program to display address of array elements using pointer. notation.






















Output :





















You know that, pointer ptr holds the address and expression *ptr gives the value stored in the address.

Simillary, you can get the value stored in the pointerptr + 1 using*(ptr+1).

Consider this code below : 

int ptr[5] = {3, 4, 5, 5, 3};

  • &ptr[0] is equal to ptr and *ptr is equal to ptr[0]
  • &ptr[1] is equal to ptr + 1 and *(ptr+1) is equal to ptr[1] 
  • &ptr[2] is equal to ptr + 2 and *(ptr+2) is equal to ptr[2] 
  • &ptr[i] is equal to ptr + i and *(ptr+i) is equal to ptr[i] 

Example: C++ pointer and Array


C++ Program to insert and display data entered by using pointers notation.




























Output : 







C++ Pointer

                                            C++ Pointer


Pointers are powerful feature 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.

If var is a variable then, & var gives the address of that variable.

Example:  Adress in C++









Output:














Note:   


The 0x in the beginning represents the address is in hexadecimal form.

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.

Pointer variable are variables that points to a specific address in the memory pointed by another variable.

How to declare a pointer?














The statement above defines a pointer variable p. It holds the memory address.

The asterisk is a dereference operator which means pointer to.

Here, pointer p is a pointer to int i.e., it is pointing to an integer value in the memory address.

C++ Arrays

                                           C++ Arrays


In programming, one of the frequently arising problem is to handle numerous data of same type.

Consider this situation, you are taking a survay of 100 people and you have to store theirage. To Solve this problem in C++ , you can create an integer array having 100 elements.

An array is a collection of data yhat 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.

This size and type of array cannot be changed after its declaration.

How to Declare an array in C++ ?

dataType arrayName[arraySize];

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.

Elements of an Array and How to access the,?


You can access element of an array by using indices.

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:

  • Array have 0 as the first index not 1.In this example, mark[0] is the firs 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 2128 and so on. It's because the size of a float is 4 bytes.

How to initialize an array in C++ programming?

Its possible to initialize an array during declaration. For example,

int mark[5]  = {19, 10, 8, 17, 9};


Another method to initialize an array during declaration.

int mark[]  = { 19, 10, 8, 17, 9};
Here,






















C++ switch...case Statement

                               C++ switch...case Statement


The nested if ...else statement allows you to execute a block code among many alternatives. if you are checking on the value of a single variable in nested if.... else statement, it is better to use switch statement.

The switch statement is often faster than nested if....else (not always). Also, the syntax of switch statement is cleaner and easier to understand.


C++ switch......case syntax



When a case constant is found that matches the switch expression, control of the program passes to the block of code associated with that case.

In the above pseudocode, suppouse the value of n is equal to constant2. The compiler will execute the block of code associated with the case statement until the end of switch block, or until the  break ststement is encountered.

The break statement is used to prevent the code running in to the next case.

Flowchart of switch Statement




The  above figur shows how a switch statement works and conditions are checked within the switch case clause.

Example: C++ switch Statement





Output













The - operator entered by the user is stored in o variable. And, two operaands 2.3 and 4.5 are stored in variables num1 and num2 respectively.


Then the control of the program jumps to



Finally, the break statement ends the switch statement.

if  break statement is not used, all cases after the correct case is executed.






C++ goto Statement

                                       C++ goto Statement


In C++ programming, goto statement is user for altering the normal sequence of program execution by transferring control to some other part of the program,

Syntax of goto Statement





In the syntax above, lebel is an identifier. When goto lebel; is encountered, the control of program jumps to label: and executes the code below it.

Example : goto Statement









Output



You can write any C++ program without the use of goto statement and is generally considered a good idea not to use them.

Reason to Avoid goto Statement

The goto statement gives power to jump to any part of program but, mmakes the logic of the program complex and tangled.

In modern programming, goto statement is considered a harmful construct and a bed programming practice.

The goto statement can be replaced in most of C++ program with the use of break  ststement and continue ststement.





C++ continue Statement

                              C++ continue Statement


It is Sometimes necessary to skip a certain test condition within a loop. In such case, continue; statement is used in C++ programming.

Syntax  of  continue:











In practice, continue; statement is almost always used inside a conditional statement.

Working of continue Statement : 


Example : C++ continue


C++ program to display integer from 1 to 10 except 6 and 9.

















Output :




In above program, when i is 6 or 9, execution of statement cout << i << "\t"; is skipped inside the loop using continue; statement.





C++ break Statement

                                      C++ break Statement


In C++, there are two statements break; and continue; specifically to alter the normal flow of a program.

Sometimes, it is desirable to skip the execution of a loop for a certain test condition or terminate it immediately without checking the condition.

For example : Yoy want to loop through data of all aged people except people aged 65. Or you wnat to find the person aged 20.

In Scenarios like these , continue; or a break; statement is used.

C++ break Statement

The break; statement terminates a loop (for, while and do while loop) and a switch statement immediately when it appears.

Syntax of break

break;

In real practice, break statement is almost always used inside the body of conditional statement (if... else) inside the loop.

How break statement works?


Example : C++ break

C++ program to add all number entered by user until user enters 0







































Output



In the above program, the test expression is always true.

The user is asked to enter a number which is stored in the variable number. if the user enters any number other than 0, the number is added to sum and stored to it.

Again, the user is asked to enter another number. When the user enters 0, the test expression inside if statement is false and body of else is executed which terminates the loop.

Finally, the sum is displayed.

C++ Nested if....else

                                      C++ Nested if....else


The if.....else statement executes two different codes depending upon whether the test expression is true or false. Sometimes, a choice has to be made from more than 2 possibilities.

The nested if...else statement executes allows you to check for multiple test expressions and execute different codes for more than two conditions.


Syntax of Nested if...else









C++   Nested if....else







































Output:







Conditional/Ternary Operator ?:

A ternary operator operates on three operand which can be used instead of if..else statement.

Consider this code:
















You can replace the above code with:

       a = ( a < b ) ? b : -b;

Ternary operator is more readable than a    if...else     statement for short conditions.


Popular Posts

Recent Posts

Categories

Unordered List

Text Widget