0% found this document useful (0 votes)
23 views

Beginning with C++

Uploaded by

Mahima
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

Beginning with C++

Uploaded by

Mahima
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 86

BEGINNING WITH

C++
Tokens,Expressions & Control Statements
Sample C++ program- Display
“Hello World!”
#include<iostream> // include header file
Using namespace std;
int main()
{
cout<<“Hello World! \n”; //C++ statement
return 0;
} //end of program
Description
■ Program execution begins at main().
■ Every C++ program must have a main().
■ C++ is a free- form language.
■ Like C, the C++ statements terminate with semicolons.
■ Comments:may start anywhere in the line,are ignored by the compiler, just for description
purposes.
– Single –line: use // (double slash)
– Multi – line: use /*..*/ (as used in C)
– For(j=0;j<n;/* loop n times*/j++) will throw an error.
■ Identifier cout is a predefined object that represents the standard output stream in C+
+. Here, the standard output steam represents the screen.
■ Output Operator(<<):inserts(or sends) the content of its variable on the right to the
object on its left.
■ Include iostream file:should be included at the beginning of all programs that use
input/output statements(it’s a preprocessor directive that contains declarations for the
identifier count and the operator <<).
■ Namespace:std is the namespace where standard class libraries are defined.
■ Input Operator(>>):causes the program to wait for the user to type in a number.
■ Identifier cin is a predefined object in C++ that corresponds to the standard input
stream.it extracts the value from the keyboard and assigns it to the variable on its right.
More Programs

■ C++ "Hello, World!" Program


■ C++ Program to Print Number Entered by User
■ C++ Program to Add Two Numbers
■ C++ Program to Swap Two Numbers(with & without
temporary variable)
■ C++ Program to Find Quotient and Remainder
Cascading of I/O Operators
■ Cout<<“sum=”<<sum<<“\n”;

■ The multiple use of << in one statement is called cascading.


■ We can also cascade input operator >>
■ Cin>> num1>>num2;
■ The values are assigned from left to right.
Structure of C++ Program
TOKENS
 The Smallest Individual Units in a program are known as
token.
 C++ has following tokens:
 Keywords
 Identifiers
 Constants
 Strings
 Operators
KEYWORDS
 Keywords are reserved words in programming .
 Each keyword has fixed meaning and that can not be

changed by user.
 Cannot be used as names for the program variables or other

user-defined program elements.


 For Ex:

int num1; where int is keyword indicates num1


is integer type.
asm double new switch
auto else operator template
break enum private this
case extern protected throw
catch float public try
char for register typedef
class friend return union
const goto short unsigned
continue if signed virtual
default inline sizeof void
delete int static volatile
do long struct while
bool export reinterpret_cast typename
const_cast false static_cast using
dynamic_cast mutable true wchar_t
explicit namespace typeid
IDENTIFIERS AND

CONSTANTS
Identifiers refer to the names of variables, functions,arrays,
classes,etc. created by the programmer.
 They are the fundamental requirement of any language.

 Each language has its own rules for naming these identifiers.For C+

+,these are as follows( same as C):


 Only alphabetic characters,digits and underscores are
permitted.
 The name can not start with digits.
 Uppercase and lowercase letters are distinct.
 A declared keyword cannot be used as a variable name.
 Constants refers to fixed values that do not change during the
execution of program.
 They include integer,character,floating point numbers

and strings.

 Examples: 123, 12.34, “C++”etc


C++ DATA
TYPES

 C++ data types divided mainly in three categories


as follows:

 Built- in data types


 User defined data types
 Derived data types
BASIC TYPES BYTES RANGE
DATA char 1 -128 to 127
unsigned char 1 0 to 255
TYPES
signed char 1 -128 to 127
int 2 -32768 to 32767
unsigned int 2 0 to 65535
signed int 2 -32768 to 32767
short int 2 -32768 to 32767
unsigned short int 2 0 to 65535
signed short int 2 -32768 to 32767
long int 4 -2147483648 to 2147483647

signed long int 4 -2147483648 to 2147483647

unsigned long int 4 0 to 4294967295


float 8 3.4E-38 to 3.4E_38
double 10 1.7E-308 to 1.7E+308
long double 3.4E-4932 to 1.1E+4932
■Uses of void :
■ 1) to specify the return type of a function when it is not returning any
value
■ 2) to indicate any empty argument list to a function
– Example: void func( void);
■ 3) to declare generic pointers
– Example: void *gp;
– A generic pointer can be assigned a pointer value of any basic
data type.
– Example: int *ip;
Gp=ip; is valid
But *gp=*ip; is not valid.
16

