Among the multitude of things wrong in this code
Wrong format limiter
Given:
char dnachar[10];
The code:
scanf("%10s",dnachar);
will read a string up to 10 characters long, not including the terminating null, which it will always place. Therefore, that scanf
can write as many as eleven (11) chars in a space only declared to hold ten (10). The result of a ten character string read (or longer) will be undefined behavior.
Solution:
if (scanf("%9s", dnachar) != 1)
return EXIT_FAILURE;
Note: if your sequences are really ten characters each, then dnachar
should be declared as:
char dnachar[11]; // account for 10-chars + terminator
And the format string for scanf
should be %10s
accordingly.
Indeterminate Counters
All four of your counters are indeterminate. They have no specified initial value as automatic variables, and therefore operations expecting predictable results are unfounded. If they had static linkage (either globals or declared static
) they would have default values of 0
, but that isn't what your code does.
Solution:
int cytosine = 0;
int thymine = 0;
int guanine = 0;
int adenine = 0;
Incorrect Loop Limit
Given:
for (int i = 0; i < 20; i++){
char x = dnachar[i];
This assumes there are twenty characters in dnachar
(which is impossible unless you've invoked undefined behavior from the item above). One you access dnachar[10]
and beyond, more undefined behavior. Ideally you stop processing chars when there are no more, which is much easier with a pointer than an index.
Solution:
for (char *p = dnachar; *p; ++p)
{
switch(*p)
{
case 'c':
++cytosine;
break;
case 't':
++thymine;
break;
case 'g':
++guanine;
break;
case 'a':
++adenine;
break;
default:
break;
}
}