Sunday, January 24, 2016

Pointer in C/C++ - Exersice 2

Ex1. Write a C++ program to accept five integer values from keyword. The five values will be stored in an array using a pointer. Then pr... thumbnail 1 summary

Ex1. Write a C++ program to accept five integer values from keyword.

The five values will be stored in an array using a pointer. Then print the elements of the array on the screen.
Solution:

#include<iostream> 
#include<conio.h>
using namespace std;
   int main() 
    { 
     int arr[5],i; 
     int *p=arr; 
     cout<<"Enter five numbers separated by space:"; 
     cin>>*p>>*(p+1)>>*(p+2)>>*(p+3)>>*(p+4); 
     cout<<"Your numbers are:\n"; 
     for(i=0;i<5;i++) 
        cout<<arr[i]<<endl; 
       getch(); 
     return 0; 
     } 
 2. Modify the solution of exercise 1 in order to print the elements of the array in reverse order using a pointer.
Solution:
#include<iostream> 
#include<conio.h>
using namespace std;
   int main() 
    { 
     int arr[5],i; 
     int *p=arr; 
     cout<<"Enter five numbers separated by space:"; 
     cin>>*p>>*(p+1)>>*(p+2)>>*(p+3)>>*(p+4); 
     cout<<"Your numbers are:\n"; 
     for(i=4;i>=0;i--) 
        cout<<*(p+i)<<endl; 
      getch(); 
     return 0; 
      }

No comments

Post a Comment