The given code reverses an array of input characters.
The additional while
loop in reverse()
function is unnecessary I guess.
Any other method or way to remove it?
I would prefer to keep reverse()
as void
.
#include <stdio.h>
#define MAXLEN 65535 /* maximum length of input line */
void reverse(char s[], int l);
/* reverses given input line */
void main()
{
int i, c;
char line[MAXLEN];
i = 0;
while(i < MAXLEN-1 && (c = getchar()) != EOF && c != '\n') /* input characters in array */
{
line[i] = c;
++i;
}
reverse(line, i);
printf("%s", line);
}
void reverse(char s[], int l)
{
char rev[MAXLEN];
int i, len;
i = 0;
len = l; /* duplicate length of initial array */
if(s[l] == '\0')
{
--l;
}
while(i < len)
{
rev[i] = s[l]; /* reversing */
++i;
--l;
}
i = 0;
while (i < len) /* what i think is unnecessary */
{
s[i] = rev[i]; /* storing back to initial array */
++i;
}
}
while
overfor
when you know exactly how many iterations do you need? I am saying aboutwhile(i < len)
. \$\endgroup\$