0% found this document useful (0 votes)
3 views22 pages

Unit 2 Basics of C

C++ is an object-oriented programming language developed by Bjarne Stroustrup in the early 1980s, combining features of C and Simula67. It supports various programming tasks, offers features like classes and inheritance, and is expected to replace C as a general-purpose language. The document outlines the structure of a C++ program, including sections such as documentation, linking, definition, global declaration, function declaration, and the main function, along with basic concepts like tokens, keywords, data types, and memory management.

Uploaded by

srijankhawasyt
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views22 pages

Unit 2 Basics of C

C++ is an object-oriented programming language developed by Bjarne Stroustrup in the early 1980s, combining features of C and Simula67. It supports various programming tasks, offers features like classes and inheritance, and is expected to replace C as a general-purpose language. The document outlines the structure of a C++ program, including sections such as documentation, linking, definition, global declaration, function declaration, and the main function, along with basic concepts like tokens, keywords, data types, and memory management.

Uploaded by

srijankhawasyt
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

Unit 2 Basics of C++ programming

Introduction of C++

C++ is an object-oriented programming language. It was developed by Bjarne Stroustrup at


AT&T Bell Laboratories in Murray Hill, New Jersey, USA, in the early 1980’s. Stroustrup, an
admirer of Simula67 and a strong supporter of C, wanted to combine the best of both the
languages and create a more powerful language that could support object-oriented programming
features and still retain the power and elegance of C. The result was C++. Therefore, C++ is an
extension of C with a major addition of the class construct feature of Simula67. Since the class
was a major addition to the original C language, Stroustrup initially called the new language ‘C
with classes’. However, later in 1983, the name was changed to C++. The idea of C++ comes
from the C increment operator ++, thereby suggesting that C++ is an augmented version of C.
C+ + is a superset of C. Almost all c programs are also C++ programs. However, there are a few
minor differences that will prevent a c program to run under C++ compiler. We shall see these
differences later as and when they are encountered. The most important facilities that C++ adds
on to C care classes, inheritance, function Overloading and operator overloading. These features
enable creating of abstract data types, inherit properties from existing data types and support
polymorphism, thereby making C++ a truly object-oriented language.

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:

/* This is a C++ program to find the

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;

• Namespaces can be accessed in multiple ways:


• using namespace std;
• using std :: cout;
Definition Section

• It is used to declare some constants and assign them some value.


• In this section, anyone can define your own data type using primitive data types.
• In #define is a compiler directive which tells the compiler whenever the message is found
replace it with “Factorial\n” .
• typedef int K; this statement telling the compiler that whenever you will encounter K
replace it by int and as you have declared k as data type you cannot use it as an identifier

Global Declaration Section


• Here the variables and the class definitions which are going to be used in the program are
declared to make them global.
• The scope of the variable declared in this section lasts until the entire program terminates.
• These variables are accessible within the user-defined functions also.

Function Declaration Section


• It contains all the functions which our main functions need.
• Usually, this section contains the User-defined functions.
• This part of the program can be written after the main function but for this, write the
function prototype in this section for the function which for you are going to write code
after the main function.

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.

#include <iostream.h> //for cout and cin


#include <conio.h> //for getch()
void main()
{
int length, width;
int perimeter, area; // declarations
cout << "Length = "; // prompt user
cin >> length; // enter length
cout << "Width = "; // prompt user
cin >> width; // input width
perimeter = 2*(length + width); // compute perimeter
area = length*width; // compute area
cout<< "Perimeter is " << perimeter<<endl; // output results
cout<< "Area is " << area;
getch();
} // end of main program

The following points should be noted in the above program:


1. Single line comment (// ………….)
Any text from the symbols // until the end of the line is ignored by the compiler. This facility
allows the programmer to insert Comments in the program. Any program that is not very simple
should also have further comments indicating the major steps carried out and explaining any
particularly complex piece of programming. This is essential if the program has to be extended
or
corrected at a later date. This is a kind of documentation. Also C comment type
/*--------------*/ is also a valid comment type in C++.
2. The line
#include <iostream.h>
must start in column one. It causes the compiler to include the text of the named file (in this case
iostream.h) in the program at this point. The file iostream.h is a system supplied file which has
definitions in it which are required if the program is going to use stream input or output. All
programs will include this file. This statement is a preprocessor directive -- that is it gives
information to the compiler but does not cause any executable code to be produced.
3. The actual program consists of the function main() which commences at the line void main(
).All programs must have a function main( ). Note that the opening brace ({) marks the
beginning of the body of the function, while the closing brace (}) indicates the end of the body of
the function. The word void indicates that main() does not return a value. Running the program
consists of obeying the statements in the body of the function main().
4. The body of the function main contains the actual code which is executed by the computer and
is enclosed, as noted above, in braces {}.
5. Every statement which instructs the computer to do something is terminated by a semi-colon.
Symbols such as main (), { } etc. are not instructions to do something and hence are not followed
by a semi-colon. Preprocessor directives are instruction to the compiler itself but program
statements are instruction to the computer.
6. Sequences of characters enclosed in double quotes are literal strings. Thus instructions such as
cout << "Length = " send the quoted characters to the output stream cout. The special identifier
endl when sent to an output stream will cause a newline to be taken on output.
7. All variables that are used in a program must be declared and given a type. In this case all the
variables are of type int, i.e. whole numbers. Thus the statement int length, width; declares to the
compiler that integer variables length and width are going to be used by the program. The
compiler reserves space in memory for these variables.

