Showing posts with label Object Oriented Programming. Show all posts
Showing posts with label Object Oriented Programming. Show all posts

Thursday, July 14, 2011

C LANGUAGE GENERAL TERM

C LANGUAGE GENERAL TERM

Variable

A variable is used to hold data within your program. A variable represents a location in your computer's memory. You can put data into this location and retrieve data out of it. Every variable has two parts, a name and a data type.

Variable Names

  • Valid names can consist of letters, numbers and the underscore
  • The first character must not start with a number.
  • A variable name may not be a C keyword.
  • Variable names are case sensitive. So, Age, AGE, aGE and AgE could be names for different variables
  • No special symbols other than underscore (such as fourth_Dimension).

Keyword

Keywords are reserved identifier and they can not be used as names for the program variables or other user defined program elements. The meanings of the keywords have already been given to the compiler. The keywords are also called reserved words.

List of C Keywords

auto
double
if
static
break
else
int
struct
case
enum
long
switch
char
extern
near
typedef
const
float
register
union
continue
far
return
unsigned
default
for
short
void
do
goto
signed
while

Data Types

C provides built in data types for character, float and integer data. As an aside, in C you may assign a value to a variable when you declare it.

Integer variables

Integer variables are used to store whole numbers. There are several keywords used to declare integer variables, including int, short, long, unsigned short, unsigned long. The difference deals with the number of bytes used to store the variable in memory, long vs. short, or whether negative and positive numbers may be stored, signed vs. unsigned. These differences will be explained in more advanced tutorials. For now, use int to declare integer variables. On most 32-bit systems, int is synonymous with signed long.
Examples:
int count;
int number_of_students = 30;

Float variables

Float variables are used to store floating point numbers. Floating point numbers may contain both a whole and fractional part, for example, 52.7 or 3.33333333. There are several keywords used to declare floating point numbers in C including float, double and long double. The difference here is the number of bytes used to store the variable in memory. Double allows larger values than float. Long double allows even larger values. These differences will be explained in more advanced tutorials. For now, use float to declare floating point variables.
Examples:
float owned = 0.0;
float owed = 1234567.89;

Character variables

Character variables are used to store character values. The use of characters and strings will be covered in a latter tutorial. Character variables are declared with the keyword char.
Examples:
char firstInitial = 'J';
char secondInitial = 'K';

Datatypes in C

Data Type
Category
Range
Bytes
Format
Character
signed char
-128 to +127
1
%c
unsigned char
0 to 255
1
%c
Integer
short signed int
-32768 to +32767
2
%d
short unsigned int
0 to 65535
2
%u
signed int
-32768 to +32767
2
%d
unsigned int
0 to 65535
2
%u
long signed int
-2147483648 to +2147483647        
4
%ld
long unsigned int
0 to 4294967295
4
%lu
Float
float
-3.4e38 to +3.4e38
4
%f
Double
double
-1.7e308 to +1.7e308
8
%lf
long double
-1.7e4932 to +1.7e4932
10
%Lf

Constants

A constant is similar to a variable in the sense that it represents a memory location. It differs, as I sure you can guess, in that it cannot be reassigned a new value after initialization. In general, constants are a useful feature that can prevent program bugs and logic errors. Unintended modifications are prevented from occurring. The compiler will catch attempts to reassign new values to constants.
#include
void main()
{
       int pi=3.1415; /*constant value of pi*/
       int r=5;    /*constant value given to r varable */
       printf("Area of circle=%d",pi*r*r);
}

Using const variables

The second technique is to use the keyword const when defining a variable. When used the compiler will catch attempts to modify variables that have been declared const.
const float pi = 3.1415;
const int id_no = 12345;
There are two main advantages over the first technique. First, the type of the constant is defined. "pi" is float. "id_no" is int. This allows some type checking by the compiler. Second, these constants are variables with a definite scope. The scope of a variable relates to parts of your program in which it is defined. Some variables may exist only in certain functions or in certain blocks of code. You may want to use "id_no" in one function and a completely unrelated "id_no" in your main program. Sorry if this is confusing, the scope of variables will be covered in a latter

Do You Need To Know C Before Learning C++?

Do You Need To Know C Before Learning C++?

Although this question is still a source of debate, and many including the author of this article learned C first, I believe the answer is no. The features of C are supported by C++. After learning C++ you will be able to read and understand most of what you would see in any C program you might encounter and can fill in any missing details easily. Additionally, the techniques used to solve programming problems in an object-oriented language such as C++ differ from a procedural language such as C. C programmers who need to study C++ must unlearn some of their programming techniques and replace them with techniques for object-oriented design.

