Saturday, 31 March 2018

Variables

A variable is a value that can change any time. It is a memory location used to store a data value. A variable name should be care fully chosen by the programmer so that it use is reflected in a useful way in entire program. Variable names are case sensitive.
Example of variable names are
  sun
  Number
  Salary
  Emp_name
  Average1
  
Any variable declared in a program should confirm to the following-
1. They must always begin with a letter, although some systems permit underscore as first character.
2. The length of a variable must not be more than 8 characters.
3. White space is not allowed and
4. A variable should not be a keyword
5. It should not contain any special characters.

Example of invalid names are
123
(area)
6th
%abc

Constants

A constant value is the one which does not change during the execution of a program. C supports several types of constants.
 1. Integer constants
 2. Real constants
 3. Single character constant
 4. String constants

Integer Constants
 An integer constant is a sequence of digits. There are 3 types of integers namely decimal integer, octal integers and hexadecimal integers.
  1. Decimal Integers consists of a set of digits 0 to 9 preceded by an optional + or -sign. Spaces, commas and non digit characters are not permitted between digits. Example for valid decimal integer constants are
123
-31
0
562321
+78

Some examples for invalid integer constant are
15 750
20,000
Rs. 1000


2. Octal Integer constant consists of any combination of digits from 0 through 7 with a O at the beginning.Some examples of octal integers are
O26
O
O347
O676

3. Hexadecimal Integer constants is preceded by OX or Ox, they may contain alphabets from A to F or a to f. The alphabets A to F refers to 10 to 15 in decimal digits. Example of valid hexadecimal integers are-
OX2
OX8C
OXbcd
Ox

Real Constants
   Real constants consists of a fractional part in their representation.Integer constant are inadequate to represent quantities that vary continuously. These quantities are represented by numbers containing fractional parts like 26.082.
Example of real constants are
0.0026
-0.97
435.29
+487.0
Real numbers can also be represented by exponential notation.

Single Character Constants
  A single Character constant represent a single character which is enclosed in a pair of quotation symbols.
Example for character constant are
'5'
'x'

String Constants
   A string constants is a set of character enclosed in double quotation marks. The character in a string constant sequence may be a alphabet, number, special character and blank space. Example of string constants are-
"IRAWEN"
"1234"
"God Bless"
"!....?"

Backslash Character Constant [Escape Sequence]
 Backslash character constants are special character used in output functions. Although they contain two characters they represent only one character.
For example "\n" is the new line character constant. and
    "\t" is to give a tab space for formatting.

Character Set, Keywords and Identifiers

Character Set
  The character set in C language can be grouped into the following categories.
   1. Letters
   2. Digits
   3. Special characters
   4. White spaces

White spaces are ignored by the compiler until they are a part of string constant.White space may be used to separate words, but are strictly prohibited while using between characters of keywords or identifiers.

C Character-set table



Special Characters



Keywords and Identifiers
  Every word in C language is a keyword or an identifier. Keywords in C language cannot be used as a variable name. They are specifically used by the compiler for own purpose and they serve as building blocks of a C program.
  
The following are the keyword set of C language.



Some compilers may have additional keywords.
  
Identifiers refers to the name of user-defined variables, array and functions. A variables should be essentially a sequence of letters and or digits and the variable name should begin with a character.
  
  Both uppercase and lowercase letters letters are permitted. The underscore character is also permitted in identifiers.

Friend Function

The private member function can not be accessed from outside the class. The non Member function can not access private data.

Sometimes there can be situation where we would like two classes to share a particular function.

In such a case, c++ allows the common function to be made friendly with both classes and so allows the function to have access to private data of the class.

Syntax:
  class abc
   {
     ........
     .........
     public:
     friend void xyz( );   //declaration
    };

The function definition does not use either keyword 'friend' or the scope resolution operator
  Definition void xyz ( )
                       {
                          .................
                          ..................
                         }

