Computer Science, asked by ananthsj06, 6 months ago

Write a function that takes 2 inputs - A string and an
integer flag (Value can be 0 or 1)
• If the flag value is 'O' the function should return
all the characters at even place in the input string
• If the flag value is 'l'the function should return
all the characters at odd place in the input string
Example Output:
• Function 1("TRACXN",0) = "RCN"
• Function 1("TRACXN", 1) = "TAX"​

Answers

Answered by ibolbam
29

Explanation:

this declaration is wrong:

char *str[41];

you're declaring 41 uninitialized strings. You want:

char str[41];

then, scanf("%40s" , str);, no & and limit the input size (safety)

then the loop (where your while (str[i]<41) is wrong, it probably ends at once since letters start at 65 (ascii code for "A"). You wanted to test i against 41 but test str[i] against \0 instead, else you get all the garbage after nul-termination char in one of odd or even strings if the string is not exactly 40 bytes long)

while (str[i]) {

if (i % 2 == 0) {

odd[j++] = str[i];

} else {

even[k++] = str[i];

}

i++;

}

if you want to use a pointer (assignement requirement), just define str as before:

char str[41];

scan the input value on it as indicated above, then point on it:

char *p = str;

And now that you defined a pointer on a buffer, if you're required to use deference instead of index access you can do:

while (*p) { // test end of string termination

if (i % 2 == 0) { // if ((p-str) % 2 == 0) { would allow to get rid of i

odd[j++] = *p;

} else {

even[k++] = *p;

}

p++;

i++;

}

(we have to increase i for the even/odd test, or we would have to test p-str evenness)

aaaand last classical mistake (thanks to last-minute comments), even & odd aren't null terminated so the risk of getting garbage at the end when printing them, you need:

even[k] = odd[j] = '\0';

(as another answer states, check the concept of even & odd, the expected result may be the other way round

Similar questions
History, 11 months ago