I have these challenges:
- Define a struct containing 4 data types
- Write a program in C that uses the
rand()
function to create 1000 instances of these structs - Inserts them in the linked list and prints out the first 10 to the console.
Modify the linked list code provided in the file code.c so that it works for inserting structs of type given in your answer to Question 1.
#include <stdio.h>
#include <stdlib.h>
#include<malloc.h>
//#include "users.h"
int i;
//Stime = srand(time(0));
typedef struct users
{
int UserID;
char FullName[50];
int Age;
//double Height;
float Weight;
}users;
typedef struct node
{
//Stime = srand(time(0));
users data;
struct node *next;
} node;
node* insert(node *ptr, users data)
{
node *entry = (node*)malloc(sizeof(node));
//printf("enter the data item\n");
//scanf("%d",*node-> next);
if(entry == NULL)
{
printf("No Free Memory!\n");
exit(0);
}
else
{
entry->data = data;
entry->next = NULL;
if(ptr == NULL)
{
ptr = entry;
}
else
{
node *temp = ptr;
while(temp->next != NULL)
{
temp = temp->next;
}
temp->next = entry;
}
}
return ptr;
}
/
obviously U[i] is not the correct way to do this. if I wanted to have unique constructors o-n (max 1000) how would I do it?
int main()
{
int i= 0;
node *first = NULL;
srand(time(0));
users U[i] = {
(U[i].UserID = 600000+rand()% 33331),
(strcpy( U[i].FullName , " Nathanial Rivers")),
(U[i].Age = 18+rand()% 82),
(U[i].Weight = 40+rand()% 99)
};
//users U1 = {600000,"Martin Toomey",19,76.6};
users U2 = {(U2.UserID = 600000+rand()% 33331),"bob boby",21,77.7};
users U3 = {600002,"abcdefg ",17,79.1};
printf(" Name: %s \n",U1.FullName);
printf(" User ID: %d \n Age is: %d \n Weight is: %f \n \n",U1.UserID, U1.Age, U1.Weight );
for (i=0; i<10; i++){
srand(time(0));
first = insert(first, U[i]);
/first = insert(first, U2);
//first = insert(first, U3);
//printf(" User ID: %d \n Age is: %d \n Weight is: %f \n \n",U1.UserID, U1.Age, U1.Weight );}
printf(" User ID: %d \n", U[i].UserID);
printf(" Age %d \n", U[i].Age);
printf(" User ID: %d \n", U[i].UserID);
printf(" Age %d \n", U2.Age);
}
//printf(U1);
first = insert(first, U2);
//printf(*U2);
first = insert(first, U3);
return 0;
}
In main() function, I'm trying to generate 100 unique users using rand I have thought that if I have a print function or param in first and every time I call first in the loop in prints the user info with C I'm not sure if that possible
Any pointers on how to improve my code greatly appreciated I know U1 U2 U3.... shouldn't be used as var names its bad practice.