#include<iostream.h>
#include<conio.h>
class sample
{
int a;
int b;
public:
void setvalue( )
{
a=25;
b=40;
}
friend float mean(sample s);
};
float mean(sample s)
{
return float(s.a+s.b)/2.0;
}
void main( )
{
sample s1;
clrscr( );
s1.setvalue( );
mean(s1);
getch( );
}

Array of Objects

Any object whether built in or user defined, can be stored in an array. When you declare the array, you tell the compiler the type of object to store and the number of objects for which to allocate room.

The compiler know how much room is needed for each object based on the class declaration.

Consider the following class definition :
class vehicle
{
int vcode;
char vname[30];
public:
void getinfo( );
void disinfo( );
};

The identifier vehicle is a user defined data type and can be used to create objects that relate to a different categories of vehicles.


Example:

vehicle v1[3];     vehicle v2[4];

The array contains three objects namely , v1[0] , v1[1], v1[2] of type vehicle class. Similarly, v2 contains 4 objects namely v2[0], v2[1], v[2], v[3].

Accessing member data in an array of objects is a two step process. You identify the member of the array by using the index operator([]) and then you add the member operator(.) to access the particular member variable.

For Example:
v[i] disinfo( );

will display the data of the ith element of the array v1. That is, this statement request the objects v[i] to invoke the member function disonfo( ). An array of object is stored inside the memory in same way as a multi-dimensional array.

The array v1 represented in figure below



Here only the space for data items of object is created. Member function are stored separately and will be used by all the objects.

Write a program to declare a class book having data members as a title and author. Accept the data for five books and display the accepted data.

#include<iostream.h>
#include<conio.h>
class book
{
char auth[20];
char title[50];
public:
void accept( );
void display( );
};
void book::accept( )
{
cout<<"\n\n\tEnter Title of the book";
cin>>title;
cout<<"\n\n\tEnter Author Name";
cin>>auth;
}
void book::display( )
{
cout<<"\n\n\tBook Name--->"<<title;
cout<<"\n\n\tAuthor is--->"<<auth;
}
void main( )
{
book b[5];
int i;
clrscr( );
for(i=0;i<5;i++)
{
 b[i].accept( );
}
for(i=0;i<5;i++)
{
 b[i].display( );
}
getch( );
}


Output:-
   Enter Title of the book c_basic
   Enter Author Name ABC
   Enter Title of the book cpp
   Enter Author Name DEF
   Enter Title of the book java
   Enter Author Name PQR
   Enter Title of the book sql
   Enter Author Name XYZ
   Enter Title of the book php
   Enter Author Name MNO

Book Name--->c_basic
 Author is--->ABC
Book Name--->cpp
 Author is--->DEF
Book Name--->java
 Author is--->PQR
Book Name--->sql
 Author is--->XYZ
Book Name--->php
Author is--->MNO

Functions returning Objects

A function can not only receive the objects as argument but also returns objects from function.

Ex:
#include<iostream.h>
#include<conio.h>
class complex
{
float x;
float y;
public:
void input(float real,float img)
{
x=real;
y=img;
}
friend complex sum(complex, complex);
void show(complex);
};
complex sum(complex c1, complex c2)
{
complex c3;
c3.x=c1.x+c2.x;
c3.y=c1.y+c2.y;
return c3;
}
void complex::show(complex c)
{
cout<<"\t"<<c.x<<"+j"<<c.y;
}
void main( )
{
complex A,B,C;
clrscr( );
A.input(3.1,5.65);
B.input(2.75,1.2);
C=sum(A,B);
cout<<"\n\n\tComplex No A is--->";
A.show(A);
cout<<"\n\n\tComplex No B is--->";
B.show( );
cout<<"\n\n\tComplex No C is--->";
C.show( );
getch( );
}

Output:-
    Complex No A is--->3.1+j5.65
    Complex No B is--->2.75+j1.2
    Complex No C is--->5.85+j6.85

Object as Function Argument

