Beginning with C++
Beginning with C++
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
changed by user.
Cannot be used as names for the program variables or other
Each language has its own rules for naming these identifiers.For C+
and strings.
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
Syntax:
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;
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
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
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
before it is used.
Syntax:
data_type name[size];
Ex:
char name[10];
int student[10];
FUNCTION
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);
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;
#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,
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
we used it.
The diiference is that in c, it requires to be defined
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:
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.
::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;
required.
Syntax:
pointer_variable=new data_type[size];
Ex:
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;
2 2
int main()
{
int roll_no=2;
char name[]="Heer";
int age=19;
}
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.
Syntax:
(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
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
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
12 | Bitwise (inclusive) OR
14 || Logical OR
precedence operators description associativity
?: Ternary 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”;
}