Two numbers N1 and N2 are said to be brothers, if each digit of N1 appears at least one time in N2, AND each digit of N2 appears at least one time in N1.

Examples:

  • N1 = 1162 and N2 = 612, are brothers.
  • N1 = 905 and N2 = 9059, are bothers.
  • N1 = 405 and N2 = 554, are not bothers.
  1. Write the function Initialize that initializes to -1 the values of an array’s integer elements. The array and its size are passed as parameters.
  2. Write the function Belongs that checks if an integer value v belongs to an array of integers T. The function returns 1 if v belongs to T and 0 otherwise. The integer v, the array and its size are passed as parameters.
  3. Write the function Decompose that has three parameters: an integer n, an array of integers T, and its size. This function stokes the digits of n in T. We suppose that the size of the array is always greater than the number of digits of n.
  4. Using the previous functions, write a main function that prompts the user to enter the values of two integers N1 and N2, and says if they are brothers or not.

Difficulty level
This exercise is mostly suitable for students
#include<stdio.h>
#define S 100

void Initialize(int A[], int size)
{
	int i;
	for(i=0;i<size;i++)
		A[i]=-1;
}

int Belongs(int v, int T[], int size)
{
	int i;
	for(i=0;i<size;i++)
		if(T[i]==v)
			return 1;
	return 0;
}

int Decompose(int n, int T[])
{
	int i=0;
	while(n)
	{
		T[i++]=n%10;
		n/=10;
	}
	return i;
}

void main()
{
	int n1, n2;
	int T1[S], T2[S];
	int s1, s2;
	int i , brothers;
 

	do{
		printf("Enter n1: ");
		scanf("%d", &n1);
	}while(n1<0);

	do{
		printf("Enter n2: ");
		scanf("%d", &n2);
	}while(n2<0);

	Initialize(T1,S);
	Initialize(T2,S);

	s1=Decompose(n1,T1);
	s2=Decompose(n2,T2);

	brothers=1;
	for(i=0;i<s1;i++)
		if(!Belongs(T1[i],T2,s2))
		{
			brothers=0;
			break;
		}

	if(brothers==1)
		for(i=0;i<s2;i++)
			if(!Belongs(T2[i],T1,s1))
			{
				brothers=0;
				break;
			}
	if(brothers)
		printf("%d and %d are brothers\n",n1,n2);
	else
		printf("%d and %d are not brothers\n",n1,n2);	
}

Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Replace the first occurrence of a string in an another string