Unit 1

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 12

UNIT 1

INTRODUCTION TO C++
1 INTRODUCTION
A program is a sequence of instructions that can be executed by a computer. Every program is
written in some programming language. C++ (pronounced “see-plus-plus”) is one of the most
powerful programming languages available. It gives the programmer the power to write
efficient, structured, object-oriented programs. A program is a collection of statements written in a
programming language. In the same way that grammar rules dictate how to construct English
sentences, there are C++ grammar rules that govern how C++ statements are formed and combined
into more complex statements and into programs.

In early 1980’s, a new programming language was developed by Bjarne Stroustrup at Bell
Laboratories, USA. This language, an extended version of C language, is known as C++. Apart
from the features of the C language, C++ also has some additional features such as classes, objects,
and so on. When C++ language was developed, it was known as ‘C with classes’. In 1983, the
name was changed to C++. The ++ sign specifies that it is an incremented version of the C
language. This means that the code written in C can also be executed in the C++ environment.
Basically, C++ was developed to eliminate some of the limitations of the C language and also to
provide some new features to the user.
In this unit, you will know about procedure-oriented programming, key concepts of object-oriented
programming, and also some C++ fundamentals.

1.1 BASICS OF GENERAL PROGRAMMING


Programmers write instructions in various programming languages, some directly understandable
by computers and others requiring intermediate translation steps.

1.1.1 Machine Languages


Any computer can directly understand only its own machine language (also called machine code),
defined by its hardware architecture. Machine languages generally consist of numbers
(ultimately reduced to 1s and 0s). Such languages are cumbersome for humans.

1.1.2 Assembly Languages


Programming in machine language was simply too slow and tedious for most programmers.
Instead, they began using English-like abbreviations to represent elementary operations. These
abbreviations formed the basis of assembly languages. Translator programs called assemblers were
developed to convert assembly-language programs to machine language. Although assembly
language code is clearer to humans, it’s incomprehensible to
computers until translated to machine language.
1.1.3 High-Level Languages
To speed up the programming process further, high-level languages were developed in which
single statements could be written to accomplish substantial tasks. High-level languages, such as
C, C++, Java, Python, Matlab and Visual Basic, allow you to write instructions that look more like
every day English and contain commonly used mathematical notations. Translator programs called
compilers convert high-level language programs into machine language.
The process of compiling a large high-level language program into machine language can take a
considerable amount of computer time. Interpreter programs were developed to execute high-level
language programs directly (without the need for compilation), although more slowly than
compiled programs. Scripting languages such as the popular web languages JavaScript and PHP
are processed by interpreters.

1.2 PROCEDURE-ORIENTED PROGRAMMING (POP)


Procedure-oriented programming (POP) is a programming technique in which a problem is divided
into subparts. These subparts are solved by using different functions. In this type of programming
technique, all the programs are developed around functions. These functions work on global data
(data that can be accessed by all the members of a program) and can also manipulate it. In this type
of programming technique, the primary focus is on the functions. For
example, you may want to solve a problem that performs three different operations such as reading
data from the user, processing the data, and printing the output. Three different functions are
created to handle these operations, see Figure 1. This figure illustrates that all the three operations
are performed by three different functions.

Figure 1 Representation of POP


In procedure-oriented programming, the data that can be accessed by all the functions is declared
as global. Each function can also have its own local data. A major drawback of procedure-oriented
programming is that the data is not treated as a critical element and can be manipulated by any of
the functions. Another drawback is that you cannot solve the real-world problems by using the
procedure-oriented technique. As the size of the program increases, it becomes more complex and
difficult to understand. Each object maintains its own copy of data and functions. The data cannot
be accessed directly by the other objects of the program. It can only be accessed through a proper
interface such as functions, as shown in Figure 2.
2.3 OBJECT-ORIENTED PROGRAMMING (OOP)
Object-oriented programming (OOP) developed to overcome the limitations of the procedure-
oriented programming is an improved technique for developing the programs. In case of OOP,
the data is treated as the most critical element and the primary focus is on the data and not on the
procedures. In this technique, the data is grouped together with the functions that operate on it. A
problem is divided into entities known as objects.

Figure 2 Representation of OOP

2.3 FEATURES OF OBJECT-ORIENTED PROGRAMMING


