AlexCR AlexCR - 27 days ago 75
C Question

How does code that repeats letters work?

I have recently started learning C and I have the following piece of code that I have a hard time understanding.



Basically it's a function that takes a string and displays it,
repeating each alphabetical character as many times as its alphabetical index, followed by a newline.

#include <unistd.h>

int ft_is_alpha(char c)
{
if ((c >= 'a') && (c <= 'z'))
return (0);
else
return (1);

}

int ft_count(char c)
{
int k;
k = (c - 'a');
return (k);
}

void ft_print(char **argv)
{
int i;
int j;
i = 0;
j = 0;
while (argv[1][i])
{
if (ft_is_alpha(argv[1][i]))
{
write(1, &argv[1][i], 1);
}
else
{
while (j <= ft_count(argv[1][i]))
{
write(1, &argv[1][i], 1);
j++;
}
j = 0;
}
i++;
}
}

int main(int argc, char **argv)
{
if (argc != 2)
{
write(1, "\n", 1);
return (0);
}
ft_print(argv);
write(1, "\n", 1);
return (0);
}


result:


./a.out "abcd"
abbcccdddd


What I don't understand is how
ft_print
is working and where the code multiplies the letters.

From what I understand
if the string is alpha it writes it letter by letter
.
If not
- here I get stuck with this
j
.

Also, why it makes it
0
at the end of the while loop?

Is there a way to somehow see what the code does line by line?

Answer Source

The reason for misunderstanding the code is that the function ft_is_alpha

int ft_is_alpha(char c)
{
  if ((c >= 'a') && (c <= 'z'))
    return (0);
  else
    return (1);

}

is defined logically incorrectly. (More precisely the reason for misunderstanding is badly written code.:) ) The function should return 1 in case when a character is in the range ['a', 'z'] and 0 otherwise.

For example

int ft_is_alpha(char c)
{
    return c >= 'a' && c <= 'z';
}

And after changing the function ft_print appropriately

void ft_print( char **argv )
{
    int i = 0;

    while ( argv[1][i] )
    {
        write( 1, &argv[1][i], 1 );

        if ( ft_is_alpha( argv[1][i] ) )
        {
            int n = ft_count( argv[1][i] );
            for ( int j = 0; j < n; j++ )
            {
                write(1, &argv[1][i], 1);
            }
        }
        i++;
    }
}

the program will be more readable and clear.

Thus when a next character argv[1][i] is in the range ['a', 'z'] it is additionally outputted argv[1][i] - 'a' times.