Answer to Question #235349 in C++ for Myname

Question #235349
Write a program that inserts 25 random integers from 0 to 100 in sorted order in a linked list.
The program should calculate the sum of the elements and the floating-point average of the
elements.
1
Expert's answer
2021-09-10T12:27:24-0400
#include<iostream>
#include <stdlib.h>     /* srand, rand */
#include <time.h>       /* time */


using namespace std;
struct SortedLinkedList{
	int value;
	SortedLinkedList *next;  
};
void sortedInsert(struct SortedLinkedList**head , int value)
{
	SortedLinkedList*temp = *head ;
	SortedLinkedList *t = new SortedLinkedList;
	if(*head==NULL)
	{
		*head = new SortedLinkedList;
		(*head)->value = value;
		(*head)->next = NULL;
	}


	else
	{


		if(value < temp->value) //start node
		{
			t = new SortedLinkedList;
			t->value = value;
			t->next = *head;
			*head = t;
		}


		else
		{
			while(temp->next != NULL && !(value < temp->next->value && value >= temp->value))
				temp=temp->next;


			if(temp->next == NULL) 
			{
				temp->next = new SortedLinkedList;
				temp = temp->next;
				temp->value = value;
				temp->next = NULL;
			}
			else 
			{
				t = new SortedLinkedList;
				t->value = value;
				t->next = temp->next; 
				temp->next = t;
			}
		}
	}
}
void display(struct SortedLinkedList**head)
{
	struct SortedLinkedList*temp=*head;
	//calculate the sum of the elements 
	float sum=0;
	while(temp!=NULL)
	{
		if(temp->next!=NULL)
			cout<<temp->value<<" ->";
		else
			cout<<temp->value;


		sum+=temp->value;
		temp=temp->next; //move to next node
	}
	// the floating-point average of the elements.
	float average=sum/25.0;
	cout<<"\nSum = "<<sum;
	cout<<"\nAverage = "<<average;
	cout<<endl;
}




int main()
{


	struct SortedLinkedList *head = NULL; 
	/* initialize random seed: */
	srand (time(NULL));
	for(int i=0;i<25;i++){
		int randomNumber = rand() % 101;
		sortedInsert(&head,randomNumber);
	}
	cout<<"Current List is:\n";
	display(&head);
	
	int k;
	cin>>k;


	return 0;
}





Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS