"Pointers & Arrays": WEEK # 15
"Pointers & Arrays": WEEK # 15
WEEK # 15
LECTURE 2
cout<<num<<endl; cout<<&num<<endl;
cout<<endl; cout<<a[0]<<endl; cout<<&a[0]<<endl; cout<<a<<endl<<endl;; cout<<a[1]<<endl; cout<<&a[1]<<endl; }
The concept of array is very similar to the concept of pointer. The name of an array actually a pointer that holds the address of the first element of the array. Therefore if you have two declarations as follows: int a[10]; int *p; then the assignment p = a; is perfectly valid
Pointer (Revision)
If you increment a pointer, it will be increased by the size of whatever it points to.
*(ptr+4)
a[4]
int a[5];
Examples
Write a program which will take ten values from the user. And the program should display the average of those ten values. Should be done through pointers.
Solution
#include<iostream.h> void main() { int a[10]; int *p; int sum=0; p=a; for(int i=0;i<=9;i++) { cin>>*p; p++; } cout<<endl<<endl; cout<<"Value Display through Array..; cout<<<<endl; for(i=0;i<=9;i++) { cout<<a[i]<<" "; } p=a; cout<<endl<<endl; cout<<"Value Display through Pointers.."<<endl; for(i=0;i<=9;i++) { cout<<*p<<" "; p++; } p=a; for(i=0;i<=9;i++) { sum=sum+(*p); p++; } cout<<endl<<endl; cout<<"Average is "<<sum/10<<endl<<endl; }
Solution
#include<iostream.h> void main() { int a[10]; int *p[10]; int sum=0; for(int i=0;i<=9;i++) { p[i]=&a[i]; } for(i=0;i<=9;i++) { cin>>*p[i]; } cout<<endl<<endl; cout<<"Value Display through Array.."<<endl; for(i=0;i<=9;i++) { cout<<a[i]<<" "; } cout<<endl<<endl; cout<<"Value Display through Pointers.."<<endl; for(i=0;i<=9;i++) { cout<<*p[i]<<" "; }
cout<<num<<endl; cout<<arr<<endl;