Thursday, 21 September 2017

Pointer demo in C++

/*
 Pointer Demo in C++
*/

#include "iostream"
using namespace std;
const int MAX=3;

int main(){
 int var[MAX] = {10,100,200};
 int *ptr = var; // or even you can write int *ptr = &var[0], but not just var[0] or &var
 cout<<"\nPrinting elements in ascending order"<<endl;
 for(int i=0; i<MAX; i++){
  cout<<*(ptr)<<endl; // printing elements in ascending order
  ptr++;
 /*
  or else below 
  cout<<*(ptr+i)<<endl;
  no need to write ptr++ then
 */
 }

 cout<<endl<<endl<<"printing elements in descending order\n";
 ptr = &var[MAX-1]; // MAX-1 is important here
 for(int i=0; i<MAX; i++){ // this i loop is not playing much role here, even this can be like int i=MAX; i>0; i--
  cout<<*(ptr)<<endl; // printing elements in ascending order
  ptr--;
 /*
  or else below 
  cout<<*(ptr+i)<<endl;
  no need to write ptr++ then
 */
 }
 
 return 0;
}
/*
 OUTPUT
[pavan@localhost Pointers]$ g++ PointerDemo.cpp
[pavan@localhost Pointers]$ ./a.out 

Printing elements in ascending order
10
100
200


printing elements in descending order
200
100
10
[pavan@localhost Pointers]$ 


*/

No comments: