Sum of array elements using recursion

QUESTION

Given an array of integers, find sum of array elements using recursion.

“TESTCASE_1”: “5\n1 2 3 4 5\n###—###SEPERATOR—###—\n15”, “TESTCASE_2”: “6\n4 5 7 9 5 2\n###—###SEPERATOR—###—\n32”, “TESTCASE_3”: “8\n5 6 12 24 78 65 70 12\n###—###SEPERATOR—###—\n272”, “TESTCASE_4”: “5\n-8 -9 6 5 10\n###—###SEPERATOR—###—\n4”, “TESTCASE_5”: “0\n###—###SEPERATOR—###—\n0

ANSWER

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
typedef struct node
{
	int data;
	struct node *next;
}Node;
Node *head;
Node *tr;
Node *prev;
void insert(int n)
{
	Node *temp=(Node*)malloc(sizeof(Node));
	temp->data=n;
	if(head==NULL)
	{
		head=temp;
		head->next=NULL;
	}
	else
	{
	
	tr=head;
	while(tr->next!=NULL)
	{
		tr=tr->next;
	}
	tr->next=temp;
	tr=tr->next;
	tr->next=NULL;
}
}

void display(int n)
{
  double sum=0;
	if(head==NULL)
	{
		printf("NULL");
		
	}
	else
	{
		tr=head;
		while(tr->next!=NULL)
		{
          sum=sum+(double)tr->data;
			//printf("%d->",tr->data);
			tr=tr->next;
		}
      sum=sum+(double)tr->data;
		printf("%.2f",sum/n);
	}
}
int main()
{
	int n;

	scanf("%d",&n);
		int data[100];
		
		//n=strlen(data);
	int i;
	for(i=0;i<n;i++)
	{
		scanf("%d",&data[i]);
		insert(data[i]);
	}
	//deletion();
	display(n);

	return 0;
}
Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.

Powered By
CHP Adblock Detector Plugin | Codehelppro