Search This Blog

Class XI | CHAPTER 6

Getting Started With C++

Introduction

C++  is  a  statically typed,  compiled,  general-purpose,  case-sensitive,  free-form programming  language  that  supports  procedural,  object-oriented,  and  generic programming.
C++  is  regarded  as  a middle-level language,  as  it  comprises  a  combination  of both high-level and low-level language features.
C++ was developed by Bjarne Stroustrup starting in 1979 at Bell Labs in Murray Hill, New Jersey, as an enhancement to the C language and originally named C with Classes but later it was renamed C++ in 1983.
C++  is  a  superset  of  C,  and  that  virtually  any  legal  C  program  is  a  legal  C++ program.
Note: A  programming  language  is  said  to  use  static  typing  when  type  checking is performed during compile-time as opposed to run-time.

The ANSI Standard

The ANSI standard is an attempt to ensure that C++ is portable;  that code you write  for  Microsoft's  compiler  will  compile  without  errors,  using  a  compiler  on  a Mac, UNIX, a Windows box, or an Alpha.
The ANSI standard has been stable for a while, and all the major C++ compiler manufacturers support the ANSI standard.

Object - Oriented Programming

C++  fully  supports  object-oriented  programming,  including  the  four  pillars  of object-oriented development:
·         Encapsulation
·         Data hiding
·         Inheritance
·         Polymorphism

Standard Libraries

Standard C++ consists of three important parts:
·         The  core  language  giving  all  the  building  blocks  including  variables,  data types and literals, etc.
·         The C++ Standard Library giving a rich set of functions manipulating files, strings, etc.
·         The  Standard  Template  Library  (STL)  giving  a  rich  set  of  methods manipulating data structures, etc.

C++ Character Set

Character set is a set of valid characters that a language can recognise. A character represents any letter, digit, or any other sign. The C++ has the following character set:
Letters: A-Z, a-z
Digits: 0-9
Special Symbols: Space + - * / ^ # ( ) [ ] { } = != < > . �? �? $ , ; : % ! & ? _(underscore) # <= >= @
White Spaces: Blank Spaces, Horizontal tab, Carriage return, Newline, Form feed.
Other Characters:  C++ can process any of the 256 ASCII characters as data or as literals.

Tokens (Lexical Units)

In a passage of text, individual words and punctuation marks are called tokens or lexical units or lexical elements. C++ has the following tokens:
·         Keywords
·         Identifiers
·         Literals
·         Punctuators
·         Operators

Keywords

Keyword is a word having special meaning reserved by programming language.
The following list shows the reserved words in C++. These reserved words may not be used as constant or variable or any other identifier names.
asm
else
new
this
auto
enum
operator
throw
bool
explicit
private
true
break
export
protected
try
case
extern
public
typedef
catch
false
register
typeid
char
float
reinterpret_cast
typename
class
for
return
union
const
friend
short
unsigned
const_cast
goto
signed
using
continue
if
sizeof
virtual
default
inline
static
void
delete
int
static_cast
volatile
do
long
struct
wchar_t
double
mutable
switch
while
dynamic_cast
namespace
template

Identifiers

A C++ identifier is a name used to identify a variable, function, class, module, or any other user-defined item. An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more letters, underscores, and digits (0 to 9).
C++  does  not  allow  punctuation  characters  such  as  @,  $,  and  %  within identifiers.  C++  is  a  case-sensitive  programming  language. Thus, Manpower and manpower are two different identifiers in C++.
Here are some examples of acceptable identifiers:
mohd zara abc   move_name a_123
myname50 _temp j a23b9 retVal

Literals

Literals (often referred to as constants) are data items that never change their value during a program run.
C++ allows several kinds of literals:
·         bool literal
·         integer-constant
·         character-constant
·         floating-constant
·         string-literal

bool literal

A bool literal of C++ can either have value true (boolean true) or false(boolean false).

Integer-constant

An  integer  literal  can  be  a  decimal,  octal,  or  hexadecimal  constant.  A  prefix specifies the base or radix: 0x or 0X for hexadecimal, 0 for octal, and nothing for decimal.
An  integer  literal  can  also  have  a  suffix  that  is  a  combination  of  U  and  L,  for unsigned  and  long,  respectively.  The  suffix  can  be  uppercase  or  lowercase  and can be in any order.
Here are some examples of integer literals:
212  // Legal
215u  // Legal
0xFeeL  // Legal
078  // Illegal: 8 is not an octal digit
032UU  // Illegal: cannot repeat a suffix
Following are other examples of various types of Integer literals:
85  // decimal
0213  // octal
0x4b  // hexadecimal
30  // int
30u  // unsigned int
30l  // long
30ul  // unsigned long

Character Literals

Character literals are enclosed in single quotes. If the literal begins with L(uppercase  only), it is a wide character  literal  (e.g.,  L'x')  and  should  be  stored in wchar_t type of variable. Otherwise, it is a narrow character literal (e.g., 'x') and can be stored in a simple variable of char type.
A character literal can be a plain character (e.g., 'x'), an escape sequence (e.g., '\t'), or a universal character (e.g., '\u02C0').
There  are  certain  characters  in  C++  when  they  are  preceded  by  a  backslash they will have special meaning and they are used to represent like newline (\n) or tab (\t). Here, you have a list of some of such escape sequence codes:
Escape Sequence
Meaning
\\
\ character
\�?
�? character
\�?
�? character
\?
? character
\a
Alert or bell
\b
Backspace
\f
Form feed
\n
Newline
\r
Carriage return
\t
Horizontal tab
\v
Vertical tab
\ooo
Octal number of one to three digits
\xhh�?
Hexadecimal number of one or more digits

Floating - point  Literals

A floating-point literal has an integer part, a decimal point, a fractional part, and an exponent part. You can represent floating point literals either in decimal form or exponential form.
While representing using decimal form, you must include the decimal point, the exponent,  or  both  and  while  representing  using  exponential  form,  you  must include  the  integer  part,  the  fractional  part,  or  both.  The  signed  exponent  is introduced by e or E.
Here are some examples of floating-point literals:
3.14159  // Legal
314159E-5L  // Legal
510E  // Illegal: incomplete exponent
210f  // Illegal: no decimal or exponent
.e55  // Illegal: missing integer or fraction

String  Literals

String  literals  are  enclosed  in  double  quotes.  A  string  contains  characters  that are  similar  to  character  literals:  plain  characters,  escape  sequences,  and universal characters.
You  can  break  a  long  line  into  multiple  lines  using  string  literals  and  separate them using whitespaces.
Here are some examples of string literals. All the three forms are identical strings.
"hello, dear"
"hello, \
dear"
"hello, " "d" "ear"

Operators

Operators are tokens that trigger some computation when applied to variables and other objects in an expression. An operator is a symbol that tells the compiler to perform specific mathematical or  logical  manipulations.  C++  is  rich  in  built-in  operators  and  provide  the following types of operators:
·         Arithmetic Operators
·         Relational Operators
·         Logical Operators
·         Bitwise Operators
·         Assignment Operators
·         Misc Operators

Unary operators

Unary operators are those operators that require one operator to operate upon. Following are some unary operators:
&
Address operator
*
Indirection operator
+
Unary plus
-
Unary minus
~
Bitwise complement
++
Increment operator
--
Decrement operator
!
Logical negation

Binary Operators

Binary operators are those operators that require two operands to operate upon.
Assume variable A holds 10 and variable B holds 20, then:
Operator
Description
Example
+
Adds two operands
A + B will give 30
-
Subtracts second operand from
the first
A - B will give -10
*
Multiplies both operands
A * B will give 200
/
Divides numerator by denumerator
B / A will give 2
%
Modulus Operator and remainder of after an integer
division
B % A will give 0
++
Increment  operator,  increases integer value by one
A++ will give 11
--
Decrement  operator,  decreases integer value by one
A-- will give 9

Shift Operators

<< shift left
>> shift right

Bitwise Operators

Bitwise operators work on bits and perform bit-by-bit operation. The truth tables for &, |, and ^ are as follows:
p
q
p & q
p | q
p ^ q
0
0
0
0
0
0
1
0
1
1
1
1
1
1
0
1
0
0
1
1

Assume if A = 60; and B = 13; now in binary format they will be as follows:
A = 0011 1100
B = 0000 1101
-----------------
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011
The  Bitwise  operators  supported  by  C++  language  are  listed  in  the  following table. Assume variable A holds 60 and variable B holds 13, then:
Operator
Description
Example
&
Binary AND Operator copies a bit to the result if it exists in both operands.
(A  &  B) will give 12 which is
0000 1100
|
Binary OR Operator copies a bit if it exists in either operand.
(A  |  B) will give 61 which is
0011 1101
^
Binary XOR Operator copies the bit if it is set in one operand but not both.
(A  ^  B)  will give 49 which is 0011 0001
~
Binary Ones Complement Operator is unary and has the effect of 'flipping' bits.
(~A  ) will give -61 which is
1100 0011 in 2's complement form due to a signed binary number.
<< 
Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand.
A  <<  2 will give 240 which is
1111 0000
>> 
Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand.
A  >>  2 will give 15 which is
0000 1111

