Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
The object cout has a simple interface, if string represents a string variable, then the following statement
will display its contents.
cout<< string;
We may recall the the operator << is bitwise left shift operator and it can still be used for this purpose.
This is an example of how one operator can be used for different purposes,depending on the contexts.
This is known as operator overloading, an important aspects of polymorphism.
1
B.Sc II Semester: PROGRAMMING IN C++
UNIT-I
Input operator:
The operator >> is known as extraction or get from operator. It extracts (or takes) the value from the
keyboard and assigns it to the variable on its right.
This corresponds to the familiar scanf() operation. Like <<, the operator >> can also be overloaded.
2
B.Sc II Semester: PROGRAMMING IN C++
UNIT-I
Structure of C++ program
C++ Programming language is most popular language after C Programming language. C++ is first
Object oriented programming language. We have summarize structure of C++ Program in the following
figure:
Section 1: Header File Declaration Section
Header files used in the program are listed here.
Header File provides Prototype declaration for different library functions.
We can also include user define header file.
Basically all preprocessor directives are written in this section.
Section 2: Global Declaration Section
Global Variables are declared here.
Global Declaration may include –
Declaring Structure
Declaring Class
Declaring Variable
Section 3: Class Declaration Section
Actually this section can be considered as sub section for the global declaration section.
Class declaration and all methods of that class are defined here.
Section 4: Main Function
Each and every C++ program always starts with main function.
This is entry point for all the function. Each and every method is called indirectly through main.
We can create class objects in the main.
Operating system call this function automatically.
Section 5: Method Definition Section
This is optional section. Generally this method was used in C Programming.
3
B.Sc II Semester: PROGRAMMING IN C++
UNIT-I
Tokens:
The smallest individual units in a program are known as tokens. C++ has the following tokens:
Keywords
Identifiers
Constants
Strings
Operators
A C++ program is written using these tokens, white spaces, and the syntax of the language.
Keywords:
The keywords implement specific C++ language features. They are explicitly reserved identifiers and
cannot be used as names for the program variables or other user defined program elements
The following table gives the complete set of C++ keywords. Many of them are commonm to both C
and C++
The ANSI C keywords are shown in boldface. Additional keywords have been added to the ANSI C
keywords in order to enhance its features and make it an object- oriented language. ANSI C++ standards
committee has added some more keywords to make the language more versatile.
Identifiers:
Identifiers refer to the names of the variables, functions, arrays, classes etc. created by the programmer.
They are the fundamental requirement of any language. Each lanuage has its own rules for naimg these
identifiers. The following rules are common to both C and C++:
4
B.Sc II Semester: PROGRAMMING IN C++
UNIT-I
Constants:
Constants (often referred to as literals) are data items that never change their value during the execution
of the program. The following types of literals are available in C++.
Integer-Constants
Character-constants
Floating-constants
Strings-constants
Integer Constants
Integer constants are whole number without any fractional part. C++ allows three types of integer
constants.
Decimal integer constants : It consists of sequence of digits and should not begin with 0 (zero). For
example 124, - 179, +108.
Octal integer constants: It consists of sequence of digits starting with 0 (zero). For example. 014, 012.
Character constants
A character constant in C++ must contain one or more characters and must be enclosed in single
quotation marks. For example 'A', '9', etc. C++ allows nongraphic characters which cannot be typed
directly from keyboard, e.g., backspace, tab, carriage return etc. These characters can be represented by
using an escape sequence. An escape sequence represents a single character.
Floating constants
They are also called real constants. They are numbers having fractional parts. They may be written in
fractional form or exponent form. A real constant in fractional form consists of signed or unsigned digits
including a decimal point between digits. For example 3.0, -17.0, -0.627 etc.
String Literals
A sequence of character enclosed within double quotes is called a string literal. String literal is by
default (automatically) added with a special character „\0' which denotes the end of the string. Therefore
the size of the string is increased by one character. For example "COMPUTER" will re-represented as
"COMPUTER\0" in the memory and its size is 9 characters.
5
B.Sc II Semester: PROGRAMMING IN C++
UNIT-I
Basic data types:
Data types in C++ can be classified under various categories as shown in figure:
Both C and C++ compilers support all the built-in (also known as basic or fundamental) data types. With
the exception of void, the basic data types may have several modifiers preceding them to serve the needs
of various situations. The modifiers signed, unsigned, long, and short may be applied to character and
integer basic data types. However, the modifier long may also be applied to double. The following table
lists all combination of the basic data types and modifiers along with their size and range for a 16 bit
word machine
6
B.Sc II Semester: PROGRAMMING IN C++
UNIT-I
Functions:
Functions have undergone major changes in C++. While some of these are simple, other require a new
way of thinking when organizing our programs. Many of these modifications and improvements were
driven by requirements of object oriented concept of C++.
7
B.Sc II Semester: PROGRAMMING IN C++
UNIT-I
We have used user defined data types such as struct and union in C. while these data types are legal in
C++, some more features have been added to make them suitable for object oriented programming. C++
also permits us to define user –defined data type known as class which can be used, just like any other
basic data type, to declare variables. The class variables are also known as objects, which are the central;
focus of object- oriented programming.
8
B.Sc II Semester: PROGRAMMING IN C++
UNIT-I
Variable
Variable is a location in the computer memory which can store data and is given a symbolic name for
easy reference. The variables can be used to hold different values at different times during the execution
of a program.
Declaration of a variable
Before a variable is used in a program, we must declare it. This activity enables the compiler to make
available the appropriate type of location in the memory.
float total;
You can declare more than one variable of same type in a single statement
int x, y;
Dynamic Initialization of variable
When we declare a variable it's default value is undetermined. We can declare a variable with some
initial value.
int a = 20;
5. Operators
Operators are special symbols used for specific purposes. C++ provides six types of operators.
Arithmetical operators,
Relational operators,
Logical operators,
Unary operators,
Assignment operators,
Conditional operators,
Comma operator.
Arithmetical operators
Arithmetical operators +, -, *, /, and % are used to performs an arithmetic (numeric) operation.
Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
You can use the operators +, -, *, and / with both integral and floating-point data types. Modulus or
remainder % operator is used only with the integral data type.
Binary operators
9
B.Sc II Semester: PROGRAMMING IN C++
UNIT-I
Operators that have two operands are called binary operators.
Unary operators
C++ provides two unary operators for which only one variable is required.
For Example
a = - 50;
a = + 50;
Here plus sign (+) and minus sign (-) are unary because they are not used between two variables.
Relational operators
The relational operators are used to test the relation between two values. All relational operators are
binary operators and therefore require two operands. A relational expression returns zero when the
relation is false and a non-zero when it is true. The following table shows the relational operators.
Relational Operators Meaning
== Equal to
!= Not equal to
Logical operators
The logical operators are used to combine one or more relational expression. The logical operators are
Operators Meaning
|| OR
&& AND
! NOT
Assignment operator
The assignment operator '=' is used for assigning a variable to a value. This operator takes the expression
on its right-hand-side and places it into the variable on its left-hand-side. For example:
m = 5;
The operator takes the expression on the right, 5, and stores it in the variable on the left, m.
x = y = z = 32;
This code stores the value 32 in each of the three variables x, y, and z.
10
B.Sc II Semester: PROGRAMMING IN C++
UNIT-I
In addition to standard assignment operator shown above, C++ also support compound assignment
operators.
+= A+=2 A=A+2
-= A-=2 A=A-2
%= A%=2 A=A%2
/= A/ = 2 A=A/2
*= A*=2 A=A*2
Increment and Decrement Operators:
C++ provides two special operators viz '++' and '--' for incrementing and decrementing the value of a
variable by 1. The increment/decrement operator can be used with any type of variable but it cannot be
used with any constant. Increment and decrement operators each have two forms, pre and post.
The syntax of the increment operator is:
Pre-increment: ++variable
Post-increment: variable++
The syntax of the decrement operator is:
Pre-decrement: ––variable
Post-decrement: variable––
In Prefix form first variable is first incremented/decremented, and then evaluated
In Postfix form first variable is first evaluated, then incremented/decremented
int x, y;
inti = 10, j = 10;
x = ++i; //add one to i, store the result back in x
y =j++; //store the value of j to y then add one to j
cout<< x; //11
cout<< y; //10
Conditional operator
The conditional operator ?: is called ternary operator as it requires three operands. The format of the
conditional operator is:
Conditional_ expression ? expression1 : expression2;
If the value of conditional expression is true then the expression1 is evaluated, otherwise expression2 is
evaluated.
int a = 5, b = 6;
big = (a> b) ?a : b;
11
B.Sc II Semester: PROGRAMMING IN C++
UNIT-I
The condition evaluates to false, therefore big gets the value from b and it becomes 6.
The comma operator gives left to right evaluation of expressions. When the set of expressions has to be
evaluated for a value, only the rightmost expression is considered.
int a = 1, b = 2, c = 3,i; // comma acts as separator, not as an operator
i = (a, b); // stores b into i
Would first assign the value of a to i, and then assign value of b to variable i. So, at the end,
variable i would contain the value 2.
As we know that different types of Variables, constant, etc. require different amounts of memory to
store them Thesizeof operator can be used to find how many bytes are required for an object to store in
memory. For example
The sizeof operator determines the amount of memory required for an object at compile time rather than
at run time.
12
B.Sc II Semester: PROGRAMMING IN C++
UNIT-I
Scope Resolution operator:
13
B.Sc II Semester: PROGRAMMING IN C++
UNIT-I
14
B.Sc II Semester: PROGRAMMING IN C++
UNIT-I
Manipulators:
15
B.Sc II Semester: PROGRAMMING IN C++
UNIT-I
Type Cast Operator:
16
B.Sc II Semester: PROGRAMMING IN C++
UNIT-I
17
B.Sc II Semester: PROGRAMMING IN C++
UNIT-I
Operator Precedence:
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
18
B.Sc II Semester: PROGRAMMING IN C++
UNIT-I
Control Flow:
Statements:
Statements are the instructions given to the computer to perform any kind of action. Action may be in
the form of data movement, decision making etc. Statements form the smallest executable unit within a
C++ program. Statements are always terminated by semicolon.
Compound Statement or Block statement:
A compound statement is a grouping of statements in which each individual statement ends with a semi-
colon. The group of statements is called block. Compound statements are enclosed between the pair of
braces ({}.). The opening brace ({) signifies the beginning and closing brace (}) signifies the end of the
block.
Conditional Statements or branching statements:
Sometimes the program needs to be executed depending upon a particular condition. C++ provides the
following statements for implementing the selection control structure.
if statement
if else statement
nested if statement
switch statement
if statement:
syntax of the if statement
if (condition)
{
statement(s);
}
From the flowchart it is clear that if the if condition is true, statement is executed; otherwise it is
skipped.
The statement may either be a single or compound statement.
19
B.Sc II Semester: PROGRAMMING IN C++
UNIT-I
if else statement:
syntax of the if - else statement
if (condition)
statement1;
else
statement2;
From the above flowchart it is clear that the given condition is evaluated first. If the condition is true,
statement1 is executed. If the condition is false, statement2 is executed. It should be kept in mind that
statement and statement2 can be single or compound statement.
if example if else example
if (x == 100) if (x == 100)
cout<< "x is 100"; cout<< "x is 100";
else
cout<< "x is not 100";
Nested if statement
The if block may be nested in another if or else block. This is called nesting of if or else block.
syntax of the nested if statement
if(condition 1) if(condition 1)
{ statement 1;
else if (condition 2)
if(condition 2) statement2;
{ else
statement(s); statement3;
}
}
if-else-if example
20
B.Sc II Semester: PROGRAMMING IN C++
UNIT-I
if(percentage>=60)
cout<<"Ist division";
else if(percentage>=50)
cout<<"IInd division";
else if(percentage>=40)
cout<<"IIIrd division";
else
cout<<"Fail" ;
switch statement:
The if and if-else statements permit two way branching whereas switch statement permits multiple
branching. The syntax of switch statement is:
switch (var / expression)
{
case constant1 : statement 1;
break;
case constant2 : statement2;
break;
.
.
default: statement3;
break;
}
The execution of switch statement begins with the evaluation of expression. If the value of expression
matches with the constant then the statements following this statement execute sequentially till it
executes break. The break statement transfers control to the end of the switch statement. If the value of
expression does not match with any constant, the statement with default is executed.
Some important points about switch statement
The expression of switch statement must be of type integer or character type.
The default case need not to be used at last case. It can be placed at any place.
The case values need not to be in specific order.
Looping statement:
It is also called a Repetitive control structure. Sometimes we require a set of statements to be executed a
number of times by changing the value of one or more variables each time to obtain a different result.
This type of program execution is called looping. C++ provides the following construct
while loop
do-while loop
for loop
While loop:
Syntax of while loop
while(condition)
{
21
B.Sc II Semester: PROGRAMMING IN C++
UNIT-I
statement(s);
}
The flow diagram indicates that a condition is first evaluated. If the condition is true, the loop body is
executed and the condition is re-evaluated. Hence, the loop body is executed repeatedly as long as the
condition remains true. As soon as the condition becomes false, it comes out of the loop and goes to the
statement next to the „while‟ loop.
do-while loop
Syntax of do-while loop
do
{
statements;
} while (condition);
Note : That the loop body is always executed at least once. One important difference between the while
loop and the do-while loop the relative ordering of the conditional test and loop body execution. In the
while loop, the loop repetition test is performed before each execution the loop body; the loop body is
not executed at all if the initial test fail. In the do-while loop, the loop termination test is performed after
each execution of the loop body. Hence, the loop body is always executed least once.
for loop:
22
B.Sc II Semester: PROGRAMMING IN C++
UNIT-I
It is a count controlled loop in the sense that the program knows in advance how many times the loop is
to be executed.
syntax of for loop
23
B.Sc II Semester: PROGRAMMING IN C++
UNIT-I
Initialization of One Dimensional Array
An array can be initialized along with declaration. For array initialization it is required to place the elements
separated by commas enclosed within braces.
int A[5] = {11,2,23,4,15};
It is possible to leave the array size open. The compiler will count the array size.
int B[] = {6,7,8,9,15,12};
#include<iostream.h>
Intmain()
{
intnewArray[10];
int n =0;// Initializing elements of array seperately
for(n=0;n<sizeof(newArray);n++)
{
newArray[n]= n;
}
int a =newArray[5];// Assigning 5th element of array value to integer 'a'.
cout<<”a=”<<a;
}
It is a collection of data elements of same data type arranged in rows and columns (that is, in two
dimensions).
Type arrayName[numberOfRows][numberOfColumn];
For example,
int Sales[3][5];
24
B.Sc II Semester: PROGRAMMING IN C++
UNIT-I
name[rowIndex][columnIndex]
Examples:
cout<<A[1][2]; //print an array element
A[1][2]=13; // assign value to an array element
cin>>A[1][2]; //input element
Using Loop to input an Two-Dimensional Array from user
int mat[3][5], row, col ;
for (row = 0; row < 3; row++)
for (col = 0; col < 5; col++)
cin>> mat[row][col];
STRINGs:
The number of elements that can be stored in a string is always n-1, if the size of the array specified is n.
This is because 1 byte is reserved for the NULL character '\0' i.e. backslash zero. A string is always
terminated with the NULL character.
Example:
char str[80];
In the above example, str can be used to store a string with 79 characters.
Initializing a string
A string can be initialized to a constant value when it is declared.
25
B.Sc II Semester: PROGRAMMING IN C++
UNIT-I
charstr[ ] = "Good";
Or
char str[]={'G','o','o','d','\0'};
Here. 'G' will be stored in str[0], 'o' in str[1] and so on.
Note: When the value is assigned to the complete string at once, the computer automatically inserts the
NULL character at the end of the string. But, if it is done character by character, then we have to insert it
at the end of the string.
Reading strings with/without embedded blanks
To read a string without blanks cin can be used
cin>>str;
To read a string with blanks cin.getline() or gets() can be used.
cin.getline(str,80);
-Or-
gets(str);
Printing strings
cout and puts() can be used to print a string.
cout<<str:
Or
puts(str);
Note: For gets( ) and puts(), the header file <cstdio> (formally stdio.h) has to be included. puts() can be
used to display only strings. It takes a line feed after printing the string.
cin gets()
It can be used to take input of a value It can be used to take input of a string.
of any data type.
It takes the white space i.e. a blank, a It does not take the white space i.e. a
tab, or a new line character as a string blank, a tab, or a new line character, as
terminator. a string terminator.
Example: Example:
char S[80]; char S[80];
cout<< "Enter a string:”; cout<< "Enter a string:";
cin>>S; gets(S);
26
B.Sc II Semester: PROGRAMMING IN C++
UNIT-I
cout puts()
It can be used to display the value of It can be used to display the value of a
any data type. string.
It does not take a line feed after It takes a line feed after displaying the
displaying the string. string.
It requires the header file iostream.h It requires the header file stdio.h
Example: Example:
char S[80] = "Computers"; char S[80] = "Computers";
cout<<S<<S; puts(S);
puts(S);
Output:
Computers Computers Output:
Computers
Computers
Strlen() –
The C library function size_tstrlen(const char *str) computes the length of the string str up to, but not
including the terminating null character.
Declaration
Following is the declaration for strlen() function.
size_tstrlen(constchar*str)
Parameters
str -- This is the string whose length is to be found.
Return Value
This function returns the length of string.
27
B.Sc II Semester: PROGRAMMING IN C++
UNIT-I
Example
The following example shows the usage of strlen() function.
#include<stdio.h>
#include<string.h>
int main ()
{
charstr[50];
intlen;
strcpy(str,"This is tutorialspoint.com");
len=strlen(str);
printf("Length of |%s| is |%d|\n",str,len);
return(0);
}
Out put:
Strcpy() –
The C library function
char *strcpy(char *dest, const char *src) copies the string pointed to, by src to dest.
Declaration
Following is the declaration for strcpy() function.
char*strcpy(char*dest,constchar*src);
Parameters
dest -- This is the pointer to the destination array where the content is to be copied.
src -- This is the string to be copied.
Return Value
This returns a pointer to the destination string dest.
Example
The following example shows the usage of strcpy() function.
#include<stdio.h>
#include<string.h>
int main()
{
charsrc[40];
chardest[100];
memset(dest,'\0',sizeof(dest));
strcpy(src,"bvc");
strcpy(dest,src);
printf("Final copied string : %s\n",dest);
return(0);
}
28
B.Sc II Semester: PROGRAMMING IN C++
UNIT-I
Let us compile and run the above program that will produce the following result:
Final copied string :bvc
Strrev() –
This function gives the output in reverse order . This function accept one argument . then entered
string Is revered as output. For exp: if we enter “program” string as input then the output becomes
“Morgorph”.
#include<iostream.h>
#include<conio.h>
#include<string.h>
void main()
{
clrscr();
char a[20];
cout<<”enter string ”<<endl;
cin>>a;
strrev(a);
cout<< reversed string :”<<a;
getch();
}
Output of program
Enter a string bvc
Reversed string :cvb
Explanation: strrev() function will reverse the strings which is entered in it . the string to be reversed
entered into program it will process and produce output string in reverse order.
Strlwr() –
function will change uppercase letters in lowercase letter . strlwr() also accept only one argument.
Similarly to convert lowercase letters into uppercase strupr function is used which will convert all
lowercase letters into uppercase.
#include<iostream.h>
#include<conio.h>
#include<string.h>
void main()
{
clrscr();
char a[20];
cout<<”enter string ”<<endl;
cin>>a;
strlwr(a); // strupr(a) for uppercase letter as output
cout<< string in lower case letters :”<<a;
getch();
}
29
B.Sc II Semester: PROGRAMMING IN C++
UNIT-I
Output:
Enter a string: BVC
String in lower case letters bvc
Strcmp()
Description
The C library function intstrcmp(const char *str1, const char *str2)compares the string pointed to,
by str1 to the string pointed to by str2.
Declaration
Following is the declaration for strcmp() function.
intstrcmp(constchar*str1,constchar*str2)
Parameters
str1 -- This is the first string to be compared.
str2 -- This is the second string to be compared.
Return Value
This function return values that are as follows:
if Return value < 0 then it indicates str1 is less than str2.
if Return value > 0 then it indicates str2 is less than str1.
if Return value = 0 then it indicates str1 is equal to str2.
Example
The following example shows the usage of strncmp() function.
#include<stdio.h>
#include<string.h>
int main ()
{
char str1[15];
char str2[15];
int ret;
strcpy(str1,"abcdef");
strcpy(str2,"ABCDEF");
ret=strcmp(str1, str2);
if(ret <0)
{
printf("str1 is less than str2");
}
elseif(ret >0)
{
printf("str2 is less than str1");
}
else
{
printf("str1 is equal to str2");
}
return(0);
}
30