USER-DEFINED DATA
TYPES
There are following user defined data types:
 struct

 union

enum

class
STRUCT:
 A structure is a collection of simple variable
 The variable in a structure can be of different type such as

int,char,float,char,etc.
 This is unlike the array which has all variables of same data type

 The data items in a structure is called the member of structure.

 Syntax:

struct structure_name{ declaration of data


member;
};

You can access data member of stucture by using only structure
variable with dot operator.
PROGRAMME OF STRUCTURE
#include<iostream>
using namespace std;

struct student{
int Roll_No;
char name[15];
int cPlus,maths,sql,dfs,total;
float per;
};
int main()
{
struct student s;
cout<<"Enter Roll No:";
cin>>s.Roll_No;
cout<<"Enter Name:";
cin>>s.name;
cout<<"Enter Marks For CPlus:";
cin>>s.cPlus;
cout<<"Enter Marks For Maths:";
cin>>s.maths;
cout<<"Enter Marks For Sql :";
cin>>s.sql;
cout<<"Enter Marks For DFS:"; cin>>s.dfs;
s.total=s.cPlus+s.maths+s.sql+s.dfs;
s.per=s.total/4;

cout<<"Your Roll No is:"<<s.Roll_No<<"\n";


cout<<"Your Name is:"<<s.name<<"\n";
cout<<"Your Total is:"<<s.total<<"\n";
cout<<"Your Percentage is:"<<s.per<<"%"<<"\n";
return 0;
}
UNION
 Union is also like a structure means union is also used to storing
different data types ,but the difference between structure and union
is that structure consume the memory of addition of all
elements of different data types but a union consume the
memory that is highest among all elements.

 It consume memory of highest variable and it will share the data


among all other variable.
 For example:
If a union contains variable like int, char,float then the
memory will be consume of float variable because float is
highest among all variable of data type.

 Syntax:
union union_name //union declaration
{
data_type member1;
data_type
member2;

};
 Like ,
union
stu{ int //occupies 2 bytes
roll_no; //occupies 1 bytes
char grade ;
};
roll_no

Byte 0 Byte 1

grade

Memory representation in union


STRUCTURE UNION

 Define with ‘struct’ keyword.  Define with ’union’ keyword.

 All member can be manipulated


 Member can be manipulated
simultaneosly. one at a time.

 The size of object is equal to


 The size of object is equal to
the sum of individual size of the the size of largest member
member object. object.

 Members are allocated distinct


 Members are share common
memory space.
memory location.
ENUM IN C+
+
 An enumeration type is user defined type that enable

the user to define the range of values for the type.


 Syntax:
enum [enum-type] { enum-list};

 Name constants are used to represent the value of an


enumeration for example:
enum char{a,b,c};

 The default value assigned to the enumeration


constant are zero-based so in above example a=0,b=1
and so on.
 The user also can assign value to one or more
enumeration constant,and subsequent values that
are not assigned will be incremented.

For example :
enum char{a=3,b=7,c,d};
here, value of c is 8 and d is 9.
PROGRAMME FOR ENUM TYPE

#include<iostream>
using namespace std;

int main()
{
enum
Fruits{apple,orange,g
uava,pinapple};

Fruits myfruit;
int i;
cout<<"Enter your choice:";
cin>>i;
switch(
i)
{ case apple:
cout<<"Your first fruit is Apple.";
break;
case orange:
cout<<"Your second fruit is Orange.";
break;
case guava:
cout<<"Your third fruit is Guava.";
break;
case pinapple:
cout<<"Your forth fruit is Pinapple.";
break;

}
return 0;
}
CLASS
 The class type enables us to create sophisticated user defined type.
 We provide data items for the class and the operation that can be

performed on the data.


 Syntax:

class class_name{
data member variables;
data member methods/functions;
};
CLASS PROGRAMME
#include<iostream>
using namespace std;

class piramid
{
int i,n,j;
public:
void getdata();
void buildpiramid();

};
void
piramid::getdata()
{
cout<<"enter N:";
cin>>n;
}
void
piramid::buildpiramid()
{
for(i=1;i<=n;i++)
{
for(j=1;j<=i;j++)
{
cout<<"*";
}
cout<<"\n";
}
}
int main()
{
piramid p;
p.getdata();
p.buildpiramid();

return 0;
}
DERIVED DATA TYPE

 The derived data type are:


 array
 function
 pointer
ARRAY
 An array is a series of elements of the same data
type placed in contiguous memory location.
 Like regular variable ,an array must be declare

before it is used.
 Syntax:

data_type name[size];

 Ex:
