Define a structure type element_t to represent one element from the periodic tab
ID: 3766221 • Letter: D
Question
Define a structure type element_t to represent one element from the periodic table of elements. The structure should include the atomic number, the name, the chemical symbol, the atomic weight.
Implement I/O functions scan_element and print_element.
Implement compare function, which takes two variables of element_t and returns 0 if the two elements are the same, -1 if the first element has a smaller atomic number, and 1 if the first element has a larger atomic number.
Write a main function which declares two elements.
Use the scan_element function two times to input one element and then the other one.
Use compare function to print (using print_element) the elements in order according to their atomic numbers.
Explanation / Answer
Here is the code for you as per the skeleton you gave me. If you need any refinement, just get back to me.
#include <iostream>
using namespace std;
typedef struct element_t
{
int atomicNumber;
string name;
string chemicalSymbol;
int atomicWeight;
}element_t;
element_t scan_element()
{
element_t temp;
cout<<"Enter the atomic number of the element: ";
cin>>temp.atomicNumber;
cout<<"Enter the name of the element: ";
cin>>temp.name;
cout<<"Enter the chemical symbol of the element: ";
cin>>temp.chemicalSymbol;
cout<<"Enter the atomic weight of the element: ";
cin>>temp.atomicWeight;
return temp;
}
void print_element(element_t temp)
{
cout<<"Atomic Number : "<<temp.atomicNumber<<endl;
cout<<"Name : "<<temp.name<<endl;
cout<<"Chemical Symbol: "<<temp.chemicalSymbol<<endl;
cout<<"Atomic Weight : "<<temp.atomicWeight<<endl<<endl;
}
int compare(element_t element1, element_t element2)
{
int num = element1.atomicNumber - element2.atomicNumber;
if(num == 0)
return 0;
else if(num < 0)
return -1;
else
return 1;
}
int main()
{
element_t element1, element2;
element1 = scan_element();
element2 = scan_element();
if(compare(element1, element2) == -1)
{
print_element(element1);
print_element(element2);
}
else
{
print_element(element2);
print_element(element1);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.