An object can be used as a function argument.This can be done in two ways
 1. Pass by value
 2. Pass by reference

Pass by value :
  In pass by value, a copy of entire object is passed to the function so any change made to the object inside the function do not affect the object used to call the function.

Pass by reference :
  In pass by reference , only the object's address is transferred to the function. When an address of the object is passed, the called function works directly on the actual object used in the call.

So any change made to the object inside the function will affect in actual object.

Write a program to illustrate the use of objects as an function argument

#include<iostream.h>
#include<conio.h>
class time
{
int hours;
int minutes;
public:
void gettime(int h, int m)
{
hours=h;
minutes=m;
}
void puttime( )
{
cout<<hours<<"Hours And"<<minutes<<"Minutes"<<"\n";
}
void sum(time,time);
};
void time::sum(time t1, time t2)
{
minutes=t1.minutes+t2.minutes;
hours=minutes/60;
minutes=minutes%60;
hours=hours+t1.hours+t2.hours;
}
void main( )
{
time t1,t2,t3;
clrscr( );
t1.gettime(2,45);
t2.gettime(3,30);
t3.sum(t1,t2);
cout<<"\n\tT1::";
t1.puttime( );
cout<<"\n\tT2::";
t2.puttime( );
cout<<"\n\tT3::";
t3.puttime( );
getch( );
}


Output :-
  T1::2  Hours And 45 Minutes
  T2::3  Hours And 30 Minutes
  T3::6  Hours And 15 Minutes

Static Member Function

Member function may also be declared static by prefixing the static keyword in the function definition header.

A static member function can have access to only other static members declared in the same class.

A static member function can be called by using its class name.
  class_name::function_name( );

A static member function can not be virtual.

There should not be member function does not have 'this' pointer.

Write a program to demonstrate static member function.

#include<iostream.h>
#include<conio.h>
class test
{
int code;
static int count;
public:
void setdata( )
{
 code=++count;
}
void show( )
{
 cout<<"\n\n\tObject Number--->"<<code<<endl;
}
static void showcount( )
{
 cout<<"\n\n\tCount is--->"<<count<<endl;
}
};
int test::count;
void main( )
{
test t1,t2,t3;
clrscr( );
t1.setdata( );
t2.setdata( );
test::showcount( );
t3.setdata( );
test::showcount( );
t1.show( );
t2.show( );
t3.show( );
getch( );


Output:-
    Count is--->2
    Count is--->3
    Object Number--->1
    Object Number--->2
    Object Number--->3

Program Documentation

What is Documentation ?
  
Documentation consists of instructions for using a computer device of program.
  
Documentation can appear in a variety of forms, the most common being manuals.
  
When you buy a computer product (hardware or software), it almost always comes with one or more manuals that describe how to install and operate the product.
  
In addition, many software products include an online version of the documentation that you can display on your screen or print out on a printer.
  
A special type of online documentation is a help system, which has the documentation embedded into the program.

Documentation is often divided into the following categories

1) Installation : Describes how to install a program or device but not now to use it.
2) Reference : Detailed descriptions of particular items presented in alphabetical order. Reference documentation is designed for people who are already somewhat familiar with the product but need remainders or very specific information about a particular topic.
3) Tutorial : teaches a user how to use the product. Tutorials move at a slower pace than reference manuals and generally contain less detail.

Need for Documentation
  A software cannot be considered to be complete until it is properly documented. So proper documentation of software is necessary due to the following reasons.

More documentation means easier usage. As soon as a user gets stuck trying to get a program feature to work, he or she starts to read that program's documentation. Therefore, creating well-structured and well-written documentation will make it easy for the user to get that feature to work.

It makes program or software is easy to maintenance.

A well documented software is easy ti modify and maintain in the future.

It is easier to understand the logic of a program  from the documented records rather than its code.

Flowcharts or comments used within the programs are very helpful in understanding the functionality of the whole program. 

Documented records are quite helpful in restarting a software project that was postponed due to some reason or the other.

