Wednesday, June 26, 2013

Function

Motivation :  Suppose, you are writting  a program that requires you to compute the area of a rectangle at several different places.
you can do two things :
1> restructure the code so that all the area computations are done at one place. So,  that a loop can be used to do the task.
2> write the code(to compute the area) at  all the places where it is required(or copy paste).

Now, both of the above two choices have flaws. In the first approach, you may overcomplicate the problem trying to restructure it, or in the worst case you are a beginner and are not able to restructure the code at all, in which case you resort to the second method. This as a result makes your code look clumsy,
 repetitive and sometimes too hard to interpret by someone viewing the code
and not to forget that you have to put labour in retyping the code multiple times.

So, how do we solve the problem, so that none of the above mentioned problems arise. The answer is we have to use Functions.

definition :  It is a module (block of code) that does a particular task.

Informally a function can be thought of as a magical box which takes some input and produces some output.



Syntax :  

            return data type function_name ( arguments* ) {

                        // function body. We write the logic here for the 
                        // task we want the function to perform.

            }
            data type : dt, 

            arguments : ( dt1 var1, dt2 var2, dt3 var3, ............, dtn varn)
            
             vari -> represents the name of the ith variable of the argument 
                          list.
            dti -> represents the data type of the i th variable in the argument 
                    list.
                    (Note that : there may  exist (i, j) such that dti = dtj for i != j )


Now, let's analyze each component one by one in detail :

1> return data type : This is the data type of the variable that the function is expected to return, i.e. say you have an area function than you expect the function to return  a double type variable.

2> function name : This is the name by which this function is referred(called) anywhere it is required. Just like a variable name.

3> arguments : This is the list of variables with data types that the function takes as input. These variables are used by the function's logic to arrive at a result. 
eg : in an area function meant for square, only one argument "int x" is required. But in case of area function for a rectangle, we require two arguments "int length, int breadth".

4> Function's Body : This is the part  where the main working logic of the function is written. In other words after the execution of these statements we arrive at the final output.
Much like starting out with basic ingredients and then following a few steps to make tea(we are making tea here !!!!! I thought we were learning functions ?). Here tea is the final product.

eg : we will look at it in a moment.....


look at the picture below to get a clear idea of a function.





























Variations of function : This variation is based on return type and arguments being void or non void (So, there are 2*2 = 4 possibilities). 

look at the following pic to understand the 4 variations of the function :




(Note : if the arguments are of void type, you may or may not specify void)


