C Unit2
C Unit2
Chapter- Two
“C++ Language basic syntax”
2.1 Introduction to C++:
t is one of the world's most popular OO programming languages.
It was first invented by Bjarne Stroustrup in 1979 at Bell Laboratories in Murray Hill, New
Jersey.
Bjarne Stroustrup initially called the new language "C with Classes." However, in 1983 the name
was changed to C++.
It is a middle-level language rendering it the advantage of programming low-level (drivers,
kernels) and even higher-level applications (games, GUI, desktop apps etc.). The basic syntax and
code structure of both C and C++ are the same.
It is a statically typed, compiled, general purpose, case -sensitive, free-form programming
language that supports procedural, object-oriented, and generic programming.
It is an object-oriented programming language which gives a clear structure to programs and
allows code to be reused, lowering development costs.
It can be found in today's operating systems, Graphical User Interfaces, and embedded systems.
It is portable and can be used to develop applications that can be adapted to multiple platforms.
Some of the features & key-points to note about the programming language are as follows:
Simple Abstract Data Machine Independent Quicker Compilation Recursion
types or Portable
Rich Memry Structured Modeling Real-World Extensibl
Library Management programming language Problems e
Object- Compiler based Mid-level Errors are easily Clarity
Oriented programming language detected
Reusability Redefine Existing Strongly typed Power and Flexibility Pointers
Operators language
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 anywhere in the line and whatever follows till
the end of line is ignored 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. 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
// c++ program
// thank you
The c comment symbols /* ….*/ are still valid and more suitable for multi-line comments.
/* this is an example of c++ program */
Paper by Naresh Kumar Shah (2080) 1
Purbanchal University School of Science & Technology, Biratnagar
Output Operator:
The statement cout <<” Hello, world” displayed the string within 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;
“cin>>” is an input statement. The program to wait for the user to type in a number. The number
keyed in is placed in the variable number1. The identifier cin is a predefined object in C++ that
corresponds to the standard input stream.
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>>number1>>number2;
Probably the best way to start learning a programming language is by writing a program. Therefore,
here is our first program:
//First program in C++
#include<iostream.h> cout << "Hello World!";
#include<conio.h> getch();
int main () return 0; Output:-Hello World!
{ }
clrscr();
We are going to look line by line at the code we have just written:
#include
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 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.
int main ()
It looks like you've started to write a C++ program with the int main() function, which is typically the
entry point of a C++ program. It does not matter whether there are other functions with other names
defined before or after it. 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. To complete your program, you'll need to add the necessary code inside the main()
function. This is where your program's execution will begin.
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).
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 0;
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 0 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.
TOKENS:
The smallest individual units in program are known as tokens. Tokens are the building blocks of a
program and are used by the compiler to understand and process the code. C++ has the following
tokens.
i. Keywords
ii. Identifiers
iii. Operators
iv. Strings
v. Constants
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.
A keyword is a reserved word that have special meaning in the language. You cannot use it as
a variable name, constant name etc.
A list of 32 Keywords in C++ Language which are also available in C language are given below.
Auto break Case Char const continue default do
Double else Enum Extern float For goto if
Int long register Return short signed sizeof static
Struct switch typedef Union unsigned Void volatile while
A list of 30 Keywords in C++ Language which are not available in C language are given below.
Asm dynamic_cast namespace reinterpret_cast bool explicit New static_cast
False Catch operator Template friend private class this
Inline Public throw const_cast delete Mutable protected true
Try Typeid Typename Using virtual wchar_t
IDENTIFIERS:
Identifiers refers to the name of variable, functions, array, class etc. Identifiers are user-defined
created by programmer. Each language has its own rule for naming the identifiers.
The following rules are common for both C and C++
1. Names can contain Only alphabetic chars, digits and underscore are permitted. Names must
begin with a letter or an underscore (_)
2. The name can’t start with a digit.
i) Fundamental Data (or Primitive/Basic/ Built-in) Types ii) Derived data types iii) User-defined data
types iv) Empty data type.
Primitive Data Types: These data types are built-in or predefined data types and can be used directly
by the user to declare variables. example:
Type Size Example
Char 1 byte char ch = 'A';
Int 2 byte int num = 100;
Float 4 bytes float num = 123.78987;
Double 8 bytes double num = 10098.98899;
Bool True or false bool b = true;
1) Arrays:
An array is a derived data type which contains homogeneous elements. Arrays refer to a list of
finite number of same data types. The data in the array can be accessed by an index number
ranging from 0 to n(where n is the number of data element it can store).
Ex- if arr[3] is an array of integers then the different values in the array can be accessed as
shown below. arr[0], arr[1],arr[2] when we declare an array such as the one sown above then by
arr[3] we mean that we want three elements in the array and hence while accessing arr[2] is the
last element.
#include<iostream.h> for(i=0; i<num; i++)
#include<conio.h> {
int main() cin>>arr[i];
{ }
int arr[50], num, i; cout<<"\n The Elements in the Array are : \n";
cout<<"\n How Many Elements You for(i=0; i<num; i++)
Want to Store into an Array? \n"; {
cin>>num; cout<<arr[i]<<"\t";
cout<<"\n Enter "<<num<<" Elements to }
Store into an Array : \n"; getch(); return 0; }
2.) Pointer: A pointer is a variable that holds the memory address of other variable. It is also of
different data types. Pointers allow to use the memory dynamically. That is, with the help of
pointers, memory can be allocated or de-allocated to the variables at run-time, thus, making a
program more efficient. For example- char pointer can store address of only char variables; int
pointer can store address of int variables and so on.
3.) Reference: A reference is an alias or alternate name for a previously defined variable. It is
possible to define a reference variable for a variable of any data type. In the following
example, k is a variable of integer data type. Reference variable y refers to k.
int k=10;
int & y=k; // variable y is a reference to variable k.
cout<<k; // prints 10
cout<<y; // prints 10
4) Function: A function is a self-contained program segment that carries out a specific well-
defined task. In C++, every program contains one or more functions which can be invoked from
other parts of a program, if required.
User-Defined Derived Data Types
1. Class: A class is a collection of variables and function under one reference name. It is the way
of separating and storing similar data together. Member functions are often the means of
accessing, modifying and operating the data members (i.e. variables). It is one of the most
important features of C++ since OOP is usually implemented through the use of classes. Classes
are declared using the keyword class. Once a class has been declared, its object can be easily
created.
2. Structure: In C++ structure and class same except for some very minor differences.
3. Union: A union is a memory location shared by two or more different variables, generally of different
data types. Giving more details here would only confuse you; I’ll leave it for future articles.
Paper by Naresh Kumar Shah (2080) 6
Purbanchal University School of Science & Technology, Biratnagar
Here, The enum-name is the enumeration's data type name. The list of names is separated by comma.
For example, the following code defines an enumeration of colors.
enum color { red, green, blue };
By default, the value of the first name is 0, the second name has the value 1, the third has the value 2,
and so on. But you can give a name a specific value by adding an initializer. For example, in the
following enumeration, green will have the value 5.
enum color { red, green=5, blue };
Here blue will have a value of 6 because each name will be one greater than the one that precedes it.
Example:
#include <iostream.h> #include <iostream.h>
#include<conio.h> #include<conio.h>
enum directions { North, South=3, East, West }; enum year // Defining enum Year
int main() {Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec};
{ // Driver Code
clrscr(); int main()
directions direction; {
direction = East; int i;
cout << "Direction: " << direction clrscr();
<<endl; for (i = Jan; i <= Dec; i++) // Traversing the year enum
getch(); cout << i << " ";
return 0; } getch(); return 0; }
2.1 OPERATORS IN C++ :
C++ has a rich set of operators. All C operators are valid in C++ also. In addition C++ introduces
some new operators.
<< insertion operator .* pointer to member operator
>> extraction operator New memory allocation operator
:: scope resolution operator Delete memory release operator
::* pointer to member declaratory Setw field width operator
. member operator Endl line feed operator
Value of local x is 3 C c;
Test::y = 2; c.fun();
getch();
return 0; }
In C,the global version of a variable can't be accessed from within 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. Syntax: : : variable –name;
#include <iostream.h> #include<conio.h> cout<<"k="<<k<<endl; //20
int m=10; cout<<"m="<<m<<endl; //30
int main() cout<<":: m="<<:: m<<endl; //10
{ clrscr(); }
int m=20; cout<<"\n we are in outer block \n";
{ cout<<"m="<<m<<endl; //20
int k=m; cout<<":: m="<<:: m<<endl; //10
int m=30; getch();
cout<<"we are in inner block"; return 0; }
int x = 10; // integer x cout << "x = " << x << endl
char y = 'a'; // character c << "y = " << y << endl Output:
x = 107
// y implicitly converted to int. ASCII << "z = " << z << endl;
y=a
// value of 'a' is 97 getch(); z = 108
return 0; }
Explicit Conversion (Also called type casting and it is user-defined)
In C++ type cast involves data conversions specified by the programmer when the automatic data
conversions do not occur. Sometimes a programmer needs to convert a value from one type to
another in a situation when the compiler will not do it automatically.
Explicit Type Conversions are those conversions that are done by the programmer manually.
In other words, explicit conversion allows the programmer to typecast (change) the data type of a
variable to another type. Hence, it is also called typecasting. Generally, we use the explicit type
conversion if we do not want to follow the implicit type conversion rules.
Explicit type conversion in C++ can be done in two ways:
Conversion using the Assignment Operator
Conversion using the Function-style Casting
Let us take a look at each one of them
Converting by assignment: This is done by explicitly defining the required type in front of the
expression in parenthesis. This can be also considered as forceful casting.
Syntax: (type) expression // where type indicates the data type to which the final result is
converted. Example;
// C++ program to demonstrate explicit type casting
#include <iostream.h> int sum = (int)x + 1;
#include<conio.h> cout << "Sum = " << sum; Output:
int main() getch(); // Sum=2
{ return 0;
double x = 1.2; }output;
// Explicit conversion from double to int
Function-style Casting: We can also use the function like notation to cast data from one type to
another. The syntax for this style is: data-type (expression);
Example:
// C++ program to demonstrate explicit type casting // C-style conversion from double to int
#include <iostream.h> int num_int1 = (int)num_double;
#include<conio.h> Output: cout << "num_int1 = " << num_int1 << endl;
int main() num_double=3.56
num-int=3
{ num-int=3
// function-style conversion from double to int
// initializing a double variable int num_int2 = int(num_double);
double num_double = 3.56; cout << "num_int2 = " << num_int2 << endl;
cout << "num_double = " << num_double << endl; getch(); return 0; }
Manipulators in C++
Manipulators are helping functions in C++ that are used to modify the input/output stream. What it
means, it will not modify the value of a variable, it will only modify the streams or formatting streams
using the insertion (<<) and extraction (>>) operators.
1. Manipulators are special functions that can be included in the I/O statement to alter the format
parameters of a stream.
2. Manipulators are operators that are used to format the data display.
3. To access manipulators, the file iomanip should be included in the program.
Manipulators are used for enhancing streams or formatting streams. For writing the data, we can adopt
some formats. For example, a common manipulator that we used is the endl that is used for the endline.
Instead of endl, we can also say that cout << “\n”; This will also print a new line. So, endl is a
manipulator which is used for formatting stream. So, it is useful for formatting output streams.
Syntax: setw(x)
#include<iostream.h>
#include<iomanip.h>
#include<conio.h>
int main() {
clrscr();
int age = 22,rollno = 9101;
cout<<setw(12)<<"My Rollno is"<<setw(8)<<rollno<<endl;
cout<<setw(12)<<"My Aqe is"<<setw(8)<<age;
getch();
return 0; }
In the above program, the setw() manipulator causes the number or string that follows it in the cout
statement to be displayed within the specified width. The value to be displayed is right-justified. The
values of variable rollno and age are displayed within 8 spaces specified using setw(S) manipulator.
The value is padded with leading blank spaces as it doesn’t fill the whole width.
If the value is larger than the specified width, it will not truncate the value, and the value is
printed as it is. For example
cout<<setw(2)<<"Roll
is"<<setw(2)<<rollno;
the output is
setfill(c) Manipulator
The setfill() manipulator is used in conjunction with the setw() manipulator. The compiler leaves the
empty spaces on the left side of the required value if the set width is greater than the needed space. If
you wish to fill the blank space with an alternative character instead of a blank space, you can use the
setfill () manipulator.
Generally, you will not want to change the fill character. However, one common example of when
you may want to is creating a program that prints cheques. To prevent the cheque amount from being
altered by the user, computer-generated cheque amounts are usually printed with leading asterisks(*).
This is done in C++ with a setfill() manipulator.
The setfill () manipulator takes a single character as an argument and fills the empty spaces with the
specified character c on the left of the value displayed if the width specified using setw() manipulator
is greater than the value to be displayed.
#include<iostream.h> int age = 22,rollno = 910l; cout<<setfill('#'); Output :
#include<iomanip.h> cout<<setw(4)<<age<<setw(6)<<rollno<<endl; ##22##9101
#include<conio.h> cout<<setfill('*'); ####22####9101
int main() { cout<<setw(6)<<age<<setw(8)<<rollno;
clrscr(); getch();return 0; }
setprecision(n) Manipulator
The setprecision() manipulator is used to control the precision of floating-point numbers, i.e. the
number of digits to the right of the decimal point. By default, the precision of the floating-point number
displayed is 6. This precision can be modified by using a setprecision () manipulator. This function
takes an integer argument that specifies the number of digits displayed after the decimal point. The
floating-point number will be rounded to the specified precision.
#include<iostream.h> float a = 129.455396; /*Output :
#include<iomanip.h> cout<<setprecision(2)<<a<<endl; 129.46
#include<conio.h> cout<<setprecision(5)<<a; 129.455*/
int main() { getch();
clrscr(); return 0;}
setbase(b) Manipulator
The setbase () manipulator is used to change the base of a numeric value during inputting and
outputting. It is an alternative to Dec, Oct and hex manipulators. It is a function that takes a single
integer argument(b) having values 8, 10 or 16 to set the base of the numeric value to octal, decimal
and hexadecimal, respectively. The default base is 10.
#include<iostream.h> Output
Enter number in Octal form = 21
#include<conio.h> Value of number in decimal form = 17
#include<iomanip.h> Value of number in octal form = 21
int main() { Value of number in hexadecimall form = 11
int num;
clrscr();
cout<<"Enter number in Octal form = ";
cin>>setbase(8)>>num;
cout<<"Value of number in decimal form = "<<setbase(10)<<num<<endl;
cout<<"Value of number in octal form = "<<setbase(8)<<num<<endl;
cout<<"Value of number in hexadecimal form = "<<setbase(16)<<numl;
getch();
return 0; }
In the above program, the value of variable num is inputted in octal form using setbase(8) manipulator
in the cin statement. The value of the variable num is displayed in different number systems by using
setbase(b) manipulator with arguments values 10, 8 and 16.
Dec, Oct,Hex Manipulator
All the numbers are displayed and read in decimal notation by default. However, you may change the
base of an integer value to octal or hexadecimal or back to a decimal using the manipulator’s oct, hex
or dec, respectively. These manipulators are preceded by the appropriate variables to be used with.
#include<iostream.h> Output :
#include<conio.h> Enter hexadecimal = f
int main() { Hexadecimal = f
int i; Octal value = 17
cout<<"Enter hexadecimal number ="; Decimal value = 15
cin>>hex>>i;
cout<<"Hexadecimal value = "<<hex<<i<<endl;
Paper by Naresh Kumar Shah (2080) 13
Purbanchal University School of Science & Technology, Biratnagar
In C, we use malloc() and calloc() functions to allocate memory dynamically at run time. Similarly,
we use function free() to dynamically allocated memory. we use dynamic allocation techniques when
it is not known in advance how much memory space is needed. now C++ supports these functions
and also define two unary operators new and delete that also help to allocate and free the memory in
much convenient way.
new operator:
*p=new int[a];
delete operator:
If we reserve a lot of memory using the new operator then finally there will no more memory left and
the system may crash. Thus we use the delete operator to free up the memory that is allocated by the
new operator.
Syntax for delete operator is:-
delete[size] pointer variable;
or
delete pointer_variable in above example: delete n;
It should be noted that if new operator is used to allocated memory explicitly to a variable, the delete
operator should be used to destroy it. Though the variable goes out of the scope when the program
gets terminated, the memory area allocated by the new operator is not released to the system unless
the delete operator explicitly releases it.
Constant Pointer : A constant pointer is a pointer that cannot change address it is pointing to. This
means that suppose there is a pointer which points to a variable (or stores the address of that
variable). Now if we try to point the pointer to some other variable (or try to make the pointer store
address of some other variable), then constant pointers are incapable of this.
A constant pointer is declared as : int *const p
Pointer to Constant : A pointer to a constant is a pointer that cannot change the value of the
variable whose address it is holding.
A pointer to a constant is declared as : const int *ptr;