To find number of Grandchildren for a Grandfather

To find number of Grandchildren for a Grandfather

Question:

Find the number of Grandchildren for Grandfather where the first name is ‘father’ and second is the ‘child’.

Logic:

  1. The input of both father and child name is stored in the structure.
  2. Then Grandfather name is compared with all father name in structure.
  3. If Grandfather name means to pass the child name to function count() whose father is found.
  4. In function count() b value is compared with all father name.
  5. If father name found in structure then increment the count of grandchildren.
  6. Repeat step 4 and 5 up to n then return cnt value.
  7. Repeat step 2 to 6 up to n.
  8. Then print the count value which is the number of grandchildren.

Program:

#include<stdio.h>
#include<string.h>
struct rela                            //structure for father and a child
{
	char child[10],father[10];
}s[10];                                
int count(char b[],int n,int cnt)      //count the no of grandchildren
{
	int i;
	for(i=0;i<n;i++)
	{
		if(strcmp(b,s[i].father)==0)   //compare the child name with all father's name to find the Grandchildean
		{
			cnt++;                     //interments when any grandchild found
		}
	}
	return cnt;
}
void main()
{
	int n,i,cnt=0;
	char a[20];
	clrscr();
	printf("enter the no of inputs:");
	scanf("%d",&n);
	printf("enter the inputs:");
	for(i=0;i<n;i++)                    //both father and child name are stored in structure
	{
		printf("father name:");
		scanf("%s",&s[i].father);       
		printf("child name:");
		scanf("%s",&s[i].child);      

	}
	printf("enter the grandfather's name:");
	scanf("%s",&a);
	for(i=0;i<n;i++) 
      { 
        if(strcmp(a,s[i].father)==0) //compare the grandfather name with all father's name 
        { 
                cnt=count(s[i].child,n,cnt); //pass child name to function to count grandchild 
        } 
      } 
      if(cnt>0)
	{
		printf("No of grandchildren for %s is %d",a,cnt);
	}
	else
	{
		printf("No of grandchildren for %s is %d",a,cnt);
	}
	getch();
}

You might also like:

To find count of specific character

Vignesh

A Computer Science graduate who likes to make things simpler. When he’s not working, you can find him surfing the web, learning facts, tricks and life hacks. He also enjoys movies in his leisure time.