Thursday, 29 March 2018

Defining Member Function

The Member function of the class can be defined in any one of the two places
 1. Inside the class definition
 2. Outside the class definition

Inside the class definition :
  Here actual function definition is included within class definition:

  Ex:
     Class class_name
  {
       Data Type datamember_1;
       Data Type datamember_2;
        .
        . 
        public:
        Return_type functionname_1(Actual Argument)
         {
          //Code of Function
         }
          .
          .
          .
          Return_type functionname_n(Actual Argument)
           {
             //Code of function
            }
     };

When a function defined inside the class, it is treated as an inline function.

Outside The class Definition :
    This is another way of defining member function. Here the member function declaration and definition is written separately i.e. function declaration is taken place inside the class and function definition is taken place outside the class.

Function definition outside the class uses scope resolution operator (::) which is used to tell the compiler the scope of the member function or tells that which function belongs to which class .


Syntax :

  class class_name
  {
     Datatype datamember_1;
     Datatype datamember_2;
     .
     .
     .
    Datatype datamember_n;
    public :
    returntype function (Argument list);    //Function Declaration
    .
    .
    .
};

returntype class_name :: function_name (Argument_list)
 {
   //Body of the Function
  }

Ex : Function Definition inside class
       
 WAP in cpp to create a class having name 'student' having members roll_no, name, age and display it on screen.

#include<iostream.h>
#include<conio.h>
class student
{
 private:
 int roll_no;
 char name[10];
 int age;
 public:
 void getdata( )
 {
  cout<<"\n\tEnter Roll no";
  cin>>roll_no;
  cout<<"\n\tEnter Name";
  cin>>name;
  cout<<"\n\tEnter Age";
  cin>>age;
  }
 void display( )
  {
    cout<<"\n\tRoll No is --->"<<roll_no;
    cout<<"\n\tName is --->"<<name;
    cout<<"\n\tAge is--->"<<age;
   }
};
void main( )
{
 student s1;
 clrscr( );
 s1.getdata( );
 s1.display( );
 getch( );
}

Output :-
 
Enter Roll no101  
  

  Enter NameIrawen
   
  Enter Age8

   Roll No is --->101
   Name is --->Irawen
   Age is--->8
      

Ex: Function definition outside class
     
#include<iostream.h>
#include<conio.h>
class student
{
 private:
 int roll_no;
 char name[10];
 int age;
 public:
 void getdata( );
 void display( );
};
  void student::getdata( )
 {
  cout<<"\n\tEnter Roll no";

  cin>>roll_no;
  cout<<"\n\tEnter Name";
  cin>>name;
  cout<<"\n\tEnter Age";
  cin>>age;
  }
  void student::display( ) 
{

    cout<<"\n\tRoll No is --->"<<roll_no;
    cout<<"\n\tName is --->"<<name;
    cout<<"\n\tAge is--->"<<age;
   }
};
void main( )
{
 student s1;
 clrscr( );
 s1.getdata( );
 s1.display( );
 getch( );
}


Output :-
  Enter Roll no101  
  

  Enter NameIrawen
   
  Enter Age8

   Roll No is --->101
   Name is --->Irawen
   Age is--->8
     

Wednesday, 28 March 2018

Classes and Objects

Class :

Class is a user defined data type which is a collection of data members and member function together.

Wrapping of data members and member function together in a single unit is called as class.

Data Members gives the information about object and member function gives the operation on the object or it describes the behavior of the object.

Class helps you for data abstraction as well as for the data encapsulation which gives the advantage of data hiding.

       Syntax of Class Definition:
       class classname
       {
              private:
              //variable declaration;
              public:
              // variable declaration;
              //function declaration;
         };
The keyword 'class' indicates the name of the class. The body of the class enclosed with curly braces followed by semicolon.

The Body of class contain declaration of variables and function collectively called as data members and member function

Class helps you to apply access specifies on data members and member functions.

Data members and member function specified by private access specifies are accessible only to their own class members and not to outsiders but on the other hand public members are accessed to their own members and also from outside class.

Members in the without access specifies are private by default.

Access Specifies public, private are followed by colon.


 
Creating Object :
Declaration of class does not define any objects but specifies what they will contain.Creating object of class called as creating variables of the class. Object of class can be created by using class name like any other variable.

The Syntax is :
 Class_name object_name;
OR
Class_name object_name1,object_name2,object_name3,.........object_name n;

The Memory for the object is created when it is created.

Ex.
       Student xyz;
OR  Student xyz, abc,......;

Objects can also be created when the class is defined by placing their names immediately after the closing brace.

class Student
{
   //Data Members
  // Member Functions
}xyz,abc;

Accessing Class Members :

Once an object of a class has been created , There must provision to access its members. This is achieved by using member access operator that is (.) dot.

The syntax for Accessing Data Members of a class :

Object_name.data_member;

Syntax for accessing Member Function of class :

Object_name.function_name(Actual Arguments);

Recursion

It is a special case of calling a function when a function calls itself again and again.It forms a chaining f calling a function.

For example:-
void main(void)
{
cout<<"Hello Dear";
main( );  /* recursive call  */
}

When executed, this program will display "Hello" on the screen indefinitely.

Another useful example of recursion is evaluation of factorial of a number. The factorial of number is expressed as a series of repetitive multiplications as,

For example:
factorial of 5 = factorial of 4 ⤫ 5 
factorial of 4 = factorial of 3 ⤫ 4
factorial of 3 = factorial of 2 ⤫ 3 
factorial of 2 = factorial of 1 ⤫ 2
factorial of 1 = 1

This statement will be transferred into recursive process in function as given below:
int factorial(int n)
{
int fact;
if(n==1)
return 1;
else
return(n*factorial(n-1));
}

Consider another example of finding value of Xy using recursion:

#include<iostream.h>
#include<conio.h>
int power(int x, int y)
{
if(y<1)
return(1);
else
return(x * power(x,--y));
}
void main( )
{
cout<<power(4,3);
getch( );
}

Function Overloading

Overloading refers to the use of same thing for different purposes.

Function overloading is given by cpp.

Function overloading means using the same function to create different functions that performs variety of different task.

In function overloading, we design family of functions with one function name with different arguments list.

Function would performs different operations depending upon the arguments list.

Declaration:-

                  int add(int a, int b);                  //Prototype 1
                 
                  int add(int a, int b, int c);         //Prototype 2
                 
                  double add(int a, double q);     //Prototype 3


Function call:-

                   add(5,10);                       //Uses Prototype 1
                  
                   add(5,10.5);                    // Uses Prototype 3
                  
                   add(5,10,15);                  //Uses Prototype 2


The correct function will be invoked by checking number and type of arguments but it is not depends upon the function type.

Function call matches the prototype having same number and type of arguments then calls the appropriate function for execution.

#include<iostream.h>
#include<conio.h>
double volume(double int);
int volume(long, int, int);
void main( )
{
clrscr( )
cout<<"\n\t"<<volume(5,10,15);
cout<<"\n\t"<<volume(2.5,8);
cout<<"\n\t"<<volume(100L,70,15);
getch( );
}
double volume(double r, int h)
{
return(3.14*r*h);
}
long volume(long l, int b, int h)
{
return(l*b*h);
}
int volume(int a, int b, int c)
{
return(a*b*c);
}

Output:-
              750
              62.8
              105000

Default Arguments

C++ allows us to call a function without specifying all its arguments.

Default values are specified when function is declared.

Compiler looks at the prototype to see how many arguments, a function uses and alerts the program for possible default values.

Declaration of function with default values
   float amt(float prin_amt, int period, float rate = 0.12)

A function call
 float value = amt(500,7);
Passes value 500 to prin_amt and 7 to perod and then function uses 0.12 for rate.

A function call
float value = amt(500,7,0.15);
Passes explicit value of 0.15 to rate.

Only the trailing argument can have default values i.e. We can add default values from right to left. We can not provide default values in the middle of argument list.

