Skip to main content

Featured

C Program to Solve Two Sum Using Brute Force (With Algorithm & Output)

 Introduction The Two Sum problem is a popular coding interview question where we must find two indices of an array whose values add up to a given target. This program demonstrates a simple brute-force solution in C using nested loops and dynamic memory allocation. Problem Statement Given an integer array and a target value, return the indices of the two numbers such that they add up to the target. Each input has exactly one solution, and the same element cannot be used twice. The result should return the indices, not the values. If no solution exists, return NULL.  Algorithm / Logic Explanation Start the program. Traverse the array using a loop from index 0 to numsSize - 1 . Inside this loop, use another loop starting from i + 1 to numsSize - 1 . For every pair (i, j) , check if nums[i] + nums[j] == target . If condition becomes true: Allocate memory for 2 integers using malloc() . Store indices i and j . Set returnSize = 2 . Return the result poi...

C++ Program to Demonstrate Friend Function with Two Classes

 

C++ Program to Demonstrate Friend Function with Two Classes

C++ Program to Demonstrate Friend Function with Two Classes


#include <iostream>
using namespace std;

class A;
class B;

class A
{
    int x;
public:
    A()
    {
        cout << "Enter the value of x: ";
        cin >> x;
    }
    friend void show(A obj1, B obj2);
};

class B
{
    int y;
public:
    B()
    {
        cout << "Enter the value of y: ";
        cin >> y;
    }
    friend void show(A obj1, B obj2);
};

void show(A obj1, B obj2)
{
    cout << "The value of x = " << obj1.x
         << " and y = " << obj2.y << endl;
}

int main()
{
    A obj1;
    B obj2;
    show(obj1, obj2);
    return 0;
}
  

๐Ÿ“˜ Explanation:

This program demonstrates a friend function shared by two different classes in C++. The function show() is declared as a friend in both classes A and B.

  • Class A contains a private data member x.
  • Class B contains a private data member y.
  • The function show(A, B) is declared as a friend in both classes.
  • Because of friendship, show() can access private members of both classes.

This technique is useful when a single function needs to work with data from multiple classes without being a member of either class.

๐Ÿงพ Sample Output:

Enter the value of x: 5
Enter the value of y: 10
The value of x = 5 and y = 10
  

๐Ÿ”‘ Keywords:

C++ friend function with two classes, accessing private members, C++ OOP concepts, friend function example, C++ classes

๐Ÿ“Œ Hashtags:

#CPlusPlus #FriendFunction #OOP #CPPBasics #Programming #1printf

๐Ÿ” Search Description:

Learn how a friend function works with two classes in C++. This example shows how a single function can access private data of multiple classes with clear explanation and output.

Comments

Popular Posts

๐ŸŒ™