The job need not be started from scratch and the old ideas may still be easily recapitulated which saves lot of time and avoids duplication of work.(Reusability).

In general the following aspects of a program or project should be documented

1) Basic usage is mostly covered in a man page.
2) More advanced usage can be achieved by giving options in the documentation and giving examples on how to use them (take the very good Apache documentation for example).
3) Source code, of course, because somebody may want to add features to the program.
4) Example of usage (what input to give and expected output) to supply a working basic configuration file and document it heavily.
5) Installation of the program, because not all program work with easy ways.

Forms of Documentation
  The three commonly used forms for documenting software are-
Comments
  Comments can be useful for
  1. Describing an element
  2. Adding remarks and lists
  3. Describing parameters
  4. Describing methods/properties
  5. Providing examples
  6. Compiling the code.

System Manual
  A document which is used to maintain all the system details and its usage is a system manual. It consist of 

 1. The objectives of developing the software and its usefulness to various categories of users.
 2. Specifies program names along with their description and purpose.
 3. Detailed system flow charts cross-referenced to the listing.
 4. A source listing of all programs together with full details of any modifications made since.
 5. Specimen of all input forms and printed output records.

User Manual

 A document which is used by the user for understanding easy use(how to use) of any product is a user manual. It consists of-

 1. Operational details of each program.
 2. Loading and unloading procedures.
 3. Starting, running, and terminating procedures.
 4. A description and example of any control statement that may be used.
 5. List of errors condition with explanations for their re-entry into the system.
 6. List of program to be executed before and after execution of each program.

Friday, 30 March 2018

Static Data Members

To create a static data member only you have to proceed a member variables declaration with static keyword.

All static variables are automatically to zero value , when the first object of the class is created. No other initialization is permitted.

Only one copy of static data member is created for the entire class and is shared by the objects of that class.

Since static variables are associated with the class itself rather than object called as class variables.

static data member is visible only within the class but lifetime is entire program.

The type and scope of each static data member must be redefined outside the class definition because static data member are stored separately rather than as a part of object.


Syntax:

Data_type classname :: static_variable_name;
            The static variable must be declared in a class with a keyword static.

Write a Program to count the no of objects using static data member.

#include<iostream.h>
#include<conio.h>
class item
{
static int count;
public:
void getdata( )
{
count++;
}
void display( )
{
cout<<"\n\n\tNo of object count is--->"<<count;
}
};
int item::count;
void main( )
{
item x1,y1,z1;
x1.getdata( );
y1.getdata( );
z1.getdata( );
cout<<"\n\n\tAfter Reading Data is--->";
x1.display( );
y1.display( );
z1.display( );
getch( );
}


Output:-
    After Reading Data is--->
    No of object count is--->3
    No of object count is--->3
    No of object count is--->3

Destructor

A destructor is a special member function which is used to destroy the objects which has been created by constructor.

Name of the constructor is same as the class name.
Destructor is preceded by tilde symbol(~)

Ex. For the class Integer , Destructor is
   ~Integer( )
      {
      
     }


Destructor should be declared in a public section only.

It is good practice to declare destructor in a program since it releases memory for future use.

Destructor is invoked implicitly by compiler when exit from the scope of the object to clean up the storage that is no longer accessible.

Destructor neither take any argument nor return any value.

#include<conio.h>
#include<iostream.h>
int count=0;
class alpha
{
public:
alpha( )
{
   count++;
   cout<<"\n\tNo of object created--->"<<count;
}
~alpha( )
{
   cout<<"No of object destroyed --->"<<count;
   count--;
 }
};
void main( )
{
 clrscr( );
  {
  cout<<"\n\tEnter into main function";
  alpha a1,a2,a3,a4;
 }
{
 cout<<"\n\tEnter Block 1";
 alpha a5;
}
{
cout<<"\n\tEnter Block 2";
 alpha a6;
}
cout<<"\n\tRe Enter main";
}
getch( );
}