#include<conio.h>
#include<iostream.h>
int volume(int len = 1, int wdt = 1, int hgt = 1);
void main( )
{
clrscr( )
{
cout<<"\n\n\tDefault box volume is--->"<<volume( );
cout<<"\n\n\tThe Volume with length 10 is--->"<<volume(10);
cout<<"\n\n\tThe Volume of the length 10 and width 10 is--->"<<volume(10,10);
cout<<"\n\n\tThe Volume with length 10, width 10 and height 10 is--->"<<volume(10,10,10);
getch( );
}
int volume(int len, int wdt, int hgt)
{
return(len*wdt*hgt);
}

Output:-
Default box volume is--->1
 The Volume with length 10 is--->10
 The Volume of the length 10 and width 10 is--->100
The Volume with length 10, width 10 and height 10 is--->1000

Inline Functions

Every time a function is called, it takes a lot of extra time in executing series of instruction such as jumping to function, saving registers, returning to calling functions.And much execution time is spent in such operations to perform.

To eliminate the cost of calls and to increase execution speed, C++ gives new function called inline function.
Inline function is a function that is expanded in a line when it is called.

Syntax:
            inline return_type function_name (Arguments)
             {
              //Function Body
               }

When we prefix the keyword 'inline' , the function becomes an inline function. All inline function must be defined before they are called.

Example:-
#include<iostream.h>
#include<conio.h>
inline float mul(float x, float y)
{
return(x * y);
}
inline double div(double p, double q)
{
return(p/q);
}
void main( )
{
float a = 12.345, b = 9.82;
clrscr( );
cout<<"\n\n\t Result of multiplication is --->"<<mult(a,b);
cout<<"\n\n\t Result of the division is --->"<<div(a,b);
getch( );
}

Output:-
Result of multiplication is --->121.227898
Result of the division is --->1.257128

Inline function will not work where functions contains loops, switch or goto exist.Also it will not work if a function contain static variable or if a inline function is recursive.

Call By Reference

In call by reference mechanism, instead of passing values to the function being called, reference/pointers to the original variables are passed. 
Example: Program interchange values of two variables by call by reference mechanism.

#include<iostream.h>
#include<conio.h>

void swap(int *x, int *y)
{
int z;
z = *x;
*x = *y;
*y = z;
cout<<"Swapped Values are a is--->"<<*x<<"And b="<<*y;

int main( )
{
int a = 7, b = 4;
cout<<"Original Value are a = "<<a<<"And b ="<<b;
swap(&a, &b);
cout<<"The values after swap are a = "<<a<<"and b = ""<<b;
}

Output:-
 Original Values are a = 7 and b = 4
 Swapped values are a = 4 and b = 7
 The values after swap are a = 4 and b = 7

Call By Value

The call by value method of passing arguments to a function copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument.
     By default, C++ uses call by value to pass arguments.In general, this means that code within a function cannot alter the arguments used to call the function. Consider the function swap( ) definition as follows.

// function definition to swap the values.
void swap(int x, int y)
{
int temp;
temp = x;  /*save the value of x */
x = y;  /* put y into x  */
y = temp;  /* put x into y  */
}

Now, let us call the function swap( ) passing actual values as in the following example:

#include<iostream.h>
using namespace std;

// function declaration 
void swap(int x, int y)

int main( )
{
//local variable declaration:
int a = 100;
int b = 200;

cout<<"Before swap, value of a:"<<a <<endl;
cout<<"Before swap, value of b :"<< b <<endl;

//calling a function to swap the values.
swap(a,b);

cout<<"After swap, value of a :" <<a<<endl;
cout<<"After swap, value of b:" <<b <<endl;
return 0;
}

When the above code is put together in a file, compiled and executed, it produces the following result:

Before swap, value of a :100
Before swap, value of b:  200
After swap, value of a : 100
After swap, value of b :200

It allows that there is no change in the values though they had been changed inside the function.

Tuesday, 27 March 2018

Characteristics of Good Programming Language

There are many programming languages, each corresponding to specific needs (formula calculus, character string processing, real-time, etc.) with each having specific characteristics and functionalities. Therefore, the choice of programming language depends above all on the requirements to be fulfilled as well as the existing resources for understanding and training in the language.

Selection Criteria for a Programming Language

 1. Usability
       Easy to learn, ease of use for an experienced programmer.
 2. Performance
       Speed of program execution, speed of compiler execution (a program which translates the program into machine code), stability (lack of defects).
 3. Portability
       A portable language is one which is implemented in variety of computers (design relatively machine dependent). Well defined language are more portable than others e.g. C, C++.
 4. Extendibility 
        Possibility of developing the language and its implementation, existence function libraries, class libraries, etc.
 5. Continuity
        Continuity of the manufacturer, language continuity, implementation continuity, existence of international standards for defining the language, comformity of implementation by following standards, existence of other manufacturers for that language.

Subprograms
 In computer science, a subroutine or subprogram (also called procedure, method, function, or routine) is a portion of code within a larger program, which performs a specific task and is relatively independent of the remaining code.

As the name "subprogram" suggests, a subroutine behaves in much the same way as a computer program that is used as one step in a larger program or another subprogram.

A subroutine is often coded so that it can be started ("called") several times and/or from several places during a single execution of the program, including from other subroutines, and then branch back (return) to the next instruction after the "call" once the subroutine's task is done.

  There are two distinct categories of subprograms:
    1. Procedures           2. Functions.

Function Calls

A function cab be called by simply using function name followed by a list of actual parameters (or arguments) if any, enclosed in parentheses.
For example:
main( )
{
float m;
m = mul(5.2, 3.17); /* function call */
cout<<m
}
When compiler encounters the function call, it transfer program control to the function mul( ) by passing values 5.2 and 3.17 (actual parameters) to the formal parameters on the function mul( ). The mul( ) will performs operations on these values and then returns the result. It will be stored in variable m. We are printing the value of variable m on the screen. There are a number of different ways in which the function can be called as given below:

mul(5.2, 3.71);
mul(m, 3.17);
mul(5.2, m);
mul(m, n);
mul(m+5.1, 3.17);
mul(m+3.6, m+9.1);
mul(mul(6.1,8.2), 4.5); 
Only we have to remember that the function call must satisfy type and number of arguments passed as parameters to the called function.


Function Prototype / Function Declaration
 Like variables, all functions in C++ program must be declared, before they are used in calling function. This declaration of function is known as prototype. It having following syntax of use:

function_type function_name (parameter list);  

 this is very similar to function header except the terminating semicolon.
For example, the function mul( ) will be declared as,
float mul(float, float);
Generally, prototype declarations as not necessary, if the function have been declared before it is used. A prototype declarations my be placed in two places in the program.
  • Above all the functions
  • Inside function definition
  We place declaration above all the functions this prototype is known as global prototype. That is, we can use this function in any part on the program. When we place the function definition in the local declaration section of another it is referred as local prototype.
 

Elements of user-defined Functions

There are some similarities exists between functions and variable in C++.
 1. Both function name and variable names are considered as identifiers and therefore they must follow the rules of creating variable's name.
 2. Like variable, function have data types associated with them.
 3. Like variable, function names and their types must be declared and defined before they are used in the program.
   In order to make use of user defined functions, we need to establish three elements that are related to functions.
  1. Function definition
  2. Function call
  3. Function declaration

Definition of functions
  The function definition is an independent program module that is specially written to implement the requirements of the definition. So it is also called as function implementation. It includes following topics:
Function Header
Function Body

The general form of function definition is as given below:
Return_type function_name(parameters list)
{
local variable declaration;
executable statement1;
executable statement2;
------------------;
------------------;
return statement;
}
The first line Return_type function_name(parameter list) is know as function header and the statement enclosing the curly braces are known as function body.

Function Header
 It includes three parts:
   1. Return type
      It specifies type of the value that the function is expected to return to the program calling the function.It is also called as return type. If function is not returning any values we have to specify it as void.
   2. Function name
      It is any valid C++ identifier name and therefore must follow the rules for creation of variable names in C++
   3. Parameters list
      It declares variable that will receive the data sent by the calling program. They serve as input data to the function to carry out specific task. Since, they represent the actual input values they are referred as formal parameters or formal arguments.
 For example:
 int findmax(int x, int y, int x)
{
---------------
}
double power(double x, int n)
{
--------------
}
double quad(int a, int b, int c)
{
---------------
}
void print_line( )
{
------------------------
}

Function Body
 It contains the declarations and statements necessary for performing required task. The body enclosed in braces, contains thee parts:
  1. Local variables declaration
       It specifies the variables needed by the function locally.
  2. Function Statements
      That actually performs task of the function.
  3. The return statement
      It returns the value specified by the function.

For example:

float mul(float x, float y)
{
float result; /* local variable */
result = x * y; /* find the result */
return(result);  /* return the result */
}
void display(void)
{
cout<<"Hello World!";  /* only print the value */
}
void sub(int a, int b)
{
cout<<"Subtraction:"<<(a-b);  /* no variable */
}

Return values
 A function may or may not send back any value to the calling function.If it does, it is done by return statement. The return statement also sends the program control back to the calling function. It is possible to pass a calling function any number of values but called function can only return one value per call, at most. The return statement can take one of the following forms:
return;
return(value);
return(variable)
return(expression);
The first plain return does not return any value; it acts much as closing brace of the function. The remaining three statements can eliminates the brackets also. When the return is executed, the program control immediately transfer back to the calling function. None of the statements written after return are executed afterwards.

For example:
return(x);
cout<<"Bye.....Bye";
  In this case the cout statement will not be executed in any case.Because the return statement will transfer program control immediately back to the calling function.Some examples of return are:
int div(int x, int y)
{
int z;
z = x/y;
return z;
}
  Here, instead of writing statement inside the function div( ), we can write a single statement as,
return (x * );
OR
return x * y;
 A function may have more than one return statement when it is associated with any condition such as,
if(x>y)
return x;
else
return y;
In this code, in any condition, only one return statement will be executed.

Function

A function is self-contained block of statements that performs particular task. C++ functions can be classified into two types:
  • Library functions
  • User-defined functions

           The library functions are the functions which are already defined in C++s functions library i.e. header files. For example, the functions clrscr( ) and getch( ) are the library functions defined in file conio.h same as functions sqrt( ) is defined in math.h. User defined function is the function defined by the programmer who has written the program. The task to perform is decided by user.

Need of user-defined function
  1. The functional program facilitates top-down modular programming approach as shown in figure below.

 

  2. The length of source program can be reduced by functions at appropriate places.
  3. It is easy to locate and isolate a faulty function for further investigations.
  4. A function may be used by many other programs. This means that a C++ programmer can build on what others have already done. That is we can reuse the functions already defined in some program files.

Some Most Popular Programming Language

FORTRAN (FORmula TRANslation)
 The name FORTRAN is an acronym for FORmula TRANslation, because it was designed to allow easy translation of math formulas into code.
Often referred to as a scientific language, FORTRAN was the first high-level language, using the first compiler ever developed.Prior to the development of FORTRAN computer programmers were required to program in machine/assembly code, which was an extremely difficult and time consuming task.
The objective during it's design was to create a programming language that would be: simple to learn, suitable for a wide variety of applications, machine independent, and would allow complex mathematical expressions, machine independent, and would allow complex mathematical expressions to be stated similarly to regular algebraic notation. 

COBOL (Common Business Oriented Language)
 COBOL (pronounced / ? ko?b?1/) is one of the oldest programming languages.Its name is an acronym for Common Business-Oriented Language, defining its primary domain in business, finance, and administrative systems for companies and governments.
The COBOL 2002 standard includes support for object-oriented programming and other modern language features. 
COBOL was an effort to make a programming language that was like natural English, easy to write and easier to read the code after you'd written it.

BASIC (Beginner's All-purpose Symbolic Instruction Code)
 In computer programming, BASIC ( an acronym for Beginner's All-purpose Symbolic Instruction Code) is a family of high-level programming languages.
It is developed to provide computer access to non-science students.
BASIC remains popular to this day in a handful of highly modified dialects and new languages influenced by BASIC such as Microsoft Visual Basic.As of 2006, 59 % of developers for the .NET platform used Visual Basic .NET as their only language.

PASCAL
 Pascal is an influential imperative and procedural programming language designed in 1968/9 and published in 1970 by Niklaus Wirth as a small and efficient language intended to encourage good programming practices using structured programming and data structuring.
A derivative known as Object Pascal was designed for object oriented programming.

C Language
 C is a general-purpose computer programming language developed in 1972 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system.
Although C was designed for implementing system software, it is also widely used for developing portable application software.
C is one of the most popular programming languages. It is widely used on many different software platforms.

C++ Language
 C++ (pronounced "C plus plus") is a statically typed, free -form multi-paradigm, compiled, general-purpose programming language.
It is regarded as a middle-level language, as it comprises a combination of both high-level and low-level language features.
It was developed by Bjarne Stroustrup starting in 1979 at Bell Labs as an enhancement to the C programming language and originally named "C with Classes". It was renamed to C++ in 1983.

JAVA
 Java is a programming language originally developed by James Gosling at Sun Micro-systems and released in 1995 as a core component of Sun Micro system Java platform.
The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities.
Java application are typically compiled to byte-code (class file) that can run on any Java Virtual Machine (JVM) regardless of computer architecture. 

LISP (LISt Processing)
 Lisp (or LISP) is a family of computer programming languages.
It is the second-oldest high-level programming language in widespread use today.
Lisp was originally created as a practical mathematical notation for computer programs.
The name LISP derives from "LISt Processing" .Linked lists are one of Lisp languages major data structures, and Lisp source code is itself made up of lists.

High-level Programming Language Tools : Compiler , Linker , Interpreter


Compiler 

 Compiler is used to transform a program written in a high-level programming language from source code into object code.

Programmers write programs in a form called source code.Source code must go through several steps before it becomes an executable program.

The first step is to pass the source code through a compiler, which translates the high-level language instructions into object code.

The final step in producing an executable program--after the compiler has produced object code-- is to pass the object code through a linker. The linker combines modules and gives real values to all symbolic addresses, thereby producing machine code.

Linker

 Also called link editor  and binder, a linker is a program that combines objects modules to form an executable program.

Many programming languages allow you to write different pieces of code, called modules, separately.

This simplifies the programming task because you can break a large program into small, more manageable pieces.

Eventually, through you need to put all the modules together.This is the job of the linker.

Interpreter

 An interpreter translates high-level instructions into an intermediate form which it then executes.

Compiled programs generally run faster than interpreted programs.

The advantage of an interpreter, however, is that it does not need to go through the compilation stage during which machine instructions are generated.The process can be time-consuming if the program is long.

The interpreter, on the other hand, can immediately execute high-level programs.

Editor

 An editor is software, where the programmer can write the source code, edit it as well as compile and execute it. Like compilers and interpreters, the editors are also different for different programming languages.

MATLAB

  MATLAB (MATrix LABoratory) is a numerical computing environment and fourth generation programming language, developed by the Math works.

 MATLAB allows matrix manipulation plotting of functions and data, implementation of algorithms, creation of user interfaces, and interfacing with programs in other languages.

GUI (Graphical User Interface)
 GUI is a program interface that takes advantage of the computer's graphics capabilities to make the program easier to use. Well-designed graphical user interfaces can free the user from learning complex command languages.

Jumps out of the Loop

The break statement
  As we have already seen, the 'break' statement is used to exit out of the switch statement.It is having another useful application in loop control structures.That is, the 'break' statement is used to jump out of the loop.When the 'break' is executed inside the loop, the program control will not execute the loop for further iterations.Generally,   the 'break' is associated with if-statement.
General form of using 'break' is :-
break;


The dotted line shows the path where the Program control will transfer.
For example:
/*Example*/
int x;
for(x = 10; x<20; x++)
{
if(x%4 ==0)
break;
printf("%d\n",x);
}

The output of this program will be:
10
11
Because, when value of x becomes 12, the condition will be evaluated to true and break get executed.

The 'continue' statement
  The continue statement is used continue the next iteration of the loop by skipping the statements in between.That is, when the 'continue' is executed the statements following is will not be executed, the program control will directly transfer to next iteration of the loop by increment or decrement.Generally, the 'continue' is associated with if-statement.General form of using 'continue' is-
continue;

The dotted line shows the path where the program control will transfer.
For Example:-
int x;
for(x = 10; x < 20; x++)
{
if(x%4 ==0)
continue;
printf("%d");
}

The output of this program will be:
10   11   13  14  15  17  18  19

The 'switch' Statement
This is another form of the multi-way decision statement.It is well structured, but can only be used in certain cases. The switch statement tests value of a given variable (or expression) against the list of case values and when the match is found, a block of statements associated with that statements are executed. The general form of switch statement is as follows:
switch(variable)
{
case value-1:
//statement 1;
break;
case value-2:
//statements 2;
break;
case value-3
//statements 3
break;
--------
default:
//default-statements;
break;
}
statements-x;
In the above given syntax, value-1, value-2, value3..... are the set the constants. When the value of the variable given in the switch brackets is matched with any one of these values, the particular set of statements are executed and then program control transfer out of the switch block. For example, if value of variable is matched with 'value-2' then statements2 are executed and the break statement transfer the program control out of the switch.If the match is not found, the 'default' block is executed. Remember, statements-x are executed in any case. Generally, switch case are executed for menu selection problems.


Rules of switch statement
1. The switch variable must be an integer or character type.
2. Case labels must be constants of constants expressions.
3. Case labels must be unique. No two labels can have the same value.
4. Case labels must end with a colon.
5. The break statement transfers the program control out of the switch block.
6. The break statement is optional. When the break is not written in any 'case' then the statements following the next case are also executed until the 'break' is not found.
7. The default case is optional. If present, it will be executed when the match with any 'case' is not found.
8. There can be at most one default label.
9. The default may be placed anywhere but generally written at the end . When placed at end it is not compulsory to write the 'break' for it.
10. We can nest the switch statements.

Monday, 26 March 2018

The Loop control Structures

Many times it is necessary to execute several statement repetitively for certain number of times. In such case, we can use looping statement of Cpp programming language. The statement are executed until a condition given is satisfied. Depending upon the position of the condition in the loop, the loop control structures are classified as the entry-controlled loop and exit-controlled loop. They are also called as pre-test and post-test loops respectively.

The 'while' loop
   The 'while' is an entry-controlled loop statement having following general form:
   while(condition)
    {
      //loop statement or body of loop
     }
        Here, the condition is evaluated first,if it is true then loop statements or body of the loop is executed.After this the program control will transfer to condition again to check whether it is true or false.If true,again loop body is executed.This process will be continued until the condition becomes false.When is becomes false, the statements after the loop are executed.This is also called as pre-test loop. 


The do-while loop
  This 'do-while' is exit-controlled loop statement in which the condition of the loop statement is written at the end of the loop.It takes the following general form:
    do
     {
      //loop statement or loop body
     }while(condition)
Here, when the program control is reached at do statement the loop body or statements inside the loop are executed first.Then at the end the condition is the 'while' is checked.If it is true, then program control again transfers to execute the loop statements.This process continues until the condition becomes false.In short, we can say that the loop statements are executed at least once without checking condition for its trueness.


     
The 'For' loop
  The 'for' loop is an entry controlled loop structure which provides more concise loop structure having following general form:
  for(initialization ; condition ; increment/decrement)
  {
   //loop statement or loop body
   }
 The execution of 'for' loop statement takes as follows:
  1. Initialization of loop control variables is done first using assignment operators such as: i= 1 or count = 0 etc. Remember this part is executed only once.
  2. The condition given afterwards is checked then. If this condition is true, the statements inside the loop are executed.Else program control will get transferred nest statement after the loop.The condition can be combination of relational as well as logical operators such as :
count < 10
  3. When the body of the loop is executed, program control will get transferred back to 'for' statement for executing the third statement that is, 'increment/decrement'. In this part the loop control variable's value is incremented or decremented.Then program controls the condition again to check whether it is true or not. If true the loop body executed again.And the process is continued again until condition evaluates to false.

Sunday, 25 March 2018

Decision Making Statements

Many times in the program such condition occur when we want to take the exact decisions in order to make an error free program.This kind of situation can be handled using decision control instruction of cpp.It includes if-else statements and the conditional operators.The  decision control structure in cpp can be implemented using:
a) The if statements 
b) The if-else statement
c)  Nested if-else 
d) The else-if ladder

