CodeFreak
CodeFreak

Reputation: 110

How to count the amount of times a specific character appears in an array in C?

So I am trying to count the amount of times a specific character occurs in my program. For example, If I entered, ABCDA, I want the program to print, "There are 2 A's." My code is as follows:

int main(void)
{
  char array[10000];
  printf("Enter input: \n");
  scanf("%s", array);
  printf("Array entered is: %s\n", array);

  char A;          //variable I want to count
  char *k          //used just to loop
  int a_counter;   //number of times A, occurs 

  fgets(array, sizeof(array), stdin);
  A = fgetc(stdin);
  a_counter = 0;

  for(k = array; *k; k++)
  {
    if (*k == A)
    {
      a_counter++;
    }
   }
   printf("Number of A's: %d\n", a_counter);
   return 0;
  }

The following loop was found on another forum which also attempted to count the a specific character but I can not seem get mine to work. Is my approach at this wrong? I also would like to get this all out of main but I am also confused on how to do so. I appreciate any help that is given. Thank you.

New Attempt at the count loop that is also not working. I got rid of fgets because it was confusing me.

    int a_counter = 0;
    if (array == 'A')
    {
       a_counter++;
    }
    printf("Number of A's: %d\n", a_counter);

Attempt after @bjorn help.

#include <stdio.h>
int main(void)
{
  char array[1000];
  printf("Enter input: \n);
  scanf("%s", array);
  printf("Input is: %s\n", array);

  int c,n =0;
  while((c = getchar()) != EOF)
    if (c = 'A')
      n++;
  printf("Amount of A's is: %d\n", n);
  return 0;
 }

Upvotes: 0

Views: 133

Answers (1)

Bjorn A.
Bjorn A.

Reputation: 1178

KISM - Keep it simple, mate :) Your code is way too complicated for a simple task. Here's an alternative, which hopefully illustrates what I mean:

#include <stdio.h>

int main(void)
{
    int c, n = 0;

    while ((c = getchar()) != EOF)
        if (c == 'a')
            n++;

    printf("Where were %d a characters\n", n);
    return 0;
}

Upvotes: 1

Related Questions