02FundamentalOfCpp
02FundamentalOfCpp
LECTURE-5
Basics of C++
C++ Comments:
C++ introduces a new comment symbol //(double slash). Comments start with a
double slash symbol and terminate at the end of line. A comment may start any where in the line and
what ever follows till the end ofline is ignored. Note that there is no closing symbol.
The double slash comment is basically a single line comment. Multi line comments can be written
as follows:
// this is an example of
II c++ program
// thank you
The c comment symbols/* ........ */ are still valid and more suitable for multi line comments.
Output Operator:
The statement cout <<"Hello, world" displayed the string with in quotes on the screen. The identifier cout
can be used to display individual characters, strings and even numbers. It is a predefined object that
corresponds to the standard output stream. Stream just refers to a flow of data and the standard Output
stream normally flows to the screen display. The cout object, whose properties are defined in iostream.h
represents that stream. The insertion operator<< also called the 'put to' operator directs the
information on its right to the object on its left.
Return Statement:
In C++ main () returns an integer type value to the operating system. Therefore every main (
) in C++ should end with a return (0) statement, otherwise a warning or an error might occur.
Input Operator:
The statement
cin>> number 1;
is an input statement and causes. The program to wait for the user to type in a number. The number keyed
in is placed in the variable numberl. The identifier cin is a predefined object in C++ that corresponds to
the standard input stream. Here this stream represents the key board.
The operator>> is known as get from operator. It extracts value from the keyboard
and assigns it to the variable on its right.
cout<<"sum="<<sum<<"\n";
cout<<"sum="<<sum<<"\n"<<"average="<<average<<"\n";
cin>>number 1>>number2;
Structure Of A Program :
Probably the best way to start learning a programming language is by writing a program. Therefore,
here is our first program:
II my first program in C++
#include <iostream>
using namespace std;
int main()
{
cout << "Hello World!";
return O;
}
Output:-Hello World!
The first panel shows the source code for our first program. The second one shows the result of the
program once compiled and executed. The way to edit and compile a program depends on the
compiler you are using. Depending on whether it has a Development Interface or not and on its version.
Consult the compilers section and the manual or help included with your compiler if you have
doubts on how to compile a C++ console program.
The previous program is the typical program that programmer apprentices write for the first time,
and its result is the printing on screen of the "Hello World!" sentence. It is one of the simplest programs
that can be written in C++, but it already contains the fundamental components that every C++ program
has. We are going to look line by line at the code we have just written:
II my first program in C++
This is a comment line. All lines beginning with two slash signs (II) are considered comments and do not
have any effect on the behavior of the program. The programmer can use them to include short
explanations or observations within the source code itself In this case, the line is a brief description
of what our program is.
#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. In this case the directive
#include<iostream> tells the preprocessor to include the iostream standard file. This specific file
(iostream) includes the declarations of the basic standard input-output library in C++, and it is
included because its functionality is going to be used later in the program.
using namespace std;
All the elements of the standard C++ library are declared within what is called a namespace, the
namespace with the name std. So in order to access its functionality we declare with this expression
that we will be using these entities. This line is very frequent in C++ programs that use the standard
library, and in fact it will be included in most of the source codes included in these tutorials.
int main()
This line corresponds to the beginning of the definition of the main function. The main function is
the point by where all C++ programs start their execution, independently of its location within the source
code. It does not matter whether there are other functions with other names defined before or after it -
SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 13
SHRI SHANKARACHARYA TECHNICAL CAMPUS
the instructions contained within this function's definition will always be the first ones to be
executed in any C++ program. For that same reason, it is essential that all C++ programs have a main
function.
The word main is followed in the code by a pair of parentheses(()). That is because it is a function
declaration: In C++, what differentiates a function declaration from other types of expressions are
these parentheses that follow its name. Optionally, these parentheses may enclose a list of parameters
within them.
Right after these parentheses we can find the body of the main function enclosed in braces ({}).
What is contained within these braces is what the function does when it is executed.
cout << "Hello World!";
This line is a C++ statement. A statement is a simple or compound expression that can actually
produce some effect. In fact, this statement performs the only action that generates a visible effect in our
first program.
cout represents the standard output stream in C++, and the meaning of the entire statement is to
insert a sequence of characters (in this case the Hello World sequence of characters) into the standard
output stream (which usually is the screen).
cout is declared in the iostream standard file within the std namespace, so that's why we needed to include
that specific file and to declare that we were going to use this specific namespace earlier in our code.
Notice that the statement ends with a semicolon character (;). This character is used to mark the end
of the statement and in fact it must be included at the end of all expression statements in all C++ programs
(one of the most common syntax errors is indeed to forget to include some semicolon after a statement).
return O;
The return statement causes the main function to finish. return may be followed by a return code (in
our example is followed by the return code 0). A return code of O for the main function is generally
interpreted as the program worked as expected without any errors during its execution. This is the
most usual way to end a C++ console program.
You may have noticed that not all the lines of this program perform actions when the code is
executed. There were lines containing only comments (those beginning by//). There were lines with
directives for the compiler's preprocessor (those beginning by #). Then there were lines that began
the declaration of a function (in this case, the main function) and, finally lines with statements (like
the insertion into cout), which were all included within the block delimited by the braces ({}) of the main
function.
The program has been structured in different lines in order to be more readable, but in C++, we do
not have strict rules on how to separate instructions in different lines. For example, instead of
int main()
{
cout <<" Hello World!";
return O;
}
int main()
{
cout << "Hello World!";
return O;
}
All in just one line and this would have had exactly the same meaning as the previous code.
In C++, the separation between statements is specified with an ending semicolon (;) at the end of
each one, so the separation in different code lines does not matter at all for this purpose. We can
write many statements per line or write a single statement that takes many code lines. The division of
SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 14
SHRI SHANKARACHARYA TECHNICAL CAMPUS
code in different lines serves only to make it more legible and schematic for the humans that may
read it.
int main()
{
cout << "Hello World! ";
cout << "I'm a C++ program";
return O;
}
ln this case, we performed two insertions into cout in two different statements. Once again, the separation
in different lines of code has been done just to give greater readability to the program, since main
could have been perfectly valid defined this way:
int main()
{
cout << " Hello World! ";
cout <<" I'm a C++ program";
return O;
}
We were also free to divide the code into more lines ifwe considered it more convenient:
int main()
{
cout << "Hello World!";
cout << "I'm a C++ program";
return O;
}
And the result would again have been exactly the same as in the previous examples.
Preprocessor directives (those that begin by #) are out of this general rule since they are not
statements. They are lines read and processed by the preprocessor and do not produce any code by
themselves. Preprocessor directives must be specified in their own line and do not have to end with a
semicolon(;).
• Include files
• Class declaration
• Class functions, definition
• Main function program
Example:-
# include<iostream.h>
SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 15
SHRI SHANKARACHARYA TECHNICAL CAMPUS
class person
{
char name[30];
int age;
public:
void getdata(void);
void display(void);
};
void displayO
{
cout<<"\n name:"<<name;
cout<<"\n age:"<<age;
}
int main()
{
person p;
p.getdata();
p.display();
return(0);
TOKENS:
The smallest individual units in program are known as tokens. C++ has the following
tokens.
1. Keywords
11. Identifiers
111. Constants
1v. Strings
v. Operators
KEYWORDS:
The keywords implement specific C++ language feature. They are explicitly reserved
identifiers and can't be used as names for the program variables or other user defined program elements.
The keywords not found in ANSI C are shown in red letter.
C++ KEYWORDS:
IDENTIFIERS:
Identifiers refers to the name of variable , functions, array, class etc. created by programmer. Each
language has its own rule for naming the identifiers.
In ANSI C the maximum length of a variable is 32 chars but in c++ there is no bar.
C ++ Data Types
Built in types
void
Both C and C++ compilers support all the built in types. With the exception of void the basic
datatypes may have several modifiers preceding them to serve the needs of various situations. The
modifiers signed, unsigned, long and short may applied to character and integer basic data types. However
the modifier long may also be applied to double.
BYTES RANGE
char -128to-127
usigned 1 0 to 265
1) To specify the return type of function when it is not returning any value.
2) To indicate an empty argument list to a function.
Example:
Void function(void);
Example:
Void *gp;
Assigning any pointer type to a void pointer without using a cast is allowed in both C and ANSI C.
In ANSI C we can also assign a void pointer to a non-void pointer without using a cast to non void pointer
type. This is not allowed in C ++.
Example:
void *ptrl;
void *ptr2;
Are valid statement in ANSI C but not in C++. We need to use a cast operator.
ptr2=(char *) ptrl;
We have used user defined data types such as struct,and union in C. While these more features have been
added to make them suitable for object oriented programming. C++ also permits us to define
another user defined data type known as class which can be used just like any other basic data type to
declare a variable. The class variables are known as objects, which are the central focus of oops.
An enumerated data type is another user defined type which provides a way for attaching
names to number, these by increasing comprehensibility of the code. The enum keyword automatically
enumerates a list of words by assigning them values 0,1,2 and soon. This facility provides an alternative
means for creating symbolic.
Example:
enurn colour{red,blue,green,yellow}
The enumerated data types differ slightly in C++ when compared with ANSI C. In C++, the
tag names shape, colour, and position become new type names. That means we can declare new
variables using the tag names.
Example:
ANSI C defines the types of enums to be ints. In C++,each enumerated data type retains its
own separate type. This means that C++ does not allow an int value to be automatically converted to
anenum.
Example:
Example:
By default, the enumerators are assigned integer values starting with O for the first
enumerator, 1 for the second and so on. We can also write
C++ also permits the creation of anonymous enums ( i.e, enums without tag names)
Example:
enum{off,on};
Here off is O and on is 1.these constants may be referenced in the same manner as regular constants.
Example:
int switch-l=off;
int switch-2=on;
ANSI C permits an enum defined with in a structure or a class, but the enum 1s
globally visible. In C++ an enum defined with in a class is local to that class.
SYMBOLIC CONSTANT:
In both C and C++, any value declared as canst can't be modified by the program in any way.
In C++, we can use canst in a constant expression. Such as
This would be illegal in C. canst allows us to create typed constants instead of having to use #define to
create constants that have no type information.
const size=lO;
Means
C++ requires a canst to be initialized. ANSI C does not require an initializer, if none is given, it
initializes the canst to 0.
In C++ canst values are local and in ANSI C canst values are global .However they can be made local
made local by declaring them as static .In C++ ifwe want to make const value as global then declare as extern
storage class.
enum {x,y,z};
DECLARATION OF VARIABLES:
In ANSIC Call the variable which is to be used in programs must be declared at the beginning of the
program .But in C++ we can declare the variables any whose in the program where it requires .This makes the
program much easier to write and reduces the errors that may be caused by having to scan back and forth. It
also makes the program easier to understand because the variables are declared in the context of their use.
REFERENCE VARIABLES:
C++interfaces a new kind of variable known as the reference variable. A references variable
provides an alias.(altemative name) for a previously defined variable. For example ,if we make the
variable sum a reference to the variable total, then sum and total can be used interchangeably to represent
the variuble.
A reference variable is created as follows:
Synatx: Datatype & reference--name=variable name;
Example:
floattotal=l500;
float &sum=total;
Here sum is the alternative name for variables total, both the variables refer to the same data object in the
memory.
A reference variable must be initialized at the time of declaration.
Note that C++ assigns additional meaning to the symbol & here & is not an address operator
.The notation float & means reference to float.
Example:
int n[lO];
int &x=n[lO];
char &a='\n';
OPERATORS INC++:
C++ has a rich set of operators. All C operators are valid in C++ also. In addition. C++
introduces some new operators.
{
Int x =10;
}
Block2 contained in block I .Note that declaration in an inner block hides a declaration of the
same variable in an outer block and therefore each declaration of x causes it to refer to a different data object .
With in the inner block the variable x will refer to the data object declared there in.
In C,the global version of a variable can't be accessed from with in the inner block.
C++ resolves this problem by introducing a new operator :: called the scope resolution operator .This can be
used to uncover a hidden variable.
Example:
#include <iostrcam.h>
int m=lO;
main()
{
int m=20;
{
intk=m;
intm=30;
cout<<"we are in inner block";
cout<<''k=''<<k<<endl;
cout<<''m=''<<m<<endl;
cout<<":: m="<<:: m<<endl;
}
cout<<''\n we are in outer block \n";
cout<<''m=''<<m<<endl;
cout<<":: m="<<:: m<<endl;
}
C++ also support those 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.
The new operator can be used to create objects of any type. Syntax: pointer-
Example:
p=new int; q=new int;
"'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 the new operator.
Syntax:
int *p=ne\v int(25);
float *q =new float(7.5);
new can be used to create a memory space for any data type including user defined such as
arrays,structures,and classes .The general form for a one-dimensional array is:
If a data object is no longer needed, it is destroyed to release the memory space for reuse.
Example:
delete p;
delete q;
MANIPULATERS:
Manipulators are operator that are used to fonnat the data display. The most commonly manipulators are
endl and setw.
The endl manipulator, when used in an output statement, causes a line feed to be insert.(just like \n)
Example:
cout<<''m=''<<1n<<endl;
cout<<"n=''<<n<<endl;
cout<<"p=''<<p<<endl;
Ifwe assume the values of the variables as 2597,14 and 175 respectively
ITF2597; IF14;
p=175
It was want to print all nos in right justified way use setw which specify a c01mnon field width
for all the nos.
Example: cout<<setw(5)<<sum<<endl;
cout<<setw(1O)<<"basic"<<setw(1O<<basic<<endl;
Cout<<setw(lO)<<''allowance''<<setw(lO<<allowance<<endl;
cout<<setw(1O)<<"total="<<setw(1O)<<total;
CONTROL STRUCTURES:
Like c,c++, supports all the basic control structures and implements them various control statements.
The if statement:
l. simple if statement
2. i£ .. else statement
Simple if statement:
if (condition)
Action;
If(condition)
Statmentl
Else
Statement2
This is a multiple-branching statement where, based on a condition, the control is transferred to one of the many
case 1:
actionl;
break;
case 2:
action2;
break;
defuuh:
message
Syn:
While(condition)
Stements
Syn:
do
Stements
} while(condition);
fur(expression1;expression2;expression3)
Statements;
Statements;
FUNCTION INC++:
mainO
{
//main program statements
}
This is property valid because the main O in ANSI C does not return any value. In C++, the main O returns a value of
type int to the operating system The functions that have a return value should use the return statement for terminating.
The main O function in C++ is therefore defined as follows.
int main()
{
return(O)
}
Since the return type of functions is int by default, the key word int in the main( ) header is optional.
INLINE FUNCTION:
To eliminate the cost of calls to small functions C++ proposes a new feature called inline function.
An inline function is a function that is expanded inline when it is invoked .That is the compiler
replaces the function call with the corresponding function code.
The inline functions are defined as follows:-
inline function-header
{
function body;
}
Example: inline double cube (double a)
{
return(a*a*a);
}
#include<iostream.h>
#include<stdio.h>
inline float mul(float x, floaty)
{
return(x*y);
}
inline double div(double p.double q)
{
return(p/q);
}
main()
{
float a=12.345;
float b=9.82;
cout<<mul(a,b)<<endl;
cout<<div (a,b)<<endl;
}
output:-
121.227898
1.257128
DEFAULT ARGUMENT:-
C++ allows us to call a function with out specifying all its arguments.In such cases, the function
assigns a default value to the parameter which does not have a matching aguments in the function
call.Default values are specified when the function is declared .The compiler looks at the prototype to
see how many arguments a function uses and alerts the program for possible default values.
Example: float amount (float principle, int period ,float rate=0.15);
The default value is specified in a manner syntactically similar to a variable initialization
.The above prototype declares a default value of 0.15 to the argument rate. A subsequent function
call like
value=amount(5000,7); //one argument missing
passes the value of 5000 to principle and 7 to period and then lets the function, use default value of
CONST ARGUMENT:-
In C++, an argument to a function can be declared as unit as const as shown
below.
int strlen(const char *p); int
length(const string &s);
The qualifier const tells the compiler that the function should not modify the argument .the
compiler will generate an error when this condition is violated .This type of declaration is significant only
when we pass arguments by reference or pointers.
FUNCTION OVERLOADING:
Overloading refers to the use of the same thing for different purposes . C++ also
permits overloading functions .This means that we can use the same function name to creates
functions that perform a variety of different tasks. This is known as function polymorphism in oops.
Using the concepts of function overloading , a family of functions with one function
name but with different argument lists in the functions call .The correct function to be invoked is
determined by checking the number and type of the arguments but not on the function type.
For example an overloaded add() function handles different types of data as shown
below.
//Declaration
int add(int a, int b); //prototype 1
int add (int a, int b, int c); //prototype 2
double add(double x, double y); //prototype 3
double add(double p, double q); //prototype 4
//function call
cout<<add(S,10); //uses prototype 1
cout<<add(15,10.0); //uses prototype 4
cout<<add(12.5,7.5); //uses prototype 3
cout<<add(S,10,15); //uses prototype 2
cout<<add(0.75,5); //uses prototype 5
A function call first matches the prototype having the same no and type of arguments and then calls
the appropriate function for execution.
The function selection invokes the following steps:-
a) The compiler first tries to find an exact match m which the types of actual
arguments are the same and use that function .
b) If an exact match is not found the compiler uses the integral promotions to the actual
arguments such as :
char to int
float to double
to fmd a match
c)When either of them tails ,the compiler tries to use the built in conversions to the actual arguments
and them uses the function whose match is unique. If the conversion is possible to have multiple matches,
then the compiler will give error message.
Example:
long square (long n);
double square(double x);
A function call such as :- square(lO)
Will cause an error because int argument can be converted to either long or
double .There by creating an ambiguous situation as to which version of square( )should be used.
#include<iostream.h>
int volume(double,int);
double volume( double , int );
double volume(longint ,int ,int);
main()
{
cout<<volume(10)<<endl;
cout<<volume(l 0)<<endl; cout<<volume(l 0)<<endl;
}
int volume( ini s)
{
return (s*s*s); //cube
}
double volume( double r, int h)
{
return(3.1416*r*r*h); //cylinder
}
long volume (longint 1, int b, int h)
{
return(l *b*h); //cylinder
}
output:- 1000
157.2595
112500