Failed_Noob
Failed_Noob

Reputation: 1357

Program to show the number of characters in a string

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;
}

enter image description here

Upvotes: 0

Views: 14923

Answers (3)

Kamal
Kamal

Reputation: 1

This will give you correct output.

void occurrence(char str[100], char ch)

{ int count=0,max = 0,i = 0;

while(str[i]!='\0')
{
    max = max + 1;

    if( str[i] == ch )
    {
    count = count + 1;
    }
    i++;
}

}

Upvotes: 0

K-ballo
K-ballo

Reputation: 81409

Yes, whitespace is a character. Also are characters each of the 100 elements in your array. You are counting everything but nulls, sp I guess you have 11 nulls. Also, your for loop is off by one.

Upvotes: 0

Ernest Friedman-Hill
Ernest Friedman-Hill

Reputation: 81724

There are two important things wrong with the for loop that counts characters:

  1. 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, not i <= 100.

  2. 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 for loop to exit as soon as the '\0' character is found, and not count anything else after that point.

Upvotes: 2

Related Questions