Output:-
  Enter into main function
  No of object created--->1
  No of object created--->2
  No of object created--->3
  No of object created--->4
  Enter Block 1
  No of object created--->5
  No of object destroyed --->5
  Enter Block2
  No of object created--->5
  No of object destroyed --->5
  Re Enter main
  No of object destroyed --->4
  No of object destroyed --->3
  No of object destroyed --->2
  No of object destroyed --->1

Constructor with default arguments

It is possible to define constructor with default arguments.

Default argument must be trailing arguments.

Default argument of the constructor can be overrides by sending the values from calling function.

Let consider 
      Complex(float real, float imag=0);
  The Default value of the argument imag is zero.

The Statement Complex c(2.0);
  Will assign 2.0 to real and 0(zero) to imag.

The Statement Complex c(2.0,3.0);
  Assigns 2.0 to real and 3.0 to imag.

In Such a way when actual parameters if specified overrides the default values.

Ex:-   Declare a class 's1' having data members principle, rate_of_int and no_of_yrs. The constructor will have default values for rate_of_int as 11.5%. Accept the data for two objects and display simple interest for each object.

#include<conio.h>
#include<iostream.h>
class S1
{
float principle,si,rate_of_int,no_of_yrs;
public:
S1(float p, float n_o_y,float r_o_i=11.5)
{
   principle=p;
   no_of_yrs=n_o_y;
   rate_of_int=r_o_i;
}
void calculate( )
{
si=(principle*rate_of_int*no_of_yrs)/100;
}
void display( )
{
cout<<"\n\tSimple INterest is --->"<<si;
}
};
void main( )
{
S1 s1(7800.0f,5.0f);
S1 s2(8500.0f,8.0f);
S1 s3(5000.0f,6,12.2f);
clrscr( );
s1.calculate( );
s2.calculate( );
s3.calculate( );
s1.display( );
s2.display( );
s3.display( );
getch( );
}

Output:-
     Simple INterest is --->4485
     Simple INterest is --->7820
     Simple INterest is --->3660

Constructor Overloading

Cpp permits to use the constructor like default, copy or parameterized constructor in the same class.

Constructor overloading means using multiple constructor in the class having different no og arguments and different types of argument.

Ex:

class abc
{
int m,n;
public:
abc( )
{
 m=0;
 n=0;
}
abc(int a, int b)
 {
  m=1;
  n=b;
 }
abc(abc &k)
 {
  m=k.m;
  n=k.n;
 }
};


Above class declares three constructor for the abc object.
→ The Statement abc a1;

Invokes the first constructor and set both m and n of a1 to zero.
→ The Statement abc a2(20,40);

Invokes the second constructor and set both m and n of a2 to 20 and 40 respectively.
→ The Statement abc a3(a2);

Invokes the third constructor and copies the value of data member of a2 to data member of a3.

#include<conio.h>
#include<iostream.h>
class abc
{
int m,n;
public:
abc( )
{
   m=0;
   n=0;
}
abc(int a, int b)
{
   m=a;
   n=b;
}
abc(abc &k)
{
m=k.m;
n=k.n;
}
void display( )
{
  cout<<"\n\tValue of m is--->"<<m;
  cout<<"\n\tValue of n is--->"<<n;
 }
};
void main( )
{
abc a1;
abc a2(20,40);
abc a3(a2);
clrscr( );
a1.display( );
a2.display( );
a3.display( );
getch( );
}


Output:-
    Value of m is--->0
    Value of n is--->0
    Value of m is--->20
    Value of n is--->40
    Value of m is--->20
    Value of n is--->40

Constructor

A constructor is a member function whose task is to allocate the memory and initialize the object of the class.

It's special member function because its name and class name is name.

The constructor in invoked whenever an object of its associated class is created.

It is called as constructor because its construct the value of data member of the class.

Constructor function should be declared in public section.

Constructor do not have return , not even void so it can not return any type of value.

