I had 1 exercise: read data form file then add into TREE.
I read data in the file into an array, then add array into TREE,
here is my solution but it does not work properly
I know that data in array seq[] will be erased after ReadFile() function but I do not know how to keep value for array to use in main function, may be it is related to pointer ...

#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
           // ---------ARRAY REPRESENTATION ----------------------//
typedef int BOOL;
#define TRUE 1
#define FALSE 0
#define TOTAL_SLOTS 500
 
struct nodetype{
	int info;
	BOOL used;
} node[TOTAL_SLOTS];
 
FILE *fp;
int seq[8];
//InitializeTree: Set the used field of each slot as false.
void InitializeTree()
{	int i;
	for (i = 0; i<TOTAL_SLOTS; i++)
		node[i].used = FALSE;
}
 
//AddNode: Add a node at a given position.
void AddNode(int NodeID, int value) 
{	if (NodeID >= TOTAL_SLOTS)	
	{	printf("overflow error\n"); 
		exit(1); 
	}
	else if (node[NodeID].used)	
	{	printf("invalid insertion\n"); 
		exit(1); 
	}
	else	
	{ 	node[NodeID].info = value;
		node[NodeID].used =TRUE;
	}
}


//Read data from File input_array.txt
void ReadFile()
{    int i;
     if((fp=fopen("input_array.txt","r"))==NULL)
     {
       printf("Error reading\n");
       exit(1);
     }
     for(i=0;i<8;i++)
     {
     fscanf(fp,"%d",&seq[i]);
     printf("%d  ",seq[i]);
     }
     fclose(fp);
}
     

int main(void)
{	int seq[8];
    
   
	int NodeID, i;
 
	InitializeTree(); //Initialize the tree
    ReadFile();
    
	for(i=0;i<8;i++) //add data in array into tree and file duplicate
	{	NodeID=0;
		while ((NodeID < TOTAL_SLOTS))
		{	if (!node[NodeID].used)   
			{	AddNode(NodeID,temp[i]); 
				break;
			}
			if (seq[i] == node[NodeID].info)   
			{	printf("%d is a duplicate\n", seq[i]); 
				break; 
			}
			if (seq[i] < node[NodeID].info) 						
				 NodeID = 2* NodeID +1;		
			else  
				 NodeID = 2* NodeID +2;
		}
		if (NodeID >=TOTAL_SLOTS)	
		{	printf("overflow error\n"); 	
			exit(1);
		}
	}
	getch();
	return 0;
}

oh, my code works well, I just made a small mistake in line 71 in my code it must be AddNode(NodeID,seq);

i had that happen a lot.

(1) get stuck
(2) post question to forum
(3) find and fix problem while waiting for answer

:)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.