There are certain features that have made object-oriented programming very popular. These
features are as follows:
1. Objects
2. Classes
3. Encapsulation
4. Inheritance
5. Polymorphism

1.4.1 OBJECTS
In object-oriented programming, a problem is divided into certain basic entities called objects. The
objects can be used to represent real life objects such as people, bank account, and so on. In this
type of programming, all communication is carried out between the objects. When a program is
executed, the objects interact with each other by sending messages. The objects contain the data
and the functions that can be used to manipulate the data. Each object maintains its own copy of
the data and methods, which can communicate with each other through a proper channel or
interface.
3 CLASSES
A class is a user-defined data type which is used to group the data and the functions together. These
objects are the instances of a class. A class can also contain important members such as a
constructor to create objects. The objects that belong to same class must have certain properties in
common. For example, a table and a chair are the objects of the furniture class. Both the objects
have certain properties in common. For example, both are made of wood and so on.

1.4.3 ENCAPSULATION
Encapsulation is a mechanism used for wrapping up the data along with the functions that can
operate on the data directly. This mechanism is used to keep the data safe from outside
interferences. It hides the internal data and only provides the external interface (functions) through
which it can be accessed. Encapsulation also provides the concept of data hiding or information
hiding so that it cannot be accessed directly.

1.4.4 INHERITANCE
Different kinds of objects often have certain amount of properties in common with each other.
Inheritance is the process by which one object can acquire the properties of another object. This is
called the reusability of code. In inheritance, whenever a new object is created, it can only define
those properties that make it unique from the other objects. Inheritance supports the concept of the
hierarchical classifications. For example, the fruit ‘Apple’ is a part of the class
‘Fruits’, which is again a part of the class ‘Food’, as shown in Figure 3.

Figure 3 Hierarchical classification


In the above figure, the two classes Fruits and Vegetables, apart from inheriting certain properties
from the class Food, add some properties of their own. The classes Apple and Mango inherit the
properties of the Fruits class while the classes Cabbage and Carrot inherit the properties of the
Vegetables class.

1.4.5 POLYMORPHISM
Polymorphism is another feature of object-oriented programming. Polymorphism is a Greek term
that consists of two words, poly and morph. Poly means many and morph means forms. So,
polymorphism means ‘one name many forms’. In polymorphism, an operation shows different
behaviors depending on the type of data used in it. In polymorphism, the internal structure
(functioning) of the operation is different but the external interface (name) is the same. When an
operator shows different behaviors in different contexts, it is known as operator overloading. When
a single function name is used to perform different operations, it is known as function
overloading, as shown in Figure 4.

Figure 4 Polymorphism

2.3 CONCEPT OF C++


In the C++ programming, you can write a sequence of commands called source file. A C++ source
file normally carries the .CPP extension. This source file can be converted into a machine-language
program. This conversion is called compiling and is done by the compiler. The machine code is
combined with some setup and instructions and some standard library routines in a process known
as linking. Together, compiling and linking are known as building. The resulting machine-
executable files carry the extension .EXE in Windows.

❖ Downloading Code: Blocks


Navigate to http://www.codeblocks.org in your browser; the Code::Blocks page is displayed, as
shown in Figure 5. Next, choose the Downloads tab from this page; the page with the
Downloads area is displayed, as shown in Figure 6.

Figure 5 The Code::Blocks page


int main()
{
cout << "What is your first name? ";
string firstName;
cin >> firstName;
cout << "\nWelcome to CS 104, " << firstName <<"!\n";
}