Constructor function can not be inherited but derived class can the base class constructor.

Constructor can not have default argument.

Constructor can not be virtual.

Constructor make implicit calls to the operators new and delete when memory allocation is required.




When you declare the object as follows
time t1;

Then object will get initialized automatically that is data members hours and minutes will be initialized to a value zero.

Therefore there is no need to write any statement to invoke the constructor function.

Different Types of Constructor
  1. Default Constructor
  2. Parameterized Constructor
  3. Copy Constructor
  4. Dynamic Constructor

Default Constructor :-
 A constructor that accepts no arguments is called as default constructor.

The default constructor for class Emp is
   Emp::Emp( )

 If no such a constructor is defined then compiler supplies a default constructor.

Statement Emp x;
 Invokes default constructor while creating object 'x';

Ex:
 #include<conio.h>
 #include<iosteam.h>
 class sample
 {
 int k;
 public:
 sample( )
 {
  k=0;
  }
  void display( )
  {
  cout<<"\n\tValue of k is --->"<<k;
   }
  };
  void main( )
   {
    sample obj1;
    clrscr( );
    obj1.display( );
     getch( );
    }

Output:-
   Value of k is --->0

Parameterized Constructor :

 A constructor with arguments / parameters is called as parameterized constructor.
 As we know that each object has separate memory for data members sometime.It becomes necessary to initialize each object with different values when they are created.

Then these arguments help to initialize an object when it is created.
 To create parameterized constructor, simply add parameters to it as you add to any function.

Write a program to declare class student having data members name and percentage. Write a constructor to initialize these data members and display them.

#include<iostream.h>
#include<conio.h>
#include<string.h>
class student
{
 private:
 char name[20];
 float per;
 public:
 student(char n[20],float p)
 {
  strcpy(name,n)
  per=p;
  }
  void display( )
  {
   cout<<"\n\tName is --->"<<name;
   cout<<"\n\tPercentage is --->"<<per;
   }
  };
 void main( )
  {
   student s1("Irawen",99.92);
   s1.display( );
   getch( );
 }

Output:-
   Name is --->Irawen
   Percentage is --->99.92

Copy Constructor 
   A constructor can accept a reference to its own class as a parameter which is called as copy constructor.
   A copy constructor takes a reference to an object of the same class as itself as an argument.
   A copy constructor can be used to declare and initialize an object of another object.

Ex:
 Class Time
 {
 ..........
 public:
 Time(Time &t)  //Copy Constructor
  {
   }
 };
→ Time T2(T1);
      It define the object t2 and at the same time initialize it to have of t1.
→ Statements T2=T1;
      This will not invoke copy constructor.If T1 and T2 are the objects,this statement is legal and simply assigns the value of T1 and T2 member by member.

Write a program to implement copy constructor

#include<iostream.h>
#include<conio.h>
class code
{
 int id;
 public:
 code(int a)
 {
  id=a;
  }
  code(code &x)
  {
   id=x.id;
   }
   void display( )
   {
    cout<<"\t"<<id;
    }
   };
  void main( )
   {
    code A(100);
    code B(A);
    code C=A;
    clrscr( );
    cout<<"\n\t ID of A is --->";
    A.display( );
    cout<<"\n\t ID of B is --->";
    B.display( );
    cout<<\n\t ID of C is --->";
    C.display( );
     getch( );
   }

Output:-
   ID of A is --->100
   ID of B is --->100
   ID of C is --->100

Access Control In Classes OR Access Modifiers

Access specifiers in C++ class defines the access control rules. C++ has 3 new keywords introduced, namely,

1. public
2. private
3. protected

These access specifiers are used to set boundaries for availability of members of class be it data members of  members or member functions

Access specifiers in the program, are followed by a colon. You can use either one, two or all 3 specifiers in the same class to set different boundaries for different class members. They change the boundary for all the declarations that follow them.

