Wednesday, August 08, 2012

Program to combine two strings by using pointers


void main(void){
  char sta[]="Hello";
  char stb[]="World";
  char stc[20];
  char *s=stc;
  char *ptr=sta;
  while(*ptr!='\0'){
  *s=*ptr; *s++; *ptr++;
  }
  *s=' '; *s++; ptr=stb;
  while(*ptr!='\0'){
  *s=*ptr; *s++; *ptr++;
  }
  *s='\0';
  cout<<stc<<endl;
}

Swap two values by using pointers as arguments to a function


void swap(int *, int *);
void main(void) {
int a,b;
a=10;
b=20;
swap(&a,&b);
cout<<"a="<<a<<endl;
cout<<"b="<<b<<endl;
}
void swap(int *x, int *y) {
int temp;
temp=*x;
*x=*y;
*y=temp;
}

Program to input data into an array and then to print on the screen by using pointers as function arguments

Program to input data into an array and then to print on the screen by using pointers as function arguments
output

void display(int *);
void main(void) {
  int i,arr[5];
  cout<<"\nInput:\n";
  for(i=0;i<5;i++) {
  cin>>arr[i];
  }
  display(arr);
}
void display(int *ptr) {
  cout<<"\nOutput:\n";
  for(int i=0;i<5;i++) {
  cout<<*ptr<<endl;
  ptr++;
  }
}