The if Statement
  The general form or syntax of if statement looks like this:
   if(condition)'
    {
      statement-1;
     }
      statement-2;
      statement-3;
     

Here, the keyword 'if' tells the compiler that what follows, is a decision control instruction.The condition following the keyword if is always enclosed within a pair of parentheses.It the condition is true, then the statement in the parenthesis are executed.It the condition is not true then the statement is not executed instead the program skips this part.


The if-else statement 
   The 'if' statement by itself will executed a single statement or a group of statement when the condition following if is true,it does nothing when the condition is false.If the condition is false then a group of statement can be executed using 'else' statement.Its syntax is as given below:

if(condition)
 {
  // statements 1
  }
   else
    {
     // statements 2
     }
    Statement3;


When, we used if-else statement, either 'if' or 'else' statement block will execute depending upon the condition given in the 'if' statement.The 'else' doesn't require condition.Execution of 'else' block also depends on if(condition). When it is false program control transfer to 'else' block.

Nested if-else
 If we write an entire if-else construct within the body of the 'if' statement or the body of an 'else' statement. This is called 'nesting' of if else.

Syntax:
 if(condition)
 {
   //statements1
   if(condition)
    {
     //statements2
     }
     else
     {
      //statements3
      }
   }
 else
 //statements4
 Here,the inner condition executed only when the outer condition of 'if' is true.This hierarchy of nesting of 'of' can be extended in deep with any number of 'if-else' statements.