The first line of the program begins with the pair of characters /* and the seventh line
ends with the pair */. In a C++ program, anything contained between these character
pairs is a comment. This multiline comment in these opening lines of the program is
opening documentation that gives information about the program such as what it does,
who wrote it, when it was written (or last updated), and what is input to and output by
the program. The dashes in the sixth line are optional and are used in the examples of The two lines
that follow begin with #include and are called compiler directives. The first one instructs the
compiler to add to the program the items in the library iostream that are needed to perform input
and output; it will appear in all of our C++ programs. The second directive adds the items in the
library string that are needed to process character strings. The // following each directive indicates
that what follows to the end of the line is a comment. Here these comments indicate which items
from the libraries are being used. The next line using namespace std; will be present in nearly all
of our programs. It informs the compiler that we want these to be the standard libraries from the
namespace named std.1 Without it, we would have to qualify each library item (such as cout) with
the prefix std::; for example: this text as a border to set this opening documentation off from the
program statements that follow.
std::cout << "What is your first name? ";
However, this soon becomes annoying because the standard library identifiers such as cin
and cout are used so frequently. The rest of the program has the form
int main()
{
A list of C++ statements
}
This is actually a function named main and is called the main function of the program. The C++
keyword int preceding the word main specifies the return type of the function and indicates that it
will return an integer value to the operating system. Normal termination is indicated by returning
zero; nonzero return values indicate abnormal termination. Some programmers use (and some
older compilers may require) a return statement return 0; as the last statement in the program.
Execution of this program will begin with the first statement enclosed between the curly
braces ({ and }) in this main function and proceed through the statements that follow it.
Note that each statement must end with a semicolon.
1.7 THE OUTPUT OPERATOR
The symbol << is called the output operator in C++. (It is also called the put operator or the
stream insertion operator.) It inserts values into the output stream that is named on its left. We
usually use the cout output stream, which ordinarily refers to the computer screen. So the statement
cout << 66;
would display the number 66 on the screen.
An operator is something that performs an action on one or more objects. The output operator
<< performs the action of sending the value of the expression listed on its right to the output
stream listed on its left. Since the direction of this action appears to be from right to left, the
symbol << was chosen to represent it. It should remind you of an arrow pointing to the left.
The cout object is called a “stream” because output sent to it flows like a stream. If several
things are inserted into the cout stream, they fall in line, one after the other as they are dropped
into the stream, like leaves falling from a tree into a natural stream of water. The values that are
inserted into the cout stream are displayed on the screen in that order.
// “Hello, World” Program
# include<iostream>
Using namespace std;
int main()
// prints "Hello,World!":
{
cout << "Hel" << "lo, Wo" << "rld!" << endl;
return 0
}
The output operator is used four times here, dropping the four objects "Hel", "lo,Wo", "rld!", and
endl into the output stream. The first three are strings that are concatenated together (i.e., strung
end-to-end) to form the single string "Hello,World!". The fourth object is the stream manipulator
object endl (meaning “end of line”). It does the same as appending the endline character '\n' to the
string itself: it sends the print cursor to the beginning of the next line. It also “flushes” the output buffer.

2.3 THE INPUT OPERATOR


In C++, input is almost as simple as output. The input operator >> (also called the get operator or
the extraction operator) works like the output operator <<.
// Using the Input Operator
# include <iostream>
using namespace std;
int main()
{
cout << "What is your first name? ";
string firstName;
cin >> firstName;
cout << "\nWelcome to CS 104, " << firstName <<"!\n";
}

The first line of the program begins with the pair of characters /* and the seventh line
ends with the pair */. In a C++ program, anything contained between these character
pairs is a comment. This multiline comment in these opening lines of the program is
opening documentation that gives information about the program such as what it does,
who wrote it, when it was written (or last updated), and what is input to and output by
the program. The dashes in the sixth line are optional and are used in the examples of The two lines
that follow begin with #include and are called compiler directives. The first one instructs the
compiler to add to the program the items in the library iostream that are needed to perform input
and output; it will appear in all of our C++ programs. The second directive adds the items in the
library string that are needed to process character strings. The // following each directive indicates
that what follows to the end of the line is a comment. Here these comments indicate which items
from the libraries are being used. The next line using namespace std; will be present in nearly all
of our programs. It informs the compiler that we want these to be the standard libraries from the
namespace named std.1 Without it, we would have to qualify each library item (such as cout) with
the prefix std::; for example: this text as a border to set this opening documentation off from the
program statements that follow.
std::cout << "What is your first name? ";
However, this soon becomes annoying because the standard library identifiers such as cin
and cout are used so frequently. The rest of the program has the form
int main()
{
A list of C++ statements
}
This is actually a function named main and is called the main function of the program. The C++
keyword int preceding the word main specifies the return type of the function and indicates that it
will return an integer value to the operating system. Normal termination is indicated by returning
zero; nonzero return values indicate abnormal termination. Some programmers use (and some
older compilers may require) a return statement return 0; as the last statement in the program.
Execution of this program will begin with the first statement enclosed between the curly
braces ({ and }) in this main function and proceed through the statements that follow it.
Note that each statement must end with a semicolon.
1.7 THE OUTPUT OPERATOR
The symbol << is called the output operator in C++. (It is also called the put operator or the
stream insertion operator.) It inserts values into the output stream that is named on its left. We
usually use the cout output stream, which ordinarily refers to the computer screen. So the statement
cout << 66;
would display the number 66 on the screen.
An operator is something that performs an action on one or more objects. The output operator
<< performs the action of sending the value of the expression listed on its right to the output
stream listed on its left. Since the direction of this action appears to be from right to left, the
symbol << was chosen to represent it. It should remind you of an arrow pointing to the left.
The cout object is called a “stream” because output sent to it flows like a stream. If several
things are inserted into the cout stream, they fall in line, one after the other as they are dropped
into the stream, like leaves falling from a tree into a natural stream of water. The values that are
inserted into the cout stream are displayed on the screen in that order.
// “Hello, World” Program
# include<iostream>
Using namespace std;
int main()
// prints "Hello,World!":
{
cout << "Hel" << "lo, Wo" << "rld!" << endl;
return 0
}
The output operator is used four times here, dropping the four objects "Hel", "lo,Wo", "rld!", and
endl into the output stream. The first three are strings that are concatenated together (i.e., strung
end-to-end) to form the single string "Hello,World!". The fourth object is the stream manipulator
object endl (meaning “end of line”). It does the same as appending the endline character '\n' to the
string itself: it sends the print cursor to the beginning of the next line. It also “flushes” the output buffer.