THE HISTORY OF C AND C++

THE HISTORY OF C AND C++

A Brief History Of C

The C programming language was developed at Bell Labs during the early 1970's. Quite unpredictably it derived from a computer language named B and from an earlier language BCPL. Initially designed as a system programming language under UNIX it expanded to have wide usage on many different systems. The earlier versions of C became know as K&R C after the authors of an earlier book, "The C Programming Language" by Kernighan and Ritchie. As the language further developed and standardized, a version know as ANSI (American National Standards Institute) C became dominant. As you study this language expect to see references to both K&R and ANSI C. Although it is no longer the language of choice for most new development, it still is used for some system and network programming as well as for embedded systems. More importantly, there is still a tremendous amount of legacy software still coded in this language and this software is still actively maintained.

A Brief History Of C++

Bjarne Stroustrup at Bell Labs initially developed C++ during the early 1980's. It was designed to support the features of C such as efficiency and low-level support for system level coding. Added to this were features such as classes with inheritance and virtual functions, derived from the Simula67 language, and operator overloading, derived from Algol68. Don't worry about understanding all the terms just yet, they are explained in About's C++ tutorials. C++ is best described as a superset of C, with full support for object-oriented programming. This language is in wide spread use.

Differences between C and C++

Although the languages share common syntax they are very different in nature. C is a procedural language. When approaching a programming challenge the general method of solution is to break the task into successively smaller subtasks. This is known as top-down design. C++ is an object-oriented language. To solve a problem with C++ the first step is to design classes that are abstractions of physical objects. These classes contain both the state of the object, its members, and the capabilities of the object, its methods. After the classes are designed, a program is written that uses these classes to solve the task at hand.


PROGRAMMING CONCEPT

PROGRAMMING CONCEPT

The earliest computers

It is an astonishing fact that as we enter the 21st century, computers has been around for less than 60 years. Many of those who worked on the earliest computer are still alive to tell us of their experiences. If you ever get a chance to visit Bletchley Park, don't miss it - it is the location of the breaking of the Enigma code (used by the Germans to code all their most secret messages), with the aid of the first programmable computer, named Colossus, built for this purpose in 1943. A fascinating exhibition the fie story and Colossus has been reconstructed there.

Generations of programming language

Machine language - the first generation

Programming languages are often characterised by 'generation'- The first generation of computer language, known as machine code, executes directly without translation. Machine code is the actual pattern of 0s and 1s used in a computer's memory. The programming of Colossus and other early computers was laboriously done with toggle switches representing a pattern of binary codes for each instruction.
Machine language, however it is entered into a computer, is time-consuming, laborious and error-prone. Few programmers code in it today. A language suited to fie particular application would be used instead.

Assembly code - the second generation

In the 1950s when computers were first used commercially, machine code gave way to assembly code, which allowed programmers to use mnemonics (abbreviations that represent the instructions in a more memorable way) and denary numbers (i-e.0-9) instead of 0s and 1s. Thus ADD or ADX might be an instruction to add two numbers, SIJB or SBX an instruction to subtract.
Programs written in assembly languages have to be translated into machine code before they can be executed, using a program called an assembler-There is more or less a one-to-one correspondence between each assembly code statement and its equivalent machine code statement, which means that programs can be written in the most efficient way possible, occupying as little space as possible and executing as fast as possible. For this reason assembly code is still used for applications where timing or storage space is critical. Assembly languages are called low level languages because they are close to machine code and the detail of the computer architecture.
Since different types of computer have different instruction sets, which depend on how the machine carries out the instructions, both machine code and assembly code are machine-dependent - each type of computer will have its own assembly language.

lmperative high level languages - the third generation

