Archive

Archive for January 11, 2010

C++ Program for CLASS Array Addition & Swapping by using Friend function – Q11

January 11, 2010 Leave a comment

Q11. Program for CLASS Array Addition & Swapping by using Friend function:

Use the concept of Friend function for swapping the private array data members of two classes and getting the sum of two arrays within third class array member.

… from College notes (BCA/MCA assignments):

#include <iostream.h>
#include <conio.h>

class B;
class A{
	private:
		int arr[10];
		int sum;
	public:
		void getdata();
		friend void Swap(A &, B &);
		friend void Sum(A *, B *);
		void display() const;
	};

class B{
	private:
		int arr[10];
		int sum;
	public:
		void getdata();
		friend void Swap(A &, B &);
		friend void Sum(A *, B *);
		void display() const;
	};

void A :: getdata(){
	cout<<"\n Enter 10 Numbers in Array A:- \n";
	for(int i=0; i<10; i++)
		cin>>arr[i];
	}

void B :: getdata(){
	cout<<"\n Enter 10 Numbers in Array B:- \n";
	for(int i=0; i<10; i++)
		cin>>arr[i];
	}

void Swap(A &ob1, B &ob2){
	int temp;
	for(int i=0; i<10; i++){
		temp = ob1.arr[i];
		ob1.arr[i] = ob2.arr[i];
		ob2.arr[i] = temp;
		}
	}

void Sum(A *ob1, B *ob2){
	int sum = 0;
	for(int i=0; i<10; i++)
		sum += ob1->arr[i];
	ob1->sum = sum;
	cout<<"\n Sum of Array A : "<<sum;

	sum = 0;
	for(i=0; i<10; i++)
		sum += ob2->arr[i];
	ob2->sum = sum;
	cout<<"\n Sum of Array B : "<<sum;
	}

void A :: display() const{
	cout<<"\n Elements of Array A are: ";
	for(int i=0; i<10; i++)
		cout<<" "<<arr[i];
	}

void B :: display() const{
	cout<<"\n Elements of Array B are: ";
	for(int i=0; i<10; i++)
		cout<<" "<<arr[i];
	}

void main(){
	A obj1;
	B obj2;
	clrscr();

	cout<<"\n Friend Function programme:-"<<endl;
	obj1.getdata();
	obj2.getdata();

	cout<<"\n Data Before Swapping:-"<<endl;
	obj1.display();
	obj2.display();

	cout<<"\n Data After Swapping:-"<<endl;
	Swap(obj1, obj2);
	obj1.display();
	obj2.display();

	cout<<"\n Addition of Both Class's Arrays:-"<<endl;
	Sum(&obj1, &obj2);
	getch();
	}

 

Output:
Friend Function program:-

Enter 10 Numbers in Array A:-
22 33 4 2 56 64 78 45 3 90

Enter 10 Numbers in Array B:-
67 543 5 67 89 90 12 0 12 70

Data Before Swapping:-

Elements of Array A are: 22 33 4 2 56 64 78 45 3 90
Elements of Array B are: 67 543 5 67 89 90 12 0 12 70

Data After Swapping:-

Elements of Array A are: 67 543 5 67 89 90 12 0 12 70
Elements of Array B are: 22 33 4 2 56 64 78 45 3 90

Addition of Both Class’s Arrays:-

Sum of Array A : 955
Sum of Array B : 397


Advertisement
Categories: Cpp Tags: ,