Any solution shorter than this ?

H

HumbleWorker

COUNT THE NUMBER OF a IN the sting cX below

PROPOSED SOLUTION IS ->
int main()
{
char cX[] = "ababcabcdabcaba", * k = cX;
int numA = 0;

while (*k && ('a' == *k++ ? ++numA : 1));

printf ("Number of a's = %u\n", numA);

return 0;
}
 
J

John Gordon

In said:
COUNT THE NUMBER OF a IN the sting cX below
PROPOSED SOLUTION IS ->
int main()
{
char cX[] = "ababcabcdabcaba", * k = cX;
int numA = 0;
while (*k && ('a' == *k++ ? ++numA : 1));
printf ("Number of a's = %u\n", numA);
return 0;
}

I can't think of a significantly shorter solution, aside from
shenanigans like shortening variable names.

However, from a code clarity viewpoint, the while loop seems gratuitously
complex. This is easier to understand:

for(k = cX; *k; k++)
if (*k == 'a')
numA++;

And of course you haven't included the appropriate headers such as
stdlib.
 
I

Ike Naar

COUNT THE NUMBER OF a IN the sting cX below

PROPOSED SOLUTION IS ->
int main()

int main(void)
{
char cX[] = "ababcabcdabcaba", * k = cX;
int numA = 0;

while (*k && ('a' == *k++ ? ++numA : 1));

while (*k) if ('a' == *k++) ++numA;
 
E

Eric Sosman

In said:
COUNT THE NUMBER OF a IN the sting cX below
PROPOSED SOLUTION IS ->
int main()
{
char cX[] = "ababcabcdabcaba", * k = cX;
int numA = 0;
while (*k&& ('a' == *k++ ? ++numA : 1));
printf ("Number of a's = %u\n", numA);
return 0;
}

I can't think of a significantly shorter solution, aside from
shenanigans like shortening variable names.

Shortest I can think of is

#include<stdio.h>
int main(){puts("Number of a's = 6");}

.... but that might fall afoul of the "Letter, not spirit" clause.
However, from a code clarity viewpoint, the while loop seems gratuitously
complex. This is easier to understand:

for(k = cX; *k; k++)
if (*k == 'a')
numA++;

Or even

numA += *k == 'a';
And of course you haven't included the appropriate headers such as
stdlib.

He's missing <stdio.h>, but why would he need <stdlib.h>?
 
J

John Gordon

He's missing <stdio.h>, but why would he need <stdlib.h>?

I rewrote the sample program to return EXIT_SUCCESS instead of 0, and
stdlib is needed for that. But you're right, the sample program doesn't
need it.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top