As computer use increased dramatically in the 1950s, the need grew to make it easier and faster to write error-free programs. Computer manufacturers and user groups started to develop so-called high-level languages such as Algol (standing for AlGOrithmic Language) and Fortran (standing for FORmula TRANslation).In the 1950s most of the people actually writing programs were scientists, mathematicians and engineers and so both these languages were created to be used in mathematical applications.
COBOL (Common Business Oriented Language) was invented by the redoubtable Admiral Grace Hopper in 1960 specifically for writing commercial and business, rather than scientific, programs.-Whilst serving in the US Navy in 1947, Grace Hopper was investigating why one of the earliest computers was not working, and discovered a small dead moth in the machine. After removing it (and taping it in her logbook) the machine worked fine, and from then on computer errors were known as 'bugs'.
Other third generation languages followed: BASIC was created in the 1960s as a language for students to learn programming. Early versions of the language however did not contain the facilities to write well-structured programs that were easy to maintain and debug, although the language has since developed. In I97l Nicklaus Wirth designed Pascal (named after the seventeenth century French mathematician) to teach structured programming to students.
High level languages are so-called because they are independent of the architecture of any particular computer; one statement written in a high level language is translated into several machine code instructions before it can be executed. The term imperative high level language refers to languages such as Pascal, BASIC, COBOL and FORTRAN - in contrast to object-oriented and declarative languages, which you will learn about in the second year of this course.

Fourth-Generation programming language

A fourth-generation programming language (4GL) is a programming language closer to human languages than typical high-level programming languages. Such languages arose after the introduction of modern, block-structured third-generation programming languages, which improved the process of software development. Most 4GLs are used to access databases. For example, a typical 4GL command is
SQL > SELECT * FROM tblStudent WHERE gender='Male'
Why use assembly code?
Assembly language, although it is laborious to write and hard to debug, is still used in some circumstances, for example:
  • when there is a need for the program to execute as fast as possible;
  • when the program must occupy as little space as possible;
Parts of an operating system, and device drivers that control the operation of devices such as a printer, mouse or CD-ROM may be written in assembly code. Programs in embedded systems like satellite decoders, encryption and decryption software, and routines that are called frequently from high-level programs may also be written in assembly code.

Types of program translator

There are three types of program used for translating the code that a programmer writes into a form (i.e. machine code) that the computer can execute. These are:
  • assembler
  • compiler
  • interpreter.

Assembler

An assembler is a program that translates an assembly code program into machine code ready for the computer to execute it. Since each type of computer has its own assembly language, it also has its own assembler. The assembler itself could be written in assembly code or in a high level language such as C, which has special facilities useful for this type of programming.

Compiler

A compiler is a program that translates a high level language program into machine code. The Turbo Pascal compiler, for example, translates a program written in Turbo Pascal on a PC into object code, which can be run on a PC. The code written by the programmer is known as the source code, and the compiled code is known as the object code.
A compiler is a complex program which takes the source code and scans through it several times, each time performing different checks and building up tables of information needed to produce the fina1 object code. When you write a short program, this process appears to happen almost instantaneously, but a long program of several thousand lines can take several minutes to compile.
Compiler: Translates the whole high level language source code into object code, which can then be executed without the presence of a compiler.

Interpreter

An interpreter also translates high-level source code. However the crucial difference between a compiler and an interpreter is that an interpreter translates one line at a time and then executes it; no object code is produced, and so the program has to be interpreted each time it is to be run. If the program performs a section of code 10,000 times, then that section of code is translated into machine code 10,000 times as each line is interpreted and then executed.
Interpreter: Analyses the source code statement by statement as execution proceeds decoding each statement and calling routines to carry out each instruction.

Relative advantages of compilers and interpreters

A compiler has many advantages over an interpreter:
  • the object code can be saved on disk and run whenever required without the need to recompile. However, if an error is discovered in the program, the whole program has to be recompiled.
  • the object code executes faster than interpreted code.
  • the object code produced by a compiler can be distributed or executed without having to have the compiler present.
  • the object code is more secure, as it cannot be read without a great deal of 'reverse engineering'.

An interpreter has some advantages over a compiler:

  • it is useful for program development as there is no need for lengthy recompilation each time an error is discovered.
  • it is easier to partially test and debug programs.
Typically, a programmer might use an interpreter during program development. A program that is tested and ready for distribution would then be compiled and the saved object code would be distributed.

Wednesday, July 13, 2011

FEATURES Of Object Oriented Programming

FEATURES OF OOP

Figure: Class and Object

Figure: Inheritance

Objects

When you approach a programming problem in an object-oriented language, you no longer ask how the problem will be divided into functions, but how it will be divided into objects. Thinking in terms of objects, rather than functions, has a surprisingly helpful effect on how easily programs can be designed. This results from the close match between objects in the programming sense and objects in the real world. Example of objects: Car, Actor, Student, ect.

Class