Public
 Public, means all the class members declared under public will be available to everyone. The data members functions declared public can be accessed by other classes too.
  Hence there are chances that they might change them. So the key members must not be declared public.

Private
  Private keyword, means that no one can access the class members declared private outside that class. If someone tries to access the private member , they will get a compile time error. By default class variables and member functions are private.

  class PrivateAccess
  {
   private:    // private access specifier
   int x;       // Data Member Declaration
   void display( );  //Member Function declaration
   }

Protected
  Protected, is the last access specifier, and it is similar to private, it makes class member inaccessible outside the class. But they can be accessed by any subclass of that class.

 class ProtectedAccess
 {
   protected:    // protected access specifier
   int x;           // Data Member Declaration
   void display( );   // Member Function declaration
   }
  

Memory Allocation for objects

Memory for the object is allocated when they are declared and not when class is specified.Since all the objects belonging to the same class use the same member function, no separate space is allocated for functions when objects are created.

 But the space for data member are allocated for each object because separate memory locations for the objects are essential and each object can hold different values.



Thursday, 29 March 2018

Concept of API / Libraries

Application Programming Interface (API) is an interface in computer science that defines the ways by which an application program may request services from libraries and/ or operating system.It is a set of routines, protocols and tool for building software applications.
  
A good API makes it easier to develop a program by providing all the building blocks.
   
Although APIs are designed for programmers, they are ultimately good for users because they guarantee that all program using a common API will have similar interface. This makes it easier for users to learn new programs.

Concept of  'C' Library
   The C standard library consists of a set of sections of the ISO C standard which describe a collection of header files and library routines used to implement common operations, such as input/output and string handling, in the C programming language.

Following are some important header files :

   Stdio.h, which stands for "standard input/output header" , is the header in the C standard library that contains macro definitions, constant and declarations of functions and types used for various standard input and output operation.
   
   String.h is the header in the C standard library for the C programming language which contains macro definition, constant and declarations of functions and types used not only for string handling but also various memory handling functions; the name is thus something of a misnomer.

    Function declared in string.h are extremely popular, since as a part of the standard library, they are guaranteed to work on any platform which supports C.
  
    Math.h is a header files in the standard library of C programming language designed for basic mathematical operation. Most of the functions involve the use floating point numbers. C++ also implements these functions for compatibility reasons and declares them in the header cmath.

Debugging a Program for Syntax Errors and Logical Errors


Debugging a Program for Syntax Errors
As compared to logical errors, syntax errors are much easier to locate and correct because almost all language processor are designed to detect syntax errors automatically.

A single syntax error often cause multiple error messages to be generated by the language processor.

Removal of the syntax error will result in the removal of all associated error messages.

Debugging a Program for Logical Errors
  Logical errors are much more difficult to detect the syntax errors as computer does not produce any error message for such errors.
  
One or more following methods are commonly used to detect the logical errors :
      
Doing hand simulation of the program code :
 One approach is to take the printout of the source code of the program and go through its execution manually with the test data input that produced incorrect results.
       
Putting the print statement in the program code
Another approach is to put several print or write statements at appropriate locations in the program so that the values of different variables can be displayed to indicate intermediate computations results.

  Using a debugger :
    This is the most commonly used approach. Debugger is the software program the assist a programmer in following a program's execution step-by-step allowing him to display intermediate calculation results.
    
Using memory dump :
     This approach is used when the program "hang up" during a test run.

Testing a Program

For most programs, it is practically impossible to prove that the program is correct on all inputs.Instead, you must try to convince skeptics that it mostly works right, by testing the program on various inputs and documenting what you have done.

This documentation is called a test plan and you must provide one with each program.

The test plan describes how you intend to test your program, that is, which inputs you plan to test it on and why those are good choices.

The results of running a set of tests is a test log, which shows the results produced by the tests in the test plan. The log should demonstrate that each test produced the output predicted by the test plan.

