Following is a sample program in
C++ that prints a string on the string.
#include<iostream.h>
int main()
{
cout<<”Hi
Everybody”;
return
0;
}
Like in C, functions are the
basic building block in C++. The above example consists of a single function
called main ().
When a C++ program executes, the
first statement that executes will be the first statement in main () function.
The main function calls member functions of various classes (using objects) to
carry out the real work. It may also call other stand-alone functions.
In C++, the return type of the
main function is ‘int’. So, it returns one integer value to the operating
system. Since the return type int is default, the keyword ‘int’ in main () is
optional. So,
main
()
{
…….// also valid
}
Compilers generate error if no
value is returned. Many operating systems test the return values. If the exit
value is zero (0), the operating system will understand that the program ran
successfully. If the returned value (exit value) is non zero, it would mean
that there was problem.
Comment syntax
In C++, comments start with a
double slash (//) symbol and end at the end of the line. A comment may start at
the beginning of a line or anywhere in the line and whatever follows till the
end of that line is ignored. There is no closing symbol. If we need to comment
multiple lines, we can write as
// this is an
// example
// of multi line
comments
The C comment style /*………….*/ may
also be used for multi line comments.
The output operator
The statement – cout<<”Hi Everybody”;
in the above example prints the phrase in quotation marks on the screen.
Here, the identifier ‘cout’,
pronounced as see out, is a predefined object of standard stream in C++. The
operator << is called ‘insertion’ or ‘put to’ operator. It inserts the
content on its right to the object on its left.
cout<<a
In the above case, the statement
will display the content of the variable ‘a’.
The input operator
A statement
cin>>a;
is an input statement. This causes the program to wait for the user
to type and give some input. The given input is stored in the variable a.
Here, the identifier ‘cin’,
pronounced as ‘see in’ is an object of standard input stream. The operator
‘>>’ is called ‘extraction’ or ‘get from’ operator. It extracts or gets
value from keyboard and assigns it to the variable on its right.
Cascading I/O operators
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.
The iostream header file
The directive
‘#include<iostream.h>’ causes the preprocessor to add the contents of
iostream.h file to the program. It contains the declarations of identifiers
cout, cin and the operators << and >>. So, the header file iostream
should always be included at the beginning if we need to use cin, cout,
<< and >> operators in our program.
Tokens: Tokens are the smallest individual units in a program.
Keywords, identifiers, constants, strings and operators are tokens in C++.
Keywords: Keywords are explicitly reserved identifiers and can not
be used as names for the program variables or other user-defined program
elements. Some keywords are int, auto, switch, case, do, else, public, default, continue etc.
Functions
A function is a single
comprehensive unit that performs a specified task. This specified task is
repeated each time the function is called. Functions break large programs into
smaller tasks. They increase the modularity of the programs and reduce code
redundancy.
Like in C, C++ programs also
should contain a main function, where the program always begins execution. The
main function may call other functions, which in turn will again call other
functions.
When a function is called,
control is transferred to the first statement of the function body. Once the
statements of the function get executed (when the last closing bracket is
encountered) the program control return to the place from where this function
was called.
Data types in C++
Fig. Hierarchy of C++
Data types
Enumerated Data Types
Like structures, enumerated data
type is another user defined data type. Enumerated means that all the values
are listed. They are used when we know a finite list of values that a data type
can take on or it is an alternative way for creating symbolic constants. The
‘enum’ keyword automatically lists a list of words and assign them values
0,1,2…
Eg. enum shape
{circle, square, triangle};
enum Boolean {true, false};
enum switch {on, off};
The above example is equivalent
to
const circle = 0;
const
square = 1;
const
triangle = 2;
We can even use standard
arithmetic operator on enum types. We can also use relational operators when
suitable. This is because, the enum data types are internally treated as
integers.
Once we specify the data type, we
need to define variables of that type.
Eg.
shape s1,s2;
Now the variables s1, s2 can hold
only the members of ‘shape’ data type (those are circle, square and triangle)
and can not hold anything except these values. If other values are given, error
will be generated.
An example
#include<iostream.h>
#include<conio.h>
enum days {sun, mon, tue, wed, thur, fri, sat};
#include<conio.h>
enum days {sun, mon, tue, wed, thur, fri, sat};
void main()
{
days
d1,d2;
d1
= sun;
d2
= thur;
int
diff = d2-d1; // using arithmetic
operator
cout<<”Days
between”<<diff<<endl;
if(d1<d2) // using relational operator
cout<<”d1
comes first”;
getch();
}
Reference variables
Reference variables are new type
of variable introduced in C++. It provides an alias (another name) for a
previously defined variable. A syntax to create a reference variable is
data-type &reference-name = variable name;
eg-
float
total = 100;
float
&sum = total; // creating reference variable for ‘total’.
In the above example, we are
creating a reference variable ‘sum’ for an existing variable ‘total’. Now these
can be used interchangeably. Both of these names refer to same data object in
memory. If the value is manipulated and changed using one name then it will
change for another also. Eg- the statement
total
= total + 200; will change value of ‘total’ to 300. And it will also change for
‘sum’. So the statements
cout<<sum;
cout<<total; both will
print 300. This is because both the variables use same data object in memory.
-
A reference variable must be initialized at the time of
declaration, since this will establish correspondence between the reference and
the data object which it names.
-
The symbol & is not an address operator here. The
notation int & means reference to integer type data.
-
References can also be created for user defined data
types like structures and classes.
-
Another application of reference variable is in passing
arguments to function.
In general, arguments are passed
by value. The called function creates a new value of the same type as the
argument and copies the argument value into it. The function does not access
the actual value. Although this provides security to the actual data, it is not
suitable if we need to modify actual data. For such situations, we can use
reference. Instead of value, a reference to the original variable is passed to
the called function. This is called calling
function by reference. The advantage is that the called function can use
actual variable and not its copy only. Likewise, we can also return values
using reference. (Example- swapping values)
Manipulators
The manipulators are operators
used with insertion operator “<<’ to format or manipulate the data
display. ‘endl’ and ‘setw’ are most common manipulators.
endl manipulator causes a linefeed to be inserted into the output
stream. i.e the cursor moves to next line. It is similar to ‘\n’ character.
Eg-
cout<<”Kathmandu ”<<endl;
cout<<”Nepal ”;
See output
setw manipulator specify a field width to a number or string that
follows it and force them to be printed right justified. The field width is
given as an argument to this manipulator.
Eg-
x
= 456; y = 40;
cout<<setw(5)<<x<<setw(5)<<y;
The manipulator will specify a
field 5 for printing the value of x. The value is right justified within the
fields as shown below. For y, it will specify again space of width 5, right
justifies and prints.
No comments:
Post a Comment