A class is a template for an object, a user-defined datatype that contains variables, properties, and methods. A class defines the abstract characteristics of a thing (object), including its characteristics (its attributes, fields or properties) and the things it can do (behaviors, methods, operations or features). One might say that a class is a blueprint or factory that describes the nature of something. For example, the class Dog would consist of traits shared by all dogs, such as breed and fur color (characteristics), and the ability to bark and sit (behaviors). Classes provide modularity and structure in an object-oriented computer program. A class should typically be recognizable to a non-programmer familiar with the problem domain, meaning that the characteristics of the class should make sense in context. Also, the code for a class should be relatively self-contained (generally using encapsulation). Collectively, the properties and methods defined by a class are called members.

 Method

Method is a set of procedural statements for achieving the desired result. It performs different kinds of operations on different data types. In a programming language, methods (sometimes referred to as "functions") are verbs. Lassie, being a Dog, has the ability to bark. So bark() is one of Lassie's methods. She may have other methods as well, for example sit() or eat() or walk() or save(Timmy). Within the program, using a method usually affects only one particular object; all Dogs can bark, but you need only one particular dog to do the barking.

Message passing

"The process by which an object sends data to another object or asks the other object to invoke a method." Also known to some programming languages as interfacing. For example, the object called Breeder may tell the Lassie object to sit by passing a "sit" message that invokes Lassie's "sit" method. The syntax varies between languages, for example: [Lassie sit] in Objective-C. In Java, code-level message passing corresponds to "method calling". Some dynamic languages use double-dispatch or multi-dispatch to find and pass messages.

Inheritance

Inheritance is a process in which a new class (Derived Class)  inherits all the state and behavior of another existing class (Base Class). This type of relationship is called child-Parent or is-a relationship. "Subclasses" are more specialized versions of a class, which inherit attributes and behaviors from their parent classes, and can introduce their own.
For example, the class Dog might have sub-classes called Collie, Chihuahua, and GoldenRetriever. In this case, Lassie would be an instance of the Collie subclass. Suppose the Dog class defines a method called bark() and a property called furColor. Each of its sub-classes (Collie, Chihuahua, and GoldenRetriever) will inherit these members, meaning that the programmer only needs to write the code for them once.
Each subclass can alter its inherited traits. For example, the Collie subclass might specify that the default furColor for a collie is brown-and-white. The Chihuahua subclass might specify that the bark() method produces a high pitch by default. Subclasses can also add new members. The Chihuahua subclass could add a method called tremble(). So an individual chihuahua instance would use a high-pitched bark() from the Chihuahua subclass, which in turn inherited the usual bark() from Dog. The chihuahua object would also have the tremble() method, but Lassie would not, because she is a Collie, not a Chihuahua. In fact, inheritance is an "a... is a" relationship between classes, while instantiation is an "is a" relationship between an object and a class: a Collie is a Dog ("a... is a"), but Lassie is a Collie ("is a"). Thus, the object named Lassie has the methods from both classes Collie and Dog.
Multiple inheritance is inheritance from more than one ancestor class, neither of these ancestors being an ancestor of the other. For example, independent classes could define Dogs and Cats, and a Chimera object could be created from these two that inherits all the (multiple) behavior of cats and dogs. This is not always supported, as it can be hard to implement.

Abstraction

Abstraction refers to the act of representing essential features without including the background details or explanations. Classes use the concept of abstraction and are defined as a list of abstract attributes.

Encapsulation

Encapsulation conceals the functional details of a class from objects that send messages to it.
For example, the Dog class has a bark() method variable, data. The code for the bark() method defines exactly how a bark happens (e.g., by inhale() and then exhale(), at a particular pitch and volume). Timmy, Lassie's friend, however, does not need to know exactly how she barks. Encapsulation is achieved by specifying which classes may use the members of an object. The result is that each object exposes to any class a certain interface - those members accessible to that class. The reason for encapsulation is to prevent clients of an interface from depending on those parts of the implementation that are likely to change in the future, thereby allowing those changes to be made more easily, that is, without changes to clients.

Polymorphism

Polymorphism allows the programmer to treat derived class members just like their parent class's members. More precisely, Polymorphism in object-oriented programming is the ability of objects belonging to different data types to respond to calls of methods of the same name, each one according to an appropriate type-specific behavior. One method, or an operator such as +, -, or *, can be abstractly applied in many different situations. If a Dog is commanded to speak(), this may elicit a bark(). However, if a Pig is commanded to speak(), this may elicit an oink(). Each subclass overrides the speak() method inherited from the parent class Animal.

Reusability

The concept of inheritence provides an important feature to the object-oriented lanuage-reusability. A programmer can take an existing class and, without modifying it, and additional features and capabilities to it. This is done by deriving a new class from an existing class.