Using C programming Define a structure type element_t to represent one element f
ID: 3920340 • Letter: U
Question
Using C programming
Define a structure type element_t to represent one element from the periodic table of elements. Components should include the atomic number (an integer); chemical symbol, the name, and class (strings). Write separate subroutines (functions) using C program to (1) Read the periodic table from file and store them in structure array (2) find out the elements in each class (3) print out the name of the distinct classes and the elements in each them in another file.
Uses the following as the input text file:
Explanation / Answer
here is your program : -------------->>>>>>>>>>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAX 20
typedef struct _el{
int aNumber;
double aMass;
char name[30];
char _class[40];
char symbol[5];
struct _el *next;
}Element;
Element* add(Element *head,int an,double am,char *name,char *_cl,char *sy);
void readFile(Element **head,char *_class[],int *ccount){
FILE *fp;
char fname[40];
int st = 0;
printf(" Enter input file name : ");
scanf("%s",fname);
fp = fopen(fname,"r");
if(fp == NULL){
printf(" Input file opening error !!! ");
exit(-1);
}
int i = 0,j;
int an;
double am;
char name[30],_cl[40],sy[5];
while (!feof(fp)){
fscanf(fp,"%d%s%lf%s%s",&an,sy,&am,name,_cl);
if(feof(fp)){
break;
}
st = 0;
for(j = 0;j<i;j++){
if(strcmp(_cl,_class[j]) == 0){
st = 1;
break;
}
}
if(st == 0){
_class[i] = (char *)malloc(sizeof(char)*40);
strcpy(_class[i],_cl);
i++;
}
*head = add(*head,an,am,name,_cl,sy);
}
*ccount = i;
fclose(fp);
}
Element* add(Element *head,int an,double am,char *name,char *_cl,char *sy){
Element *n = (Element *)malloc(sizeof(Element));
n->aMass = am;
n->aNumber = an;
strcpy(n->name,name);
strcpy(n->_class,_cl);
strcpy(n->symbol,sy);
n->next = NULL;
if(head == NULL){
return n;
}
n->next = head;
return n;
}
void saveElement(Element *head,char *_class[],int ccount){
int i;
FILE *fp;
char fname[40];
printf(" Enter output file name : ");
scanf("%s",fname);
fp = fopen(fname,"w");
if(fp == NULL){
printf(" Output file opening error !!! ");
exit(-1);
}
Element *cur = NULL;
for(i=0;i<ccount;i++){
cur = head;
fprintf(fp," %s ------------------------------------------------------------------- ",_class[i]);
fprintf(fp,"%6s%8s%20s%8s ","Number","Symbol","Name","Mass");
while(cur != NULL){
if(strcmp(_class[i],cur->_class) == 0){
fprintf(fp,"%4d%8s%22s%4s%lf ",cur->aNumber,cur->symbol,cur->name," ",cur->aMass);
//printf("%4d%8s%22s%lf ",cur->aNumber,cur->symbol,cur->name,cur->aMass);
}
cur = cur->next;
}
}
fclose(fp);
}
int main(){
char *_class[MAX];
Element *head = NULL;
int ccount;
readFile(&head,_class,&ccount);
saveElement(head,_class,ccount);
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.