0

This is my code to find the number of times a character is found in an array:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>

int main(){
    int a[100],i,size,count;
    char c;

    printf("Enter the size of the array: ");
    scanf("%d", &size);

    printf("Enter the elements into the array: ");
    for(i=0;i<size;i++){
        scanf(" %c", &a[i]);
    }

    printf("Enter a character: ");
    scanf(" %c", &c);

    for(i=0;i<size;i++){
        if(a[i] == c){
            count++;
        }
    }

    printf("The number of occurrences of %c is %d.", c,count);

    return 0;
}

This is the output I am getting:

Enter the size of the array: 5
Enter the elements into the array: a q w w t
Enter a character: w
The number of occurrences of w is 2985985.

It is not printing the count value but some other value. What is wrong with my code and what does 2985985 mean?

1 Answers1

3

You invoked undefined behavior by

  • Passing data having wrong type to scanf(): %c expects char*, but &a[i] is int*.
  • Using an (indeterminate) value of non-static local variable count to calculation (incrementing).

The 2985985 is an indeterminate value created by adding something to an indeterminate value.

    int a[100],i,size,count;
    char c;

should be

    int i,size,count=0;
    char a[100],c;
MikeCAT
  • 73,922
  • 11
  • 45
  • 70