Logical Operators

There are following logical operators supported by C++ language.
Assume variable A holds 1 and variable B holds 0, then:
Operator
Description
Example
&&
Called Logical AND operator. If both the operands are non-zero, then condition becomes true.
(A && B) is false.
||
Called Logical OR Operator. If any of the two operands is nonzero, then condition becomes true.
(A || B) is true.
!
Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true, then Logical NOT operator will make false.
!(A && B) is true.

Assignment Operators

There are following assignment operators supported by C++ language:
Operator
Description
Example
=
Simple assignment operator, Assigns values from right side operands to left side operand.
C = A + B will assign value of A + B into C
+=
Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand.
C += A is equivalent to C = C + A
-=
Subtract  AND  assignment operator,  It  subtracts  right operand  from  the  left  operand and  assign  the  result  to  left operand.
C  -=  A  is  equivalent  to  C  =  C - A
*=
Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand.
C *= A is equivalent to C = C *
A
/=
Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand.
C  /=  A  is  equivalent  to  C  =  C  /
A
%=
Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand.
C  %=  A  is  equivalent  to  C  =  C
% A
<<=
Left shift AND assignment operator.
C <<= 2 is same as C = C << 2
>>=
Right shift AND assignment operator.
C >>= 2 is same as C = C >> 2
&=
Bitwise AND assignment operator.
C &= 2 is same as C = C & 2
^=
Bitwise exclusive OR and assignment operator.
C ^= 2 is same as C = C ^ 2
|=
Bitwise inclusive OR and assignment operator.
C |= 2 is same as C = C | 2

Relational Operators

There are following relational operators supported by C++ language
Assume variable A holds 10 and variable B holds 20, then:
Operator
Description
Example
==
Checks if the values of two operands are equal or not, if yes then condition becomes true.
(A == B) is not true.
!=
Checks if the values of two operands are equal or not, if values are not equal then condition becomes true.
(A != B) is true.
> 
Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true.
(A > B) is not true.
< 
Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true.
(A < B) is true.
>=
Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true.
(A >= B) is not true.
<=
Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true.
(A <= B) is true.

 Component Selection Operators

.  (dot)
Direct component selector
-> (arrow)
Indirect component selector

Class member operations

::
Scope access/resolution
.*
Deference pointer to class member
à*
Deference pointer to class member

Conditional Operators

?
:

Operators Precedence in C++

Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator:
For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence than +, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first.
Category
Operator
Associativity
Postfix
() [] -> . ++ - -
Left to right
Unary
+ - ! ~ ++ - - (type)* & sizeof
Right to left
Multiplicative
* / %
Left to right
Additive
+ -
Left to right
Shift
<< >>
Left to right
Relational
< <= > >=
Left to right
Equality
== !=
Left to right
Bitwise AND
&
Left to right
Bitwise XOR
^
Left to right
Bitwise OR
|
Left to right
Logical AND
&&
Left to right
Logical OR
||
Left to right
Conditional
?:
Right to left
Assignment
= += -= *= /= %=>>= <<= &= ^= |=
Right to left
Comma
,
Left to right

A First Look at C++ Program

//My first C++ program
#include<iostream.h>
int main()
{
     cout<<”Welcome to C++ Programming�?;
     return 0;
}
The above program produces the following output:
Welcome to C++ Programming
This is a simplest program that can be written in C++, but include the basic elements that every C++ program has.
//My first C++ program
This is a comment.Program comments are explanatory statements that you can include in the C++ code. These comments help anyone reading the source code. All programming languages allow for some form of comments. C++ supports single-line and multi-line comments. All characters available inside any comment are ignored by C++ compiler.
#include<iostream.h>
Statements that begin with # sign �? are directives for the pre-processor. The  pre-processors  are  the  directives,  which  give  instructions  to  the  compiler  to pre-process the information before actual compilation starts. This macro is used to include a header file into the source file.
int main()
This line indicates the beginning of main function. The main() function is the point by where all C++ programs begin their execution. Infact, the content of main() is always the first to be executed when a program starts. And for the same reason, it is essential that all C++ programs have a main()function.
Every function in C++ has its code included in a pair of curly braces ({}) so that code below line int main() inside { and } is code of function main().
cout<<”Welcome to C++ Programming�?;
The coutis the standard output stream in C++ and the above statement inserts a sequence of characters �? �?Welcome to C++ Programming�? here - into this output stream. Since cout is declared in header file iostream.h, so in order to use cout in the program, we have included this very header file with #include directive.

