You are on page 1of 48

Computers are electronic information-processing machines.

Data and programs in these machines are saved, moved, and transformed in the form of electrical voltages. These electrical voltages can be interpreted as a zeros and ones. The zeros and ones can be aggregated and interpreted as words, numbers, images, sounds, and so on. Long ago, information be it data or programs could be entered into the computer by manipulating switches on the front of the machine. Today, there are better methods. Computer programming languages convert text into the requisite binary instructions. If your computer could understand English, you would not have to learn a programming language. But because it does not understand English, you must learn to write instructions in a language your computer recognizes.

Early computers were programmed in machine language. To see how instructions are written in machine language, suppose you want to use the equation: wages = rate * hours to calculate weekly wages. Further, suppose that the binary code 100100 stands for load, 100110 stands for multiplication, and 100010 stands for store. In machine language, you might need the following sequence of instructions to calculate weekly wages: 100100 010001 100110 010010 100010 010011 To represent the weekly wages equation in machine language, the programmer had to remember the machine language codes for various operations. Also, to manipulate data, the programmer had to remember the locations of the data in the main memory. This need to remember specific codes made programming not only very difficult, but also error-prone.

The 1960s gave birth to structured programming. This is the method of programming supported by languages such as C. With structured languages, it was, for the first time, possible to write moderately complex programs fairly easily. Dividing a problem into smaller subproblems is called structured design. Each subproblem is then analyzed, and a solution is obtained to solve the subproblem. The solutions to all of the subproblems are then combined to solve the overall problem. This process of implementing a structured design is called structured programming. The structured-design approach is also known as top-down design, bottom-up design, stepwise refinement, and modular programming. However, even with structured programming methods, once a project reaches a certain size, its complexity exceeds what a programmer can manage. By the late 1970s, many projects were near or at this point. To solve this problem, a new way to program began to emerge. This method is called object-oriented programming (OOP for short). Using OOP, a programmer could handle larger programs. The trouble was that C did not support object-oriented programming. The desire for an object-oriented version of C ultimately led to the creation of C++.

In response to the need to manage greater complexity, C++ was born. It was invented by Bjarne Stroustrup in 1979 at Bell Laboratories in Murray Hill, New Jersey. He initially called the new language C with Classes. However, in 1983 the name was changed to C++. C++ contains the entire C language. As stated earlier, C is the foundation upon which C++ is built. C++ includes all of C s features, attributes, and benefits. It also adheres to C s philosophy that the programmer, not the language, is in charge. At this point, it is critical to understand that the invention of C++ was not an attempt to create a new programming language. Instead, it was an enhancement to an already highly successful language.

Most of the additions that Stroustrup made to C were designed to support object-oriented programming. In essence, C++ is the object-oriented version of C. By building upon the foundation of C, Stroustrup provided a smooth migration path to OOP. Instead of having to learn an entirely new language, a C programmer needed to learn only a few new features to reap the benefits of the object-oriented methodology. But C is not the only language that influenced C++. Stroustrup states that some of its object-oriented features were inspired by another objectoriented language called Simula67. Therefore, C++ represents the blending of two powerful programming methods. When creating C++, Stroustrup knew that it was important to maintain the original spirit of C, including its efficiency, flexibility, and philosophy, while at the same time adding support for object-oriented programming. Happily, his goal was accomplished. C++ still provides the programmer with the freedom and control of C, coupled with the power of objects.

What Is Object-Oriented Programming? Since object-oriented programming was fundamental to the development of C++, it is important to define precisely what object-oriented programming is. Object-oriented programming has taken the best ideas of structured programming and has combined them with several powerful concepts that allow you to organize your programs more effectively. In general, when programming in an object-oriented fashion, you decompose a problem into its constituent parts. Each component becomes a self-contained object that contains its own instructions and data related to that object. Through this process, complexity is reduced and you can manage larger programs. All object-oriented programming languages have three things in common: encapsulation, polymorphism, and inheritance.