The else-if ladder
  There is another way of putting multiple 'if's together when multipath decisions are involved. A multipath decision is a chain of 'if's which the statement is associated with each else in an 'if'. It takes the following general form:

if(condition1)
//statements1;
else if(condition2)
//statements2;
else if(condition3)
//statements3;
else if(condition n)
//statements n;
else
//statements-x;
                         This construct is known as else-if ladder.The condition are evaluated from top to the bottom of ladder.As soon as true condition is found, statements associated with it are executed and then program control  is transferred to the 'statements-x' , skipping the rest of the ladder.
  When all the condition become false, then final else containing default statements will be executed.This is shown in the following flowchart-


Types of Programming Languages

We classify programming language by their level.
a) Natural Language.
b) Machine level Language
c) High-level Language
d) Assembly level Language
e) Scripting Language

Natural Language
  A language spoken, written or signed by humans for general purpose communication.

Machine Level Language
  It is the lowest-level programming language.
  Machine language are the only language understood by computers.
  Programs written in high-level language are translated into machine language by a compiler.
  A computer's language consists of strings of binary numbers (0,1).

Limitations 
 - In this programming language a programmer has to remember dozens of code numbers or commands in the machine instruction set.
- A programmer has to keep track of the storage locations of data and instructions.
- Modifications of a machine level program and the location of errors in it is a tedious job and can take long time.

