Unit 2 Basics of C
Unit 2 Basics of C
Introduction of C++
Application of C++
C++ is a versatile language for handling very large programs; it is suitable for virtually any
programming task including development of editors, compilers, databases, communication
systems and any complex real life applications systems.
• Since C++ allow us to create hierarchy related objects, we can build special object-
oriented libraries which can be used later by many programmers.
• While C++ is able to map the real-world problem properly, the C part of C++ gives the
language the ability to get closed to the machine-level details.
• C++ programs are easily maintainable and expandable. When a new feature needs to be
implemented, it is very easy to add to the existing structure of an object.
• It is expected that C++ will replace C as a general-purpose language in the near future.
Structure of C++ Program
The C++ program is written using a specific template structure. The structure of the program
written in C++ language is as follows :
Documentation Section:
• This section comes first and is used to document the logic of the program that the
programmer going to code.
• It can be also used to write for purpose of the program.
• Whatever written in the documentation section is the comment and is not compiled by the
compiler.
• Documentation Section is optional since the program can execute without them. Below is
the example:
factorial of a number*/
Linking Section:
The linking section contains two parts:
Header Files:
• Generally, a program includes various programming elements like built-in functions,
classes, keywords, constants, operators, etc. that are already defined in the standard C++
library.
• In order to use such pre-defined elements in a program, an appropriate header must be
included in the program.
• Standard headers are specified in a program through the preprocessor directive #include. In
Figure, the iostream header is used. When the compiler processes the
instruction #include<iostream.h>, it includes the contents of the stream in the program.
This enables the programmer to use standard input, output, and error facilities that are
provided only through the standard streams defined in <iostream>. These standard streams
process data as a stream of characters, that is, data is read and displayed in a continuous
flow. The standard streams defined in <iostream> are listed here.
#include<iostream.h>
Namespaces:
• A namespace permits grouping of various entities like classes, objects, functions, and
various C++ tokens, etc. under a single name.
• Any user can create separate namespaces of its own and can use them in any other
program.
• In the below snippets, namespace std contains declarations for cout, cin, endl, etc.
statements.
using namespace std;
Main Function
• The main function tells the compiler where to start the execution of the program. The
execution of the program starts with the main function.
• All the statements that are to be executed are written in the main function.
• The compiler executes all the instructions which are written in the curly braces {} which
encloses the body of the main function.
• Once all instructions from the main function are executed control comes out of the main
function and the program terminates and no further execution occurs.
C++ program Construction
Before looking at how to write C++ programs consider the following simple example program.
// Sample program
// Reads values for the length and width of a rectangle
// and returns the perimeter and area of the rectangle.
Keywords:
The keywords implement specifies C++ language features. They are explicitly reserved
identifiers and cannot be used as names for the program variables or other user-defined program
elements. Many of the keywords are common to both C and C++.
char int float for while switch else new delete etc.
Identifiers refer to the names of variables, functions, arrays, classes, etc. created by the
programmer. Identifiers are the fundamental requirement of any language. Each language has its
own rules for naming these identifiers. The following rules are common to both C and C++:
Constants refer to fixed values that do not change during program execution. They include
integers, characters, floating point numbers and strings.. Examples are:
123 // decimal
Built-in-type is also known as basic or fundamental data type. The basic data type
may have several modifiers preceding them to serve the needs of various situations
except void. The modifier signed, unsigned, long and short may be applied to
character and integer basic data types. Long modifier may also be applied to double
data type representation in memory in terms of size (Bytes)
Type Bytes
char 1
unsigned char 1
signed char 1
int 2
unsigned int 2
signed int 2
short int 2
float 4
double 8
Arrays:
The application of arrays in C++ is similar to that in C. The only except is the way
character arrays are initialized. When initializing a character array in C, the compiler
will allow us to declare the array size as the exact length of the string constant. For
instance,
char string[3] = “xyz” is valid in C.
It assumes the programmer intends to leave out the null character ‘\0’ in the definition.
But in C++, the size should be one larger than the number of
characters in the string.char string[4] = “xyz” // o.k. for C++
data_type array_name[size]
e.g. int marks[30] ;
pointer
User-defined Data types:
Structure and Union are same as in C. Class is a user defined data type takes the
keyword class and declaration is as:
class class_name
{
};
Suppose in a C program there are two variables with the same name a. Assume that one has
become declared outside all functions (global) and another is declared locally inside a function.
Now, if we attempt to access the variable a in the function we always access the local variable.
This is because the rule says that whenever there is a conflict between a local and a global
variable, local variable gets the priority. C++ allows you the flexibility of accessing both the
variables. It achieves through a scope resolution operator (: :).
Type conversion
Type conversion (often called type casting) refers to changing an entity of one data type into
another. This is done to take advantage of certain features of type hierarchies. For instance
values from a more limited set, such as integers, can be stored in a more compact format and
later converted to different format enabling operations not previously possible, such as division
with several decimal places, worth of accuracy. In the object-oriented programming paradigm,
type conversion allows programs also to treat objects of one type as one of another.
Whenever the compiler expects data of a particular type, but the data is given as a different type,
it will try to automatically covert. For e.g.
In the example above, in the first case an expression of type float is given and automatically
interpreted as an integer. In the second case, an integer is given and automatically interpreted as
a float. There are two types of standard conversion between numeric type promotion and
demotion. Demotion is not normally used in C++ community.
Promotion
There is generally no problem with automatic promotion. Programmers should just be aware that
it happens.
New & Delete Operators:
C uses malloc( ) and calloc( ) functions to allocate memory dynamically at run time. Similarly, it
uses the function free( ) to free dynamically allocated memory. Although C++ supports these
functions, it also defines two unary operators new and delete that perform the task of allocating
and freeing the memory in a better and easier way. Since these operators manipulate memory on
the free store, they are also known as free store operators.
An object can be created by using new and destroyed by using delete as and when required.
The new operator can be used to create objects of any type. Its syntax is:
pointer_variable=new data-type ;
Here, pointer-variable is a pointer of type data-type. The new operator allocates sufficient
memory to hold a data object of type data-type and return the address of the object. The data-
type may be any valid data type. The pointer variables holds the address of the memory space
allocated. For e.g.
p = new int ;
q = new float ;
where p is a pointer of type int and q is a pointer of type float. Here, p and q must have already
declared as pointers of appropriate types. Alternatively, we can combine the declaration of
pointers and their assignments as follows:
*p=25 ;
*q=7.5 ;
assign 25 to the newly created int object and 7.5 to the float object.
We can also initialize the memory using new operator. This is done as pointer_variable=new
data-type(value)
For e.g.
New can be used to create a memory space for any data type including user-defined types such
as arrays, structures and classes. The general form for a one-dimension array is
pointer_variable=new data_type[size] ;
Here, size specifies the number of elements in the array. For example,
Delete:
When a data object is no longer needed, it is destroyed to release the memory space for reuse.
For this purpose, we use delete unary operator. The general syntax is
delete pointer_variable
The pointer_variable is the pointer that points to a data object created with new.
delete q ;
If we want to free a dynamically allocated array, we must use the following form of delete.
Manipulators are operators that are used to format the data display. The most commonly used
manipulators are endl and setw.
endl
The endl manipulator, when used in an output statement, causes a linefeed to be inserted. It has
the same effect as using the new line character “\n”.
setw
To use setw manipulator the “iomanip.h” header file must be included. The setw manipulator
causes the number or string that follows it in the stream to be printed within a field n characters
wide , where n is the argument used with setw as stew(n).
e.g.
#include<iostream.h>
#include<iomanip.h>
void main()
cout<<setw(12)<<”number1”<<setw(10)<< “num1<<endl;
cout<<setw(12)<<"number2<<setw(10)<<num2;
}
The output operator ( Output using “cout”)
The identifier cout (pronounced as ‘C out’) is a predefined object that represents the standard
output stream in C++.
The operator << is called insertion (or put to) operator. It inserts the contents of the variable on
its right to the object on its left. For e.g.
“<<” is the bit-wise left-shift operator. The above concept is called as operator
overloading.
The identifier cin (pronounced as ‘C in’) is a predefined object in C++ that corresponds to the
standard input stream. Here, this stream represents the keyword.
The “>>” operator is known as extraction (or get from) operator. It extracts (or takes) the value
form the keyboard and assigns it to the variable on its right. This corresponds to the familiar
scanf( ) operation. “>>” is bit-wise right shift operator.
The i/o operators can be used repeatedly in a single i/o statements as follows.
cout<<a<<b<<c;
cin>>x>>y>>z;
These are perfectly legal. The above cout statement first sends the value of ‘a’ to cout, then sends
the value of b and then sends the value of c.
Similarly, the cin statement first reads a value and stores in x, then reads again and stores in y
and then in z. The multiple uses of i/o operators in one statement is called cascading.
Function
A function is a group of statements that is executed when it is called from some point of the
program. The following is its format:
statements
where,
• parameters (as many as needed): Each parameter consists of a data type specifier
followed by an identifier, like any regular variable declaration (for example: int x) and which
acts within the function as a regular local variable. They allow to pass arguments to the function
when it is called. The different parameters are separated by commas.
e.g.
// function example
# include <iostream.h>
int addition (int a, int b)
{
int r ;
r=a+b ;
return(r) ;
}
void main( )
{
int z ;
z = addition (5,3) ;
cout << “The result is” <<z ;
}
Output:
The result is 8.
Function in C++:
Dividing a program into function is one of the major principles of top-down structured
programming. Another advantage of using functions is that it is possible to reduce the size of a
program by calling and using them at different places in the program.
Syntax of function:
void show( ) ; / * Function declaration * /
main ( )
{
------
------
show( ) ; / * Function call * /
}
void show( ) / * Function definition * /
{
------
- - - - - - / * Function body * /
------
}
When the function is called, control is transferred to the first statement in the function body. The
other statements in the function body are then executed and controls return to the main program
when the closing brace is encountered. C++ has added many new features to functions to make
them more reliable and flexible.
Function Prototyping:
Function prototyping is one of the major improvements added to C++ functions. The prototype
describes the function interface to the compiler by giving details such as the number and type of
arguments and the type of return values. Any violation in matching the arguments or the return
types will be caught by the compiler at the time of compilation itself. These checks and controls
did not exist in the conventional C functions.
Function prototype is a declaration statement in the calling program and is of the following form:
The argument_list contains the types and names of arguments that must be passed to
the function E.g.
float volume(int x, int y, float z) ;
An argument is a data passed from a program to the function. In function, we can pass a variable
by following ways:
1. Passing by value
Passing by value:
In this the value of actual parameter is passed to formal parameter when we call the function. But
actual parameter are not changed.
#include <iostream.h>
#include<conio.h>
void swap(int, int) ; // declaration prototype
void main ( )
{
int x,y ;
x=10 ;
y=20 ;
swap(x,y) ;
cout<<"after swap"<<endl;
cout << “x =” <<x<<endl ;
cout<< “y =” <<y<<endl ;
getch( ) ;
}
void swap(int a, int b) // function definition
{
int t ;
t=a ;
a=b ;
b=t ;
cout<<"a="<<a<<endl;
cout<<"b="<<b<<endl;
}
#include <iostream.h>
#include <conio.h>
void swap(int *, int *) ;
void main( )
{
int x, y ;
x=10 ;
y=20 ;
swap(&x, &y) ;
cout<< “x=”<<x<<endl ;
cout<< “y=”<<y<<endl ;
getch( ) ;
}
void swap(int *a, int *b)
{
int t ;
t=*a ;
*a=*b ;
*b=t ;
}
Function Overloading
Two or more functions can share the same name as long as either the type of their arguments
differs or the number of their arguments differs – or both. When two more functions share the
same name, they are said overloaded. Overloaded functions can help reduce the complexity of a
program by allowing related operations to be referred to by the same name.
To overload a function, simply declare and define all required versions. The compiler will
automatically select the correct version based upon the number and / or type of arguments used
to call the function.
Inline Functions:
In C++, it is possible to define functions that are not actually called but, rather are expanded in
line, at the point of each call. This is much the same way that a c like parameterized macro
works.
The advantage of in-line functions is that they can be executed much faster than normal
functions. The disadvantage of in-line functions is that if they are too large and called too often,
your program grows larger. In general, for this reason, only short functions are declared as in-
line functions.
To declare an in-line function, simply precede the function’s definition with the inline specifier.