Monday, November 11, 2013

Pointer Programs in C++

Program 1:
#include <iostream.h>
int main()
{
int intvar = 10;
int *intptr;
intptr = &intvar;
cout << "\nLocation of intvar: " << &intvar;
cout << "\nContents of intvar: " << intvar;
cout << "\nLocation of intptr: " << &intptr;
cout << "\nContents of intptr: " << intptr;
cout << "\nThe value that intptr points to: " << *intptr;
return 0;
}

Program 2:
#include <iostream.h>
int main()
{
char name[40];
char *str_ptr = name;
int pos, num_chars;
cout << "Enter a string for the character array: ";
cin.get(name,40,'\n');
cout << "How many characters do you want to extract? ";
cin >> num_chars;
for (pos = 0; pos < num_chars; pos++)
cout << *str_ptr++;
cout << '\n';
return 0;
}

Program 3:
#include <iostream.h>
void swap(int *, int *); // This is swap's prototype
int main()
{
int x = 5, y = 7;
swap(&x, &y);
cout << "\n x is now "<< x << " and y is now " << y << '\n';
return 0;
}
void swap(int *a, int *b) // swap is actually defined here
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}

No comments:

Post a Comment