This is a program to find the number of characters in a string. But it counts the wrong number of characters. Is it counting the white space too ? Even if that is true how can the total number be 89 ? (see output below)
#include <stdio.h>
#include <conio.h>
void occurrence(char str[100], char ch)
{
int count=0,max =0,i;
for(i=0;i<=100;i++)
{
if(str[i]!='\0')
{
max = max + 1;
if(str[i]==ch)
{
count = count + 1;
}
}
}
printf("\nTotal Number of characters : %d\n",max);
printf("\nNumber of Occurrences of %c : %d\n",ch,count);
}
int main(void)
{
void occurrence(char [], char);
int chk;
char str[100], ch, buffer;
clrscr();
printf("Enter a string : \n");
gets(str);
printf("Do you want to find the number of occurences \nof a particular character (Y = 1 / N = 0) ? ");
scanf("%d", &chk);
do
{
if (chk==1)
{
buffer = getchar(); //dummy varaiable to catch input \n
printf("Enter a Character : ");
ch = getchar();
occurrence(str,ch);
printf("\n\nDo you want to check the number of occurences \nof another character (Y = 1 / N = 0) ? ");
scanf("%d", &chk);
}
else
{
exit();
}
}
while(chk);
return 0;
}

There are two important things wrong with the
forloop that counts characters:It goes from 0 to 100, when it should go from 0 to 99. If you allocate a 100-element array, then the index of the highest element is 99, for a total of a hundred elements. Traditionally the exit condition for the loop would be
i < 100, noti <= 100.It keeps going after the ‘\0’ is found. The ‘\0’ character marks the end of the string, and you should not count any characters after it. Some of the characters after the ‘\0’ may themselves be ‘\0’s, and so you won’t count them; but there could be any other kind of garbage there as well, and those will mess up your count. You must figure out how to change your
forloop to exit as soon as the ‘\0’ character is found, and not count anything else after that point.