char name[10];
int student[10];
FUNCTION

 A function is a group of statement that together


perform a task.

 Every c++ program has at least one function that


is main() and programmer can define additional
function.

 You must define function prototype before use


them.

 A function prototype tells compiler the name of the


function ,return type, and parameters.
 Syntax:
return_type function_name(parameter_list);

 Ex:
int max(int n1,int n2);
FUNCTION PROGRAM
#include<iostream
> using
namespace
int std;n2);
max(int n1,int \\declaration

int main()
{
int n1;
int
n2;
int a;
cout<<"Enter Number1: "<<"\n";
cin>>n1;
cout<<"Enter Number2: "<<"\n";
cin>>n2;
\\calling function
a=max(n1,n2);

cout<<"max value is "<<a<<"\


n";
int max(int n1,int n2)
{
int result;
if(n1>n2)
result=n1;
else
result=n2;

return
result;
}
POINTER
 Pointer is basically the same as any other
variable,difference about them is that instead of
containing actual data they contain a pointer to
the memory location where information can be
found.
 Basically, pointer is variable whose value is address

of another variable.
 Syntax:

type *var_name;
 Ex:

int *p;
 There are few operation which will do frequently
with pointer is:
I. We define a pointer variable.
II. Assign address of variable to a pointer and
III. Finally access the value at the address available in
the pointer variable.
 Like,

I. int var=20;
II. p =&var;
III. int *p;
POINTER PROGRAM

#include<iostream>
using namespace std;

int main()
{
int var=34;
int *p;
p=&var;

cout<<"Value of Var variable is "<<var<<"\n";


cout<<"Address stored in variable is "<<p<<"\
n"; cout<<"Value of P Variable is "<<*p<<"\n";
return 0;
}
SYMBOLIC CONSTANT TYPE
 Constant is an identifier with associated value
which can not be altered by the program during
execution.

 You must initialize a constant when you craete


it,you can not assign new value later after constant
is initialized.

 Symbolic constant is a constant that is


represented by name.
 Defining constant with ’
 #define’. Defining constant with
 ’const’.
Defining constant with ’enum’.
 Ex:

#define pi 3.14

const max=10;

enum char{a,b,c};
TYPE COMPATIBILITY

The sizeof is a keyword but it is compile
time operator that determine the size, in byte,
of a variable or data type.
 It can be used to get the size of classes, structure,

union and any other user defined data type.


 Syntax:

sizeof(data_type)

 Ex:
sizeof(x) or sizeof(int)
 sizeof operater will return integer value.
PROGRAM: USE OF SIZEOF OPERATOR
#include<iostream>
using namespace std;

int main()
{
int a,x;
char
b;
float c=10.02;
double d;
cout<<"size of a:"<<sizeof(a)*sizeof(x)<<"\n"; \*nested sizeof *\
cout<<"size of b:"<<sizeof(b)<<"\n";
cout<<"size of c:"<<sizeof(10.02)<<"\n";
cout<<"size of d:"<<sizeof(d)<<"\n";
return 0;
}
VARABLE IN C+
+
 Variable is a place to store information.
 A variable is a location in your computer’s memory

in which you can store a value and from which


you can later retrive the value.
 This is temporary storage,when you turn the

computer off these variable are lost.


 Like c, in c++ all variable must be declare before

we used it.
 The diiference is that in c, it requires to be defined

at the beginning of a scope,rather c++ allow you to


declaration of variable anywhere in the scope.
 This means that a variable can be declared right at
the place of its first use.
 Declaration Of variable:

char name[12];
int a;
float num;

If you are going to declare more than one
variable having same data type, you can declare
all of them in single statement by separating their
identifiers with commas.
 For ex:

int a,b,c;
 At the other-end you can assign value to the variable
when you declare them its called initialization.

 Ex:
int a=0;
char name[]={‘h’,’e’,’l’,’l’,’o’};
char name[8]=‘computer’
 Dynamic initialization:
The additional feature of c++ is ,to initialize the
variable at run time it is called dynamic initialization.

For example:
int c= a+b;
float avg=sum/n;
 Reference variable:

 c++ references allow you to create a


second name for the variable that you can use
to read or modify the original data stored in that
 variable.
This means that when you declare a reference
and assign it a variable it will allow you to treat the
reference exactly as though it were the original
variable for the purpose of accessing and modifying
the value of the original even if the second
name(reference) is located within the different
 scope.
Variable with different name share same data
space.
 Syntax:
data_type& ref_name=
var_name;

 Ex:
int a;
int& i=a;
REFERENCE PROGRAM
#include<iostream>
using namespace std;
int main()
{
int x[5]={1,2,3,4,5};
int& y=x[2];
cout<< "The Value of y is::" << y;
return 0;
}
OPERATORS IN C+
+
All the operator in c is available in c++,but some
additional operator that are not in c are:
<< Insertion operator
>> Extraction operator
:: Scope resolution operator
.* Pointer to member operator
delete memory release operator endl
line feed operator
new memory allocation operator
setw field width operator
SCOPE RESOLUTION OPERATOR(::)
 Basically variable are two types ,local variable and
global variable.

 The variable which are declared within a block or


function, that are used only inside a function is called
local variable.

 The global variable are declared out side function


and used anywhere in the program.

A situation occurs when both global and local variable
name are same and we have to use global variable inside a
local block or function, then it is only possible by using Scope
Resolution Operator, it is used with global variable.
 Syntax:

::variable_name;


A major application of the scope resolution operator is in
the classes to identify the class to which a member
function belongs.
PROGRAME USING :: OPERATOR

#include<iostream>
using namespace std;

int m=5; //global declaration


int main()
{
int m=15;
cout<<"Value of m is "<<m<<"\n";
cout<<"Value of global ::m is "<<::m<<"\n";
return 0;
}
MEMORY MANAGEMENTOPERATOR
 In addition to calloc, malloc,Sfree ,C++ uses two unary operators new and
delete that perform the task of allocating and freeing the memory in better
and easy way.
 A new operator can be used to create object of any type, as and when

required.
 Syntax:

pointer_variable= new data_type;


 Ex:

int *p=new int;


Int *p;
P= new int;
 A delete operator deallocate pointer variable
 When a data object is no longer needed, it is destroyed to release the

memory space for reuse.


 Syntax:
 You can also create space for any data type including user-defined
data type like array, structure, classes ,etc.
 Syntax :

pointer_variable=new data_type[size];
 Ex:

int *p=new int[100];


 Delete array element.

 Syntax:

delete [] pointer_variable;
 Ex:

delete []p;
PROGRAM USING NEW AND DELETE OPERATOR
#include<iostream>
using namespace std;
int main()
{
int *a=new int;
int *b =new int;
int *sum= new
int;

cout<<"Enter value for a and b:"<<"\n";


cin>>*a>>*b;
*sum=*a+*b;
cout<<"Sum of a and b is: "<<*sum;
delete a;
delete b;
return
MANIPULATORS

 C++ provides the operators called manipulator for formatting the


output or data display.
 Most commonly used manipulators are:
 endl
 setw()
 endl manipulator ,when used in an output statement, causes
a linefeed to be inserted .It has the same effect as using the
newline character “\n”.
 setw() is used to provide the field width for the value and
display them right-justified.
 Like,
int x=22;
cout<<setw(5)<<x;

2 2

 The <iomanip> header file provide rich set of


manipulators.
MANIPULATOR PROGRAM
#include<iostream>
#include<iomanip>
using namespace std;

int main()
{
int roll_no=2;
char name[]="Heer";
int age=19;

cout<<"Roll number is :"<<setw(5)<<roll_no<<endl;


cout<<"Name is :"<<setw(5)<<name<<endl;
cout<<"Age is :"<<setw(5)<<age<<endl;

}
TYPE CASTING
 While evaluating an expression if both operands for an
operator are not of same data type, then using implicit
conversion rule c++ convert smaller type to
wider type.

 For example, if two operands are respectively int and


float type, then int is converted into a float ad then
operation is performed.

 Many times implicit conversion cause the problem and


we do not get proper result.
 For that, like c, c++ also uses explicit type casting
with the type cast operator in two different style as
follow:

 Syntax:
(type_name) expression; //C notation

type_name (expression); //C++ notation

 Ex:
average=(float) sum/n;

average=float(sum)/n;
IMPLICIT CONVERSION
 Whenever data type are mixed in expression, c++
perform conversions automatically. This process is
known as implicit conversion.
 If the operand type differ than the compiler converts

one of them to match with the other using the


rule that the “smaller” type is converted to the
“wider” type.
 For example, if one operand is an int and other is

float , the int is converted into float because float


is wider than int.
 Whenever a char and short int appears
in expression it is converted to an int.
EXPRESSION AND THEIR TYPES
 An expression is combination of operators,constants and
variables arranged as per the rule of language.

 It may also include function calls which return values.

 An expression may consist of one or more operands and


zero or more operators to produce a value.
 Expression may consist of following seven types:

 Constant expressions
 Integral expressions
 Float expressions
 Pointer expressions
 Relational expressions
 Logical expressions
 Bitwise expressions
 Constant expression:
It consist of only constant values.
Ex: 20 + 5 / 20;

 Integral expression:
Integral expressions are those which produce integer results after
implementing all the automatic and implicit type conversions.
Ex: m * n – 5; //m and n are integer
5 + int(2.0);

 Float expression:
Floating expression are those which, after all conversions,
produce floating point results.
Ex: 5 + float(10);
x * y / 10; //x and y are floating point
Pointer expression:
Pointer expression produce address values.
Ex: &m;
ptr; //m is variable and ptr is pointer

 Relational expression:
Relational expressions yield results of type bool which takes
a value true or false.
Also known as boolean expression.
Ex: x <= y;
a+b == c+d;
If arithmetic expression are used either side of relational
operator, they will be evaluated first then the results
compared.
 Logical expression
Logical expression combine two or more relational
expression and produces bool type result.
Ex: a>b && x==10;
x==10 || y==5;

Bitwise expression
Bitwise expressions
are used to
manipulate data at
bit
level. They are
basically used for
testing or shifting
bits.
Ex: x<<3 // shift three bit position to left
SPECIAL ASSIGNMENT EXPRESSIONS
 Chained assignment:
x = (y=10); or x = y = 10;
In above expression the 10 value is first assign to y and
then to x.
Chained expression is not used to do initialization at the time of
declaration .
Like ,
float a=b=12.34; is wrong, instead of this we may write ,
float a = 12.34, b= 12.34; is correct.
 Embedded assignment:
x = (y =50) +10;
where y=50 is an assignment expression
known as embedded assignment.
here, value 50 is assigned to y and then the result
(50 + 10 = 60) is assigned to x.
like, y=50;
x = y + 10;

 Compound assignment:
Compound assignment operator (+=)is a
combination of the assignment operator with a
binary operator.
Ex: x=x+10 may be
written as , x +=10;
OPERATOR PRECEDENCE AND ASSOCIATIVITY

precedence operators description associativity

Scope resolution
1 ::
operator
Suffix/postfix
++ --
increment decrement

Function style
type()
Type cast
type{ } Left-to-right
2 Function call
()
Array subscripting
[]
Element selection by
.
Reference
Element selection
->
through pointer
precedence operators description associativity

++ - - Prefix increment and


decrement
+- Unary plus and minus
logical NOT and
! ~ bitwise NOT
C-style type cast
(type)
Indirection
3 * (dereference) Right-to-left
Address –of
&
Sizeof
sizeof Dynamic memory
new, new[] allocation
Dynamic memory
delete , deallocation
delete[]
precedence operators description associativity
4 .* ->* Pointer to member
* / Multiplication, division
5 % and remainder

+ - Addition and subtraction


6

<< >> Bitwise left shift and right


7
shift
< <= Relational operator
8
> >= Left-to-right
== != Relational is equal to
9
and not equal to
10 & Bitwise AND
11 ^ Bitwise(exclusive)OR

12 | Bitwise (inclusive) OR

13 && Logical AND

14 || Logical OR
precedence operators description associativity

?: Ternary operator

throw Throw operator

= Direct assignment
operator
+= -= Assignment by sum
and difference
15 Right-to-left
*= /= %= Assignment by product
quotient, and
remainder
<<= >>= Assignment by left shift
and right shift
&= ^= |= Assignment by bitwise
AND XOR and OR
, comma
16 Left-to-right
CONTROL STRUCTURE
 Like c ,c++ also provide same control structure as
follows:
 if statement
 if-else statement
 switch statement
 do-while statement
 while statement
 for statement
If statement:
syntax:
if (expression is true)
{
action-1; if(a>b)
} {
cout<<“a is max”;
else
}
{ else
a {
c cout<<“b is max”;
t }
i
o
n
-
2
 Switch statement:
switch(expression)
{
case1: switch(character)
action1; {
case ‘m’:
break;
cout<<“male candidate”;
case2: break;
action2; case ‘f’:
break; cout<<“female
… candidate”;
break;
default:
acti default:
} onN; cout<
<“inva
lid
 While statement:
syntax:
while(condition is true)
{
action1;
}

while(i>5)
{
cout<<“number of class:”;
i++;
}
 Do-while statement:
syntax:
do
{
actio
n1;
}
while(co
ndition
i=0;
is
do
true);
{
cout<<i<<“\n”;
i++;
}
while(i<5);
 For statement:
syntax:
for(initial_value;condition;incement/decrement)
{
action1;
}

for(int i=0;i<=5;i++)
{
cout<<i<<“\n”;
}

You might also like