Developing a Test Plan
  The programs written for this course will require you to test the execution of your programs on various sets of inputs to demonstrate program functionality. These input sets or test cases, will be of your own choosing, but the following guidelines should be followed :

        Input sets should be ordered logically, preferably in the same order as the code being tested.

        When there are only a few possible inputs, test them all.

        If your program does not handle certain inputs, the ASSUMPTIONS section of the program header must indicate precisely which inputs are not handled in the program.

Format for Program Test Document
  Test results must be submitted separately on paper, even if the program may be submitted on disk or electronically. The program test document should be organized as follows :
    1. Your name ( and the names of any people you work with).
    2. The name of the programming assignment (e.g., Program 1).
    3. Rationale behind chosen test cases(inputs). Note that you MUST include some justification for each test case, even if it is something as simple as testing the program on odd or even numbers.
    4. Printouts of output files for each separate input set (i.e., test logs).


Program Testing and Debugging

A software bug (or just "bug") is an error, flaw, mistake, failure, fault or "undocumented feature" in a computer program that prevents it from behaving as intended (e.g., producing an incorrect result).

Most bugs arise from mistakes and errors made by people in either a program's source code or its design and a few are caused by compilers producing incorrect code.

Formal Program Testing
                The software industry is primarily concern with logical errors and hidden run-time errors. Companies expend enormous effort to find the errors before the release. To fix a bug after the release cost a 100 times more; patches must be designed and ship out.Besides the customer are not very happy. So, there is the necessity of program testing before it goes to the end user.
   The industry is concerned with Verification and Validation :
               Validation or appropriate :
                  Techniques for insuring validation :
                         Inspection code at a high level
                         Have the user/customer test software
                         Requires good software specification

                Verification or correctness :
                         Is the program producing the correct answers ?
                         Techniques for insuring verification :
                              Code walk through of inspection
                              Testing

Testing
    Testing is the primary technique for the above two Vs :
        Testing uses input data and observes output.
             There may be additional output then in the final product.
             The evaluation may include more then just the correctness of the output.
             Testing can be at the component level or integrated level.

Debugging
   Debugging is a methodical process of finding and reducing the number of bugs or defects, in a computer program or a piece of electronic hardware thus making it behave as expected. Debugging tends to be harder when various subsystem are tightly coupled, as changes in one may cause bugs to emerge in another.

Difference between Testing and Debugging



Types of Program Errors
  There are three basic errors :
    1. Syntax/Compilation error
    2. Run-time exception error
    3. Logical error

Syntax / Compilation Error
   Error during compiling prevents getting a compiled code. Modern compilers indicate well the location of the error. Sometimes problems with delineators such as semicolons in C or brackets in C++.

Run-time Exception Error
  When you get an error message while running the compiled code. Java gives good error messages indicating the location of the error but that might not be the location of the actual error.Some languages, such as C seem to have only one type of error; segmentation fault or Fortran, index out of bounds.

Logical Error
  These errors are the hardest to correct or detect. The program "runs" but the output is not correct.
     
Tools for detecting and fixing logical error :
      1. Choose test cases well. Try to cover everything with small cases. Try one big case.
      2. Print intermediate value. Use a boolean variable to turn on and off debug printing.
      3. Walk though. Play computer in front of an audience (if you can) and suspect all code especially uncommitted code.

Logical errors generally occur at :
Loops : 
    Check the range of for loops and the boolean expression of while loop.
  
Ifs :
    Check complicated boolean expressions (more than one variables) and especially if you are using negation.

Popular Posts

Categories

100 Python Programs for Beginner (13) AI (33) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (161) C (77) C# (12) C++ (82) Course (67) Coursera (223) Cybersecurity (24) data management (11) Data Science (127) 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 (53) Meta (22) MICHIGAN (5) microsoft (4) Nvidia (1) Pandas (3) PHP (20) Projects (29) Python (917) Python Coding Challenge (304) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (2) Software (17) SQL (42) UX Research (1) web application (8)

Followers

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