Notice this statement ends with a semicolon character (;). The semicolon (;) character is used to finish every executable instruction.

Why include iostream.h?

The header file iostream.h (all header files end with .h) is included in every C++ program to implement input/output facilities. Input/Output facilities are not defined within C++ language, but rather are implemented through a component of C++ standard library, iostream.hwhich, is I/O library.
In C++, all devices are treated as files. Thus, the standard input device (the keyboard) (where from the input is received), the standard output device(the screen/monitor) (where the output is displayed) and the standard error device (the screen/monitor) (where the errors, if any, are displayed) are all treated as files. At its lowest level, a file is interpreted simply as a sequence, or streamof bytes. At this level, the notion of a data type is absent i.e., data is treated simply as sequence of bytes without considering its data type. However, at the user level, a file consists of a sequence of possibly intermixed data types-characters, arithmetic values, class objects etc.

Predefined Streams in I/O Library

Input and output operations are supported by the istream(input stream) and ostream(output stream) classes.
The predefined stream objects for input, output and error are as follows:
  1. cin, as istream class object tied to standard input. cin stands for console input.
  2. cout, an ostream class object tied to standard output. cout stands for console ouput.
  3. cerr, an ostream class object tied to standard error. cerr stands for console error.
Declarations and functions of cin, cout and cerr are contained within iostream.h

Comments in a C++ Program

Program comments are explanatory statements that you can include in the C++ code. These comments help anyone reading the source code. All programming languages allow for some form of comments.
C++ supports single-line and multi-line comments. All characters available inside any comment are ignored by C++ compiler. C++ comments start with /* and end with */. For example:
/* This is a comment */
/* C++ comments can also
* span multiple lines
*/
A comment can also start with //, extending to the end of the line. For example:
#include <iostream>
using namespace std;
main()
{
cout << "Hello World"; // prints Hello World
return 0;
}
When the above code is compiled, it will ignore // prints Hello World and final executable will produce the following result:
Hello World
Within a /* and */ comment, // characters have no special meaning. Within a // comment, /* and */ have no special meaning. Thus, you can "nest" one kind of comment within the other kind. For example:
/* Comment out printing of Hello World:
cout << "Hello World"; // prints Hello World
*/

Using I/O Operators

Output Operator �?<<�?

The cout is used in conjunction with the stream insertion operator, which is written as << which are two less than signs as shown in the following example.
#include <iostream>
using namespace std;
int main( )
{
char str[] = "Hello C++";
cout << "Value of str is : " << str << endl;
}
When the above code is compiled and executed, it produces the following result:
Value of str is : Hello C++
The C++ compiler also determines the data type of variable to be output and selects the appropriate stream insertion operator to display the value. The << operator is overloaded to output data items of built-in types integer, float, double, strings and pointer values.
The insertion operator << may be used more than once in a single statement as shown above and endl is used to add a new-line at the end of the line.

Input Operator �?>>�?

The cin is used in conjunction with the stream extraction operator, which is written as >> which are two greater than signs as shown in the following example.
#include <iostream>
using namespace std;
int main( )
{
char name[50];
cout << "Please enter your name: ";
cin >> name;
cout << "Your name is: " << name << endl;
}
When the above code is compiled and executed, it will prompt you to enter a name. You enter a value and then hit enter to see the following result:
Please enter your name: cplusplus
Your name is: cplusplus
The C++ compiler also determines the data type of the entered value and selects the appropriate stream extraction operator to extract the value and store it in the given variables.
The stream extraction operator >> may be used more than once in a single statement. To request more than one data you can use the following:
cin >> name >> age;
This will be equivalent to the following two statements:
cin >> name;

cin >> age;

No comments:

Post a Comment

How do I crack the GSOC in the field of machine learning?

How do I crack the GSOC in the field of machine learning? Working as a student at Google Summer of Code demands for your dedication an...