Assembly Level Language
  The assembly language is simply a symbolic representation for its associated machine language.
  This representation consists of mnemonic operation codes and symbolic address.
Advantage
 - Less number of errors and also errors are easy to find.
 - Modification of assembly language program is easier than that of machine language program.
Limitation
 - They are machine oriented.

High Level Language (HLL)
  A programming language such as c, FORTRAN, or Pascal that enables programmer to write programs that are more or less independent of a particular type of computer. Such language are considered high-level because they are closer human languages and further from machine languages.

Characteristics of High Level Programming Language
  In computing, a high-level programming language is a programming language with strong abstraction from the details of the computer.
 In comparison to low-level programming language, it may use natural language elements, be easier to use, or be more portable across platforms.
 Such language hide details of CPU operations such as memory access models and management of scope

Scripting Language
  A scripting language is a high-level programming language that is interpreted by another program at runtime rather than compiled by the computer's processor as other programming language (such as C and C++) are.
 Scripting language, which can be embedded within HTML, commonly are used to add functionality to a web page, such as different menu styles or graphic displays or to serve dynamic advertisements. 

Popular Posts

Categories

100 Python Programs for Beginner (53) AI (34) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (173) C (77) C# (12) C++ (82) Course (67) Coursera (226) Cybersecurity (24) data management (11) Data Science (128) Data Strucures (8) Deep Learning (20) Django (14) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (6) flask (3) flutter (1) FPL (17) Google (34) Hadoop (3) HTML&CSS (47) IBM (25) IoT (1) IS (25) Java (93) Leet Code (4) Machine Learning (59) Meta (22) MICHIGAN (5) microsoft (4) Nvidia (3) Pandas (4) PHP (20) Projects (29) Python (932) Python Coding Challenge (358) Python Quiz (23) Python Tips (2) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (3) Software (17) SQL (42) UX Research (1) web application (8) Web development (2) web scraping (2)

Followers

Person climbing a staircase. Learn Data Science from Scratch: online program with 21 courses