C++ Language Basic


C++ Language Basic consists of following things:
Token:
The smallest individual units in a program are called as tokens. C++ has the following tokens:
• Keywords
• Identifiers
• Constants
• Strings
• Operators
C++ tokens are basically almost similar to C tokens except few differences.

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++.

Examples of C++ keywords are:

char int float for while switch else new delete etc.

Identifiers and Constants:

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++:

• Only alphabetic characters, digits and underscores are permitted.

• The name cannot start with a digit.

• Uppercase and Lowercase letters are distinct.

• A declared keyword cannot be used as a variable name.

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

12.37 // floating point

“C++” // string constant


Data Types
Data types in C++ can be classified as:

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

void is a basic data type. It is used mainly for two purposes:


1. To specify the return type of function when it is not returning any value and
2. To indicate an empty argument list to a functio
Example: void function1(void) ;
Derived Data Types
Derived data types are those which depend on built –in data types. That’s why, they
are called so. For Eaxamples:
Arrays, Pointers, function.

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
{

};

Scope Resolution Operator (: :)


This operator allows access to the global version of variable. For e.g. it also
declare global variable at local place.
#include <iostream.h>
#include<conio.h>
int a=10 ; // global a
void main( )
{
clrscr( );
int a=15 ; // a redeclared, local to main
cout << “\n Local a=” <<a<< “Global a =” << : : a ;
: : a=20 ;
cout<< “\n Local a=”<<a<< “Global a<<: : a ;
getch();
}
Output:

Local a=15 Global a=10

Local a=15 Global a=20

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.

Automatic Type Conversion (or Standard Type Conversion):

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.

int a=5.6 ; float b=7 ;

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

Promotion occurs whenever a variable or expression of a smaller type is converted to a larger


type.

// Promoting float to double

float a=4 ; //4 is a int constant, gets promoted to float

long b=7 ; // 7 is an int constant, gets promoted to long

double c=a ; //a is a float, gets promoted to double

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:

int *p=new int ;

float *q=new float ;

subsequently, the statements

*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.

int *p=new int(25) ;

float *q=new float(7.5) ;

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,

int *p=new int[10] ; creates a memory space for an array of 10 integers.

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.

For e.g. delete p ;

delete q ;

If we want to free a dynamically allocated array, we must use the following form of delete.

delete [size] pointer_variable ;

The size specifies the number of elements in the array to be freed.


Manipulators:

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”.

cout<< “m=” <<m <<endl ;

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).

The value is right justified within the field.

e.g.

//demonstrates setw manipulator

#include<iostream.h>

#include<iomanip.h>

void main()

int num1=10, num2=20;

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.

cout << “Number” ;

“<<” is the bit-wise left-shift operator. The above concept is called as operator
overloading.

The input operator ( input using cin)

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.

Cascading I/O operators( multiple input/output)

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:

type name (parameter1, parameter2, )

statements

where,

• type is the data type specifier of data returned by the function.

• name is the identifier by which it will be possible to call the function.

• 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.

• statements is the function’s body. It is block of statements surrounded by braces { }.

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:

type function_name (argument-list) ;

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) ;

Passing Arguments to Function:

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

2. Passing by address or pointer

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;
}

Passing by Address or Pointer:


Passing argument by address uses a different approach. In this, the reference of original variable
is passed to function. But in call by value, the value of variable is passed.

#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.

// Program illustrate function overloading


// Function area( ) is overloaded three times
#include <iostream.h>
#include<conio.h>
// Declarations (prototypes)
int area(int) ;
double area(double, int) ;
long area(long, int, int) ;
void main( )
{
cout<<area(10)<< “\n” ;
cout<<area(2.5,8)<< “\n” ;
cout<<area(100,75,15)<< “\n”;
getch( );
}
// Function definitions
int area(int s) // square
{
return(s*s) ;
}
double area(double r, int h) // Surface area of cylinder ;
{
return(2*3.14*r*h) ;
}
long area(long l, int b, int h) //area of parallelopiped
{
return(2*(l*b+b*h+l*h)) ;
}
Output:
100
125.6
20250

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.

// Example of an in-line fucntion


#include <iostream.h.>
#include<conio.h>
inline int max(int x, int y)
{
return ((x>y)?x:y) ;
}
void main( )
{
int a, b;
cout<< “enter two values" ;
cin>>a>>b;
cout<<"greater value is"<<max(a,b);
getch( );
}

You might also like