Control Structures & Pointers in C++: by Prof. Manikandan Dept of Computer Application
Control Structures & Pointers in C++: by Prof. Manikandan Dept of Computer Application
POINTERS IN C++
By
Prof. Manikandan
Conditional Statements
1.Conditional Execution
The conditional expressions are mainly used for
decision making.
The following statements are used to perform the task
of the conditional operations.
1. if statement
2. if-else statement
3. Nested If statement
LOOPING
1. for loop
2. while loop
3. do-while loop
For loop
Syntax
Example Program:
#include<iostream.h>
#include<conio.h>
void main()
{
int i;
clrscr();
for(i=0; i<=100; i++)
cout<<i<<endl;
getch();
}
WHILE LOOP
Syntax
While (Condition)
Statement;
Example Program:
#include<iostream.h>
#include<conio.h>
void main()
{
int i=0; // initialization
clrscr();
while(i<10) //Condition
{
cout<<i<<endl;
i++; // increment
}
getch();
}
DO-WHILE LOOP
Syntax
do{
Statement_1;
Statement_2;
----------} while (expression);
Example Program:
#include<iostream.h>
#include<conio.h>
void main()
{
int i=0; // initialization
clrscr();
do
{
cout<<i<<endl;
i++;
// increment
}while(i<10);
//Condition
getch();
}
Syntax:
For(exp-1; exp-2; exp-3a, exp-3b)
{
Statement(s);
}
Example Program:
#include<iostream.h>
#include<conio.h>
void main()
{
int a,b;
clrscr();
for(a=0, b=10; a<=10; a++, b--)
cout<<"\n"<<a<<"\t" <<b;
getch();
}
SELECTION STATEMENT
1. Switch
2. Break
3. Continue
SWITCH STATEMENT
Syntax
switch (expression) {
case constant_1 :
Statements;
case constant_2 :
Statements;
;;
;;
;;
case constant _n :
Statements;
default :
Statement;
}
Example Program:
#include<iostream.h>
#include<conio.h>
void main()
{
int grade,hra;
clrscr();
cout<<"Enter the grade:";
cin>>grade;
switch(grade)
{
case 1:
hra=1000;
break;
case 2:
hra=800;
break;
case 3:
hra=500;
break;
default:
hra=0;
}
cout<<"Grade="<<grade<<"HRA="<<hra;
getch();
}
UNCONDITIONAL GOTO
Example
#include<iostream.h>
void main(){
start:
cout << II BCA;
goto start;
}
POINTER
Pointer operator
For eg.
int *ptr;
float *fp;
Address operator
An address operator can be represented by a combination
of & (ampersand) with a pointer variable.
For Ex:
K = &ptr;
Note:
The address Operator (&)
The Indirection Operator (*)
(or) Value at address and return the value stored at the
specified address.
Example Program:
#include<iostream.h>
#include<conio.h>
void main()
{
int a=5;
cout<<"The value of a :"<<a;
cout<<"The address of a :"<<&a;
getch();
}
Output :
The value of a = 5
The address of a = 0x516240e
POINTER EXPRESSIONS
Pointer assignment :
Ex:
int x,y;
int *ptr1, *ptr2;
ptr1 = &x;
y = *ptr1;
Example Program:
#include <iostream.h>
void main()
{
char x,y;
char *pt;
x = k; // assign character
pt = &x;
y = *pt; // * value at address
cout << Value of x = << x << endl;
cout << Pointer value = << y << endl;
}
Thank You