Encapsulation As you probably know, all programs are composed of two fundamental elements: program statements (code) and data. Code is that part of a program that performs actions, and data is the information affected by those actions. Encapsulation is a programming mechanism that binds together code and the data it manipulates, and that keeps both safe from outside interference and misuse. In an object-oriented language, code and data may be bound together in such a way that a selfcontained black box is created. Within the box are all necessary data and code. When code and data are linked together in this fashion, an object is created. In other words, an object is the device that supports encapsulation. Within an object, the code, data, or both may be private to that object or public. Private code or data is known to, and accessible only by, another part of the object. That is, private code or data may not be accessed by a piece of the program that exists outside the object. When code or data is public, other parts of your program may access it, even though it is defined within an object. Typically, the public parts of an object are used to provide a controlled interface to the private elements of the object.

Polymorphism Polymorphism (from the Greek, meaning many forms ) is the quality that allows one interface to be used for a general class of actions. The specific action is determined by the exact nature of the situation. A simple example of polymorphism is found in the steering wheel of an automobile. The steering wheel (i.e., the interface) is the same no matter what type of actual steering mechanism is used. That is, the steering wheel works the same whether your car has manual steering, power steering, or rackand-pinion steering. Therefore, once you know how to operate the steering wheel, you can drive any type of car. The same principle can also apply to programming. For example, consider a stack (which is a first-in, last-out list). You might have a program that requires three different types of stacks. One stack is used for integer values, one for floating-point values, and one for characters. In this case, the algorithm that implements each stack is the same, even though the data being stored differs. In a non-object-oriented language, you would be required to create three different sets of stack routines, calling each set by a different name, with each set having its own interface. However, because of polymorphism, in C++ you can create one general set of stack routines (one interface) that works for all three specific situations. This way, once you know how to use one stack, you can use them all.

Inheritance Inheritance is the process by which new classes called derived classes are created from existing classes called base classes. The derived classes have all the features of the base class and the programmer can choose to add new features specific to the newly created derived class. For example, a programmer can create a base class named fruit and define derived classes as mango, orange, banana, etc. Each of these derived classes, (mango, orange, banana, etc.) has all the features of the base class (fruit) with additional attributes or features specific to these newly created derived classes. Mango would have its own defined features, orange would have its own defined features, banana would have its own defined features, etc. Inheritance helps the code to be reused in many situations. The base class is defined and once it is compiled, it need not be reworked. Using the concept of inheritance, the programmer can create as many derived classes from the base class as needed while adding specific features to each derived class as needed. The above concept of reusability achieved by inheritance saves the programmer time and effort. Since the main code written can be reused in various situations as needed. Increases Program Structure which results in greater reliability.

C++ is a compiled language. This means that before the program is run, it is first translated into a form that the machine can use directly. The C++ files (and a typical project contains several) are called the source files. You create the source files by typing them using a program called a text editor. The translation of the source files into a program proceeds in two phases. First, the individual source files are translated by a program called the compiler into so called object files. Next, a second program, called a linker (or loader) combines the individual object files into an executable file, that is, a program you can execute (run). The precise manner in which is all this is done (source file creation/editing, compiling, linking, and execution) varies among different computing platforms.

The C++ language consists of two basic elements: Semantics: This is a vocabulary of commands that humans can understand and that can be converted into machine language, fairly easily. and Syntax: This is a language structure (or grammar) that allows humans to combine these C++ commands into a program that actually does something (well, maybe does something). To write a program, you need two specialized computer programs. One (an editor) is what you use to write your code as you build your .CPP source file. The other (a compiler) converts your source file into a machine-executable .EXE file that carries out your real-world commands (open spreadsheet, make rude noise, deflect incoming asteroid, whatever). Nowadays, tool developers generally combine compiler and editor into a single package a development environment. After you finish entering the commands that make up your program, you need only click a button to create the executable file.

What s a program? A computer program is simply a set of instructions to tell a computer how to perform a particular task. At the very simplest level it consists of issuing a sequence of commands to a computer to achieve an objective. A C++ program is a text file containing a sequence of C++ commands put together according to the laws of C++ grammar. This text file is known as the source file (probably because it s the source of all frustration). A C++ source file carries the extension .CPP just as a Microsoft Word file ends in .DOC or an MS-DOS (remember that?) batch file ends in .BAT. The concept extension .CPP is just a convention. It is not possible to execute this file directly. The source file is passed to a compiler (a program which generates a new file containing a machine code translation of the source text). This file is called an object file or executable file. The executable file is said to have been compiled from the source text.

All C++ programs are based on what are known as C++ statements. A statement is a single set of commands. All statements other than comments end with a semicolon. Unlike some other programming languages, such as COBOL, C++ is a free-form language, meaning that programming statement can start in any column of any line. You can insert blank lines in a program if you want. A declaration is a statement that defines a variable. A variable is a holding tank for a value of some type. A variable contains a value, such as a number or a character. For example int age; is a declaration statement. C++ is a case-sensitive: This means the word name is different from the word Name related to capitalization. or any other variations

To be a good problem solver and a good programmer, you must follow good problem solving techniques. One common problem-solving technique includes analyzing a problem, outlining the problem requirements, and designing steps, called an algorithm, to solve the problem. Algorithm: A step-by-step problem-solving process in which a solution is arrived at in a finite amount of time. In a programming environment, the problem-solving process requires the following three steps: 1. Analyze the problem, outline the problem and its solution requirements, and design an algorithm to solve the problem. 2. Implement the algorithm in a programming language, such as C++, and verify that the algorithm works. 3. Maintain the program by using and modifying it if the problem domain changes.

Probably the best way to start learning a programming language is by writing a program. Therefore, here is our first program: // my first program in C++ #include <iostream> using namespace std; int main () { cout << "Hello World!"; return 0; } We are going to look line by line at the code we have just written: // my first program in C++ This is a comment line. All lines beginning with two slash signs (//) are considered comments and do not have any effect on the behavior of the program. You can put any character you want in a comment.

It may seem odd to have a command in C++ (or any other programming language) that s specifically ignored by the computer. However, all computer languages have some version of the comment. It s critical that the programmer explain what was going through her mind when she wrote the code. A programmer s thoughts may not be obvious to the next colleague who picks up her program and tries to use it or modify it. In fact, the programmer herself may forget what her program meant if she looks at it months after writing the original code and has left no clue. Single-line comments begin with a double slash // and continue to the end of the line. They are useful for short comments. Multiple-line comments may span one or more lines. The comment begins with the pair of characters /* and ends with */. #include <iostream> Lines beginning with a hash sign (#) are directives for the preprocessor. They are not regular code lines with expressions but indications for the compiler's preprocessor. The job of the preprocessor is to read through your source code looking for lines that begin with #, and when it finds one, to modify the code as requested by that command. These manipulations usually include other text files to be compiled and perform various text replacements. This all happens before the compiler sees your code.

The #include tells the compiler to include the header file iostream.h the compiler is smart enough to know about the .h, so you don t have to put it in. This header file describes what components the library provides so that the compiler can recognize names such as cout. This header file is part of the C++ system, and so is called a system header file. Including the header file for iostream gives you the ability to use the iostream library. You can open the iostream.h file if you can find it on your system (usually in the include subdirectory of the directory where your compiler is installed). You will probably find its source code hard to understand. Fortunately, the compiler doesn t. The iostream file must be included for any program that outputs data to the screen or inputs data from the keyboard using C++ style stream input/output. It also includes the declaration of the stream inserter (<<). include is an instruction that says, What follows is a filename. Find that file and read it in right here. The angle brackets around the filename tell the preprocessor, Look in all the usual places for this file. If your compiler is set up correctly, the angle brackets will cause the preprocessor to look for the file iostream.h in the directory that holds all the header files for your compiler. The effect of this line is to include the file iostream.h into this program as if you had typed that file into the code yourself.

The cout object: This is an object to which we send information that we want written on the computer screen. The word cout is an abbreviation of console output. The << operation: This is an operation that acts on the objects immediately to its left and right: in this case, the cout object on its left and the character array (described next) on its right. The character array enclosed in quotation marks: These are the words Hello World!. The quotation marks mark the beginning and end of the character array. Note that the single quote (apostrophe) is a valid character. The statement terminator: The semicolon at the end of the line denotes the end of the statement. As mentioned, the << operation takes two arguments: the cout object on its left and the character array on its right. The effect of this operation is that the character array is typed onto the computer s screen. The semicolon at the end of the line is mandatory; it marks the end of the statement.

The object cout is not core part of C++, but standard addition to the language. It is possible that a software developer let s call her Sophie might want a different version of cout that is somehow different from the standard version. Sophie also wants to call her console output object cout; this is possible in C++. Sophie creates (don t worry about how, you are not a software developer) a separate namespace, which she calls, say, sophie. Each namespace itself has a name that is added to any names in the code it holds. Therefore, the full name of Sophie s cout is sophie::cout. Similarly, the full name of the standard cout is std::cout, where std stands for the standard namespace. We can say that namespaces are a sort of container for names (or objects). In the iostream file, cout is defined to have the full name std::cout. It is possible to delete line using namespace std; from the program, but then it would be necessary to replace cout with std::cout. However, for our purposes, it is much easier to declare: we are going to be using the standard namespace, so we will use the short forms of the names. That s what the statement using namespace std; does.

The statement using namespace std tells the compiler, If you see a name and you don t know what namespace it is from, assume it is from the std namespace. If you leave this command out, you will get the following message from the compiler: error : cout was not declared in this scope This is because the compiler does not know where to look for cout. Since we never mention the namespace in which they can be found. We could cure this without the using namespace statement by changing line to std::cout << "Hello World!";

The basic building block in a C++ program is the function. The term function refers to a task or job. Every C++ program is a collection of one or more functions, written in some arbitrary order. One and only one of these functions in the program must have the name main(). C++ program always start its execution at the function named main. It doesn t matter if main is physically located at the beginning or end of your source code. Functions take various values as arguments, execute instructions, and return a value. In this case, the function named main returns an integer value; this is signified by the word int before the name of the function. The value returned is zero, and this is accomplished at the end of the function with the statement return 0; which returns the value 0.