Function call :  It is the process of calling an already defined function. When and where required by the program. The function which contains the function call statement is called the "calling function". The function which is called is "called function" (wow!!! that wasn't a mystery).

e.g. look at the pic below to understand it 

























(note : there is one more control jump, when the body of the function is done executing, the control jumps back to the calling function i.e. main() here).

Function Prototype : This is a signature of a function. Whose declaration and definition are not done together.(confused are we ???) 
This is a method to tell the compiler that i want to define a function later.

look at the pic below to understand it more clearly :


(Note : the fact that every thing has to be declared at some point before it's usage in a c++ program is known as forward dependence.)


Now, we are ready to take a look at a program


Explanation : only one thing needs to be explained in the above program.
More specifically the call statement of function number '4.> '. Let's look at the statement carefully and try to understand what is happening. 
What we are doing here is that, we are storing the return value of the function area() in the variable darea. when the control returns from the body of the function  area()  it returns the value of variable area(in the function) with the help of the return statement.(Note : we may choose to ignore the value returned from a function.)

actual parameters  :  The actual variables(value) that is passed to the calling function by the called function.

formal parameters : The variables used in a function definition to represent the actual variables that are passed to the function during it's call.

look at the picture for further clarification :




Calling Mechanisms :  This are two calling mechanism supported in c++.

1> call by value : In this mechanism the value  of the actual parameters are just copied to formal parameters. Hence any change in the formal parameters 
does not reflect in the actual parameters. Since they are separate variables having the same values.



let's see a program to illustrate this concept :



Explanation




2> call by reference : In this mechanism the address  of the actual parameters are just passed as the formal parameters. Hence any change in the formal parameters reflects in the actual parameters. Since they are same variables having the different names.

before delving any deeper into the concept of call by reference let's look at what is a alias

alias : It is a mechanism using which you can have multiple names for the same memory space(i.e. same variable).

Syntax : 
                data_type var1 ;
                data_type var2 = &var1 ;

look at the following picture too understand what is happening




I explained the concept of alias because when we call a function by "call by reference". We actually create the alias of the actual parameters i.e. the formal parameters become the reference of the actual parameters.



Explanation : In the program above, we use call by reference. Notice the '&' 
symbols in front of the formal parameters. Now when we call the function with the actual (a, b) in main, the formal parameters (a, b) in the swap function act as an alias to them. Hence any change to the formal parameters reflect on the actual parameters.


look at the following pic to understand more clearly



Recursion  :  The phenomenon where a function calls itself. 

let's look at a program to understand the concept of recursion :




Explain  : observe that the function has a basis case. The basis case is the case where we know the value of the function before hand and the recursive step where the function is expressed in terms of smaller instances of itself.

       n!   =  n * (n-1) * (n-2) * ....... * 1
(n-1)!  =  (n-1) * (n-2) *....... * 1
       n!  =   n * (n-1)! (easy isn't it)
and we know that 
 0! =1 (basis case)

 as with all other posts i have uploaded the source code of all the programs here in google drive hereLearning c++






Wednesday, June 19, 2013

Loops

Motivation : Suppose you want to print 1 to 10 on the screen on a single line.
what will you do??
easy right??? just use 'cout' to print them on screen(huh!!! childs play).
Now, imagine the same scenario but this time instead of 1 to 10 try to print 
1 to 1000. Not so easy right!!!!!
So, what i want to say is, if you want to execute the same block of code a no. of times than c++ provides what is known as a loop.
There are 3 different loops that c++ provides 
1> for loop
2> while loop
3> do while loop

Now let's have a look at each of them in details :
1> for loop : 
                   general Syntax :  
                   for(initialization; condition checking; increment or decrement) {
                                               //repeating block of code
                   }
note : if the loop's body contains one statement than it is not necessary to give the curly brackets(for all types of loops).

let's take an example to understand the syntax more clearly :




















                                   




*in the previous picture the output : 0 1 2 3 4 5 6 7 8 9 
(sorry for the silly mistake)

The picture below depicts the flow of control in the for loop :

let's look at the following code to find the sum of n entered numbers : 


Explanation :  we have taken the loop variable as i. we have initialized 'i' to 1(as you may have noticed from the flow chart that the initialization is  done only once ). Now 1<= 10 condition is checked. which is found to be true.
so, control enters the loop body and it takes a number as input from user.
Add this number with sum(which is 0 initially) now sum = 0+10 = 10. Then i is incremented 2<=10 condition is checked and found true. Again a number is taken as input from the user and  added to sum.  so, sum = 10 + 20 = 30 and so on.............


look at the following diagram for more clarity(it is assumed that the user gives same input as in the program shown above)


























the general syntax of the for header can be varied the following program illustrates this none of the parts of the for loop header are compulsory.
 Explanation :  you can easily see from the above program, that for loop can be used in various ways. You can skip the initialization part, the increment decrement part, the condition checking part or you can skip all. This gives us flexibility to write our code. The break will be explained shortly.

2> while loop :
                         general syntax : 
                          while(condition) {
                                             //repeating code block
                          }
the following figure depicts the particular pattern for a while loop





look at the following code snippet to understand various ways of using while loop :




























Explanation :  in the 2. standard loop i have used post increment so it prints first and then increments the value. In the 3. standard loop i have post incremented the value during condition checking so that first condition is checked and then it is incremented, (i-1) is used since the value is already incremented and i want to print the previous value.


Entry Control loop :  upto this point whatever loop we have studied is known as entry control loop. Because the condition checking is done prior to getting entry in the loop body(much like buying ticket at the entry of a fair to enter it).

2> do while loop : 
                              Syntax :
                               do {
                                  //repeating code block
                                 
                                } while(condition) ;
look at the following code to understand the syntax of do while loop properly
look at the following code to understand the syntax of do while loop properly :

Explanation : by observing the output one can easily say that this loop behaves a little differently than the others because the condition checking is after the loop body it executes one time more than the value of n(in 1 and 3).
I encourage you to find out what is happening in the 2nd version where exactly 6 numbers are getting printed.


break : this is a instruction that is used to break out of the current active loop
body without executing any further iterations.

continue : this instruction is used to skip any c++ statements in the current iteration after the continue statement   and go to the next iteration.

look at the code for more clarity :
Explanation : 
                      continue : the control enters the if's body for odd values of i and then encounters the increment so in cases where the value of i is odd the cout is not executed
                  break : user is prompted for a input at each iteration of the loop and then the if is used to check the choice if found to be true break is used to exit the loop body.
 here is the output :

the while loop part of the above program which uses break can be done by do while loop i encourage you to do it as an exercise.



                      Nested Loops

Motivation : Sometimes we require that for each iteration of the outer loop there is some work that we need to do that occurs a fixed no. of times.
For these kind of situations nested loop is used

Syntax : 
ini -> initialization
cndchk -> condition checking
inr/dcr -> increment/decrement
                for(ini; cndchk; inr/dcr) {//outer loop body
                                    for(ini; cndchk; inr/dcr) {//inner loop body
                                                               //repeatable code block  
                                    }
                    }
                    while(cndchk) {//outer loop body
                                    while(cndchk) {//inner loop body
                                                               //repeatable code block 
                                                                inr/dcr
                                     }
                                     inr/dcr
                   
                     }
                     do {/outer loop body
                                     do {/inner loop body
                                                //repeatable code block 
                                                inr/dcr
                                     } while(cndchk)
                                     inr/dcr
                     } while(cndchk)


let's have a look at the following snippet to understand the nested loops better :
output : 1 2 3 4 5 6 7 8 9 10
               1 2 ..................10
               1
             .
             .
             .
               1 2 3 ...............10  (no. of rows 10 and no. of columns 10)

let's look at a few programs to print patterns :

1>

2>

3>
note :
Enter patterns :  means Enter n : i don't know why i wrote it please bear with it.
I encourage you to program all these patterns using while loop and try several other patterns by yourself. you can find a lot of these patterns on the internet or in basic books of c++.
 as with all other posts i have uploaded the source code of all the programs here in google drive here : Learning c++







Tuesday, June 18, 2013

Condition Checking (if else and switch case)


Motivation :
suppose you want to write a program that takes a particular action 
depending on the user's input. That is your want your program to execute a particular section of code if the user gives a particular input and not otherwise. For condition like these we need to do what is known as condition checking
c++ provides two methods to do these :
1> if else :
syntax :
                //1st indentation style
                if(expression or condition) {
                                     //body of the 'if' write the program logic here
                } else {
                                     //body of the 'else' write the program logic here
                }
                
                //2nd indentation style
             if(expression or condition) 
               {
                                      //body of the 'if' write the program logic here
                } 
                else
               {
                                     //body of the 'else' write the program logic here
                }
note : you do not need to give the curly brackets if the if's body contains only one statement.
Working : When the control reaches the if(condition) line then it checks the condition and if found true then the control enters the if body and if found false it enters the else part.

Let's see an example to see the use of if and else
(it checks if a entered no  is odd or even)











































Explanation : The program is simple here we take a number 'n' as input from the user using 'cin' and then use the modulus(%) operator to check if after dividing it by 2 the remainder is 1 or 0. If it is even it will leave a remainder of '0' so it will enter the if body and if it is 1 then the if condition will be false and so it will enter the  else part. 


                                  if - else if ladder


Motivation : now let's assume that you want to write a program for calculating your electric bill, then you need to check a lot of conditions as different different ranges have different different values.
for that c++ provides something known as if - else if ladder.

Syntax : 
               //you can figure the next indentation style by yourself
             if(condition) {
                      //your code
              
              } else if(condition) {
                       //control enters here only if the first if's condition is false
                      //your code
            
              } else if(condition) {
                      //control enters here only if the previous else if's condition 
                      // is false
                     //your code
              } else {
                     //control enters here only if none of the conditions
                     // are true
                    //your code
               
              }


Nested ifs ans elses :

Motivation : now let's assume that you want to write a program where 
you want to check a contition that is too long to write in a line 
(becomes to messy if written in one line) 
or 
condition is too complicated to be written all at once than for your 
safety(safety as in to prevent you from making errors) and to make the program more readable. you should use what is known as nested if else.

Nested : if's are said to be nested when the body of an if is completely encapsulated within the body of another if.

Syntax :

              if(condition) { // this is the outer if's body
                 
                          if(condition) { //this is the encapsulated if's body
               
                          } 
              }
            
               or 
               if(condition) { // this is the outer if's body
                 
                          if(condition) { //this is the encapsulated if's body
               
                          } else {
                            
                          }
                 }
if-else if ladder :
let's look at a code  for more clarity :
Explanation the first if checks the the age to be between 10 and 20 remember the and logical operator now the control enters the 
else if (age < 30) only when the first if is false and it will enter the next if-else if only if the previous one is false and so on.

same code could also be written with only if's and else(i leave it as an exercise )
will upload an hint in the google drive you can refer to that if you are having problem

nested if else :
let's look at a code  for more clarity :

Explanation : the above program uses nested if concept first the age of the user is checked and then the profession is checked making the code look elegant and easy to read this same effect could have been obtained by the and logical operator.
like this way : 
                       if(age > 20 && age < 30 && profession == 'a') {
                                      cout<<"your code here";
                    }
here is the output :

2>  switch case :              

motivation :  well all of you are already motivated. When you have a single decision variable (the variable which determines what part of code to execute)
then switch case is really helpfull.

Syntax :
               switch(variable) {
                            
                           case val1 :
                                              //control enters here if value of variable = val1   
                                             // you code here
                                             break;
                           case val2 :
                                              //control enters here if value of variable = val2
                                             // you code here
                                             break;
                           case val3 :
                                              //control enters here if value of variable = val3
                                             // you code here
                                             break;
                                  .
                                  .
                                  .
                                  .
                           case valn :
                                              //control enters here if value of variable = valn
                                             // you code here
                                             break;
                           default :
                                              //control enters here if value of variable not  
                                              //equal to anything
                                             //warning that the variable does not match any
                                             //of the given values
               }

Break : it is statement which when encountered the control skips the current active block and moves to the first statement of the outer block.
 (not so clear!!!) ok the diagram below will make it more clear.
the use of break in switch case is to ensure that only the case with matches the value of the variable is executed. If it is not given then all the cases after the case that matches the value will be executed.  
In order to understand i encourage you to download the source code of the program below from google drive link at the end of the post and remove the break statements to see what is happening.

here is a program illustrating the use of a switch statement :

the source file of the programs are uploaded in google drive in Learning c++  folder