I am learning how to create struct's and I am stuck on a program I made. Everything works fine until I try to input "2". When the program prints the symbol it's supposed to be "He" but prints "HeHelium" instead. I can't figure out what's wrong and why it's printing he.symbol
and he.name
all in one line. Link to image below.
#include <stdio.h>
#include <stdlib.h>
struct Element {
int num;
double mass;
char symbol[2];
char name[20];
};
int main()
{
struct Element h;
h.num = 1;
h.mass = 1.008;
strcpy(h.symbol, "H");
strcpy(h.name, "Hydrogen");
struct Element he;
he.num = 2;
he.mass = 4.0026;
strcpy(he.symbol, "He");
strcpy(he.name, "Helium");
int number;
printf("Please enter the number of the element you want info on.
");
scanf("%d", &number);
if (number == 1 /*&& !(number > 1)*/) {
printf("Atomic Number: %d
", h.num);
printf("Atomic Mass: %.3f
", h.mass);
printf("Atomic Symbol: %s
", h.symbol);
printf("Atomic Name: %s
", h.name);
} else if (number == 2) {
printf("Atomic Number: %d
", he.num);
printf("Atomic Mass: %.3f
", he.mass);
printf("Atomic Symbol: %s
", he.symbol);
printf("Atomic Name: %s
", he.name);
} else {
printf("Invalid number!
");
printf("Or that element hasn't been added to the date base yet.
");
printf("Try back later
");
}
return 0;
}
When I input "2":