2.3 THE INPUT OPERATOR


In C++, input is almost as simple as output. The input operator >> (also called the get operator or
the extraction operator) works like the output operator <<.
// Using the Input Operator
# include <iostream>
using namespace std;
int main()
// tests the input of integers,floats,and characters:
{
int m,n;
cout << "Enter two integers: ";
cin >> m >> n;
cout << "m = " << m << ", n = " << n << endl;
double x,y,z;
cout << "Enter three decimal numbers: ";
cin >> x >> y >> z;
cout << "x = " << x << ", y = " << y << ", z = " << z << endl;
char c1,c2,c3,c4;
cout << "Enter four characters: ";
cin >> c1 >> c2 >> c3 >> c4;
cout << "c1 = " << c1 << ",c2 = " << c2 << ", c3 = " << c3
<< ", c4 = " << c4 << endl;
}
Enter two integers: 22 44
m = 22, n = 44
Enter three decimal numbers: 2.2 4.4 6.6
x = 2.2,y = 4.4,z = 6.6
Enter four characters: ABCD
c1 = A, c2 = B, c3 = C, c4 = D
SELF ASSESSMENT
1. Describe the two ways to include comments in a C++ program.
2. In a C++ program, anything contained between /* and */ is a .--------------------
3. Execution of a C++ program begins with the first statement enclosed between------------------
in the ---------------------------function.
4. Objects whose values will change are called .
5. The screen has the predefined name--------------------------------- in C++.
6. The keyboard has the predefined name----------------------------- in C++.
7. --------------------------------- is the output operator in C++ and ------------------------------is the
input operator.
8. Finding the errors in a program is called-----------------------------------
9.

10. What is wrong with this program?


#include <iostream>
int main ()
// prints "Hello,World!":
{
cout << "Hello,World!"
11. What’s wrong with this program:
#include <iostream>;
int main
{ // prints "n = 22":
n = 22;
cout << "n = << n << endl;
}
12. Calculate and display the perimeter and the area of a square with a given side. (The
perimeter of a square where the length of each side is s is 4s and the area is s2.)
13. Calculate and display the diameter, circumference, and the area of a circle with a given
radius. (The diameter is twice the radius. For radius r, the circumference is 2πr and the
area is πr2 where π is the mathematical constant pi whose value is approximately 3.14159.)
14. Three resistors are arranged in parallel in the following circuit:

For given values of R1, R2, and R3, calculate and display the combined resistance.

15. What C++ command(s) would be used within a program (inside the main
section of the code) to output the following multiline poem?
Learning C++,
Syntax, Concepts, and Design
What fun lies ahead!
16. There are 8 errors in the following program. Can you find them?
1 / Program to debug
2 include<iostream>
3 using std;
4
5 main()
6 cout "Hello, World! << endl
7}

You might also like