The main function does not take any arguments; this is signified by the empty pair of parentheses following the word main. The main function defined as : main() { } int main() { // function header, no semicolon // start of function body return 0; // C++ statement, requires semicolon // end of function body

The function definition is the combination of the function header and the function body. A function header is the first line in a function definition. The function body contains the statements enclosed in curly braces.

The function main() does not have to be at the top of a program so a C++ program does not necessarily start at line 1. It always starts where main() is. Also, the function main()cannot be called from any other function in the program. Only the operating system can call the function main(): this is how a C++ program is started.

Escape Sequence:
 Non graphics characters (characters that can be typed directly from keyboard e.g. backspace, tabs, carriage return etc.) can be represented by using escape sequences.  An escape sequence is represented by a backslash (\) followed by one or more characters.  An escape sequence is represents a single character.

Escape Sequence:
\a \b \n \t \v \\ \ \ \0

Non graphic character


Audible bell (alert) Backspace Newline or linefeed Horizontal tab Vertical tab Backslash Single quote Double quote Null character

A null character is a special character, used among other things to give a character variable an initial value.

What will be the output of the following C++ code:


#include <iostream> using namespace std; main() { cout << Hello World! \n It\ s Holiday \n ; cout << \tHe said, \ Hurray!\ ; return 0; } Output:
Hello World! It s Holiday He said, Hurray!

The following comment in a C++ program would cause the compiler to issue an error message. /* * In C++ comments are enclosed between /* and */ */ What s wrong? For the following code, indicate if there are any errors. If there is an error, specify how you fix it: 1. \\ This is my first program 2. /* this is the example of multi line Comment/* 3. /* Isn t this /* a fun */ comment */ 4. int main(); 5. int main( ) ( return 0 ; )

int main() { return 0 } end of main() function Numbers are the building blocks of mathematics and, of course, computers are extremely adept with numbers. There are several ways in which numbers are handled in C++. Numbers in C++ are divided into two broad categories: integers and reals. Each of these categories is refined further. Of course, to a mathematician every integer is a real number, so these categories may seem spurious. The reasons for having many different ways to represent numbers are efficiency and accuracy; if the quantities with which we are computing are known to be integral, then using an integer representation is not subject to roundoff error and the computations are faster.

Literals:
Literals (often referred to as constants) are data items that never change their value during a program run. C++ allows several kinds of literals:
Literals

Integer

Floating

Character

String

Decimal

Octal

Hexadecimal

Variables:
A variable is a placeholder whose contents can change. A placeholder is given a name, which we use reference the value stored in the variable. Every variable name in C++ must start with a letter, the rest of the name can consist of letters, numbers and underscore characters. It can not contain any blanks, commas or special symbols, such as ()&#!?. C++ recognizes upper and lower case characters as being different. you cannot use any of C++ keywords like main, while, switch etc. as variable names.

Examples of Variable Names:


Valid Variable Names: Idnumber sumofnumbers I, j, k1 transaction_number phone_number CASENO Invalid Variable Names:

4myfriend sum of two no s.no T1_ amount@1 while write

Every variable in a C++ program must be given a type. The type of a variable is a specification of the kind of data the variable can store. The most basic type is int. An int represents an integer quantity. In this program, two variables, x and y, are declared to be of type int. C++ requires that we specify the type of every variable, and the declaration statement is the manner by which this is accomplished.. Variables may be declared anywhere in the program so long as they are declared before they are used. Subsequently the variables are assigned values. In this case x is assigned the value 3 and y the value 4. The equal sign = is an operation (called assignment) that stores the value of the expression to its right into the variable on its left.

It is possible to combine declarations on a single line; in place of lines 6 and 7, we could have this: int x,y; It is possible to combine declaration with assignment. Lines 9 10 can be replaced by these two: int x = 3; int y = 4; In line 12, the contents of x and y are added, and the result is written on the computer s screen. Variables of type int can store a finite range of integer values. The size of that range depends on your specific computer. On many computers an int is held in 4 bytes of memory (one byte is 8 bits, so this is 32 bits). With 32 bits one can store 232 different values.

There is an easy way to learn the size of an int on your computer in C++ with the sizeof operator. Evaluating sizeof(int) gives the number of bytes used to store variables of type int. There are a few variations of the fundamental int type. A short is an integer type that is either the same as int, or else a smaller size than int. That is, sizeof(short)cannot exceed sizeof(int). There are a few variations of the fundamental int type. A short is an integer type that is either the same as int, or else a smaller size than int. That is, sizeof(short) cannot exceed sizeof(int). A long is an integer type that is either the same size as int, or else a larger size than int. In other words, sizeof(long) is at least sizeof(int). Some compilers provide a long long type. This is an integer type that is at least the size of a long. That is, sizeof(long long)cannot be less than sizeof(long). In summary, sizeof(short) sizeof(int) sizeof(long) sizeof(long long).

Finally, each of the integer types can be modified for holding only nonnegative integers using the unsigned keyword. For example, a variable can be declared unsigned int x; In this case, x may take on only nonnegative values. The real number types C++ can handle more than integers. Real numbers are represented using floating point approximations. There are two principal types of floating point types: float and double. Both hold real values of limited precision. Variables of type float use less memory and have less precision than those of type double. Some computers may have a long double type that has even greater precision than double. Unless you have special needs (for increased speed or decreased memory), use the double type for all your real number calculations. For the float and double data types, there are three quantities of interest: the largest value, the smallest positive value, and the difference between 1 and the smallest value greater than 1. This latter value is known as the epsilon value of the data type.

C++ provides header files with this information. The header file climits gives the minimum and maximum value of various integer types. It defines symbols such as INT_MIN and INT_MAX that are equal to the smallest and largest value an int may hold. Similarly, the header file cfloat gives the minimum positive, maximum, and epsilon values for float, double, and long double (if available) data types.

The bool and char types There are other basic data types available in C++. Two that we encounter frequently in C++ are designed for handling Boolean and character data. The data type bool is used to represent the logical values TRUE and FALSE. In C++, these are represented as integers: 1 for TRUE and 0 for FALSE. Indeed, bool is considered to be an integer type. Boolean values emerge as the result of comparison operations. In C++, to see if two variables hold equal values we use the == operator. The result of x == y is either 1 (TRUE) in the case where x and y hold equal values and 0 (FALSE) otherwise. If your program contains the statement cout << (x==y) << endl; either a 0 or a 1 is typed on the screen.

Individual characters have the type char. One can create variables to hold single characters by declaring them to be of type char as shown below: char x; x = A; cout << x << endl; This code causes the letter A to appear on the computer s screen. Notice that a single character is enclosed in single quotes. Arrays of characters are enclosed in double quotes. It is incorrect to write char x = "A"; because x is of type char whereas "A" is an array of elements of type char. C++ has two principal ways of handling textual data: arrays of characters and objects of type string.

Exercises:
What is wrong with each of the following declaration statement: 1. int a, int b; 2. int a = 0, b = 4.5; 3. char grade = A; 4. char title = this is first test program; 5. int base_salary (30000) int id_num, staff_salary = base_salary; 6.float area, circumfrence;

C++ Constants:
ANSI C++ allows you to declare constants.  A constant is similar to a variable in the sense that it represents a memory location.  It differs, in that it cannot be reassigned a new value after initialization. The const keyword is to declare a constant, as shown below:
int const a = 1; or const int a =2; const double PI = 3.1416;

Note:
You can declare the const before or after the type. It is usual to initialize a constant with a value as it cannot get a value any other way.

There are three techniques used to define constants in C++:


 Using #define  Using const variables  Using Enumerated Data Types

Example:
// defined constants: calculate circumference #include <iostream> using namespace std; #define PI 3.14159 int main () { double r = 5.0; // radius double circle; circle = 2 * PI * r; cout << Circumference of circle with radius 5.0 is << circle ; return 0; }

Standard operations C++ provides the familiar arithmetic operations. The expressions x+y, x-y, x*y, and x/y are the usual sum, difference, product, and quotient of x and y. In these expressions, x and y may be any of the numeric types we discussed. However, mixing types can sometimes cause problems and confusion. If x and y are of the same type, then the result of the operation is also that type. For example, consider the following code: int numerator = 13; int denominator = 5; double quotient; quotient = numerator/denominator; cout << quotient << endl;

We might expect this code to print the value 2.6 on the computer s screen. The surprise is that the computer prints 2. To understand why, we have to remember that when two int values are divided, the result is an int. In this case, C++ divides the integers 13 and 5 to give the result 2 (the fractional part is lost) and then assigns that value to quotient. Because quotient is of type double there is a silent, behind-the-scenes conversion of the int quantity into a double quantity. We can coerce C++ to give us the answer 2.6 by converting 13 or 5 (or both) into double variables. We replace quotient = numerator/denominator with this: quotient = double(numerator) / double(denominator); The expression double(numerator) converts the integer value in numerator into a double quantity. This conversion process is known as casting. Note that the variables numerator and denominator are unaffected by this; they remain type int and their type cannot be changed. What double(numerator) does is create a temporary double number to be used in the division.

We do not have to cast both numerator and denominator to type double. Once we cast one of them to double, we have an expression involving a double and an int. In this case, C++ automatically converts the other value as well. We can also write algebraic expressions. These expressions may contain explicit numbers in addition to variables, such as x = 2*x+3;. This expression means that we take the value of x, multiply that by 2, then add 3, and then save the result of the calculation back into x. So if the initial value of x is 10, after this statement x would hold the value 23. Numbers written without a decimal point are assumed to be integers, and numbers with decimal points are assumed to be floating point values. Consider the following code: cout cout cout cout << << << << 13/5 << endl; 13./5 << endl; 13./5. << endl; 13/5. << endl;

The first of these prints 2 and the other three print 2.6.

For integer variables, the percent sign denotes the mod operation. The expression 237 % 100 evaluates to 37. Unfortunately, the % operation is not exactly the same as the mathematician s mod. For us, when a and b are integers with b > 0, we have that a mod b is the remainder r in the division of a by b where r must satisfy 0 r < b. Even if a is negative, the result of a mod b is nonnegative. However, in C++, if a is negative and b is positive, a%b is negative. Furthermore, C++ allows b to be negative, or even zero! 34 % 5 = 4 4 % 6 = 4 In the division 4 / 6, the quotient is 0 and the remainder is 4. Therefore, 4 % 6 evaluates to the remainder, which is 4. For example, -34 % 5 = -4, because in the division 34 / 5, the quotient is -6 and the remainder is -4. Similarly, 34 % -5 = 4, because in the division 34 / 5, the quotient is 6 and the remainder is 4. Also, -34 % -5 = -4, because in the division 34 / 5, the quotient is 6 and the remainder is 4.

You might also like