简体   繁体   中英

C program to find frequency of a character from a string

why the code doesn't work?? anything wrong with that loop?? if then what should be answer? and why it can't be. Please make me clear. :)

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

int main()
{
    char s[1000];
    int i,j=1,x,y; char k,l;

    gets(s);
    l = strlen(s);
    scanf("%c",&k);
    for(s[i]=0; s[i]<l; i++)
    {
        if(s[i]=='k')
            j++;
    }
    printf("\n%c is %d time(s) in string",k,j);


    return 0;
}

please check this way. you are matching letter 'k' instead of variable.

if(s[i]==k)

First use l = strlen(s)+1; instead of l = strlen(s); . Then change s[i]=0 in for loop to i = 0; and use i<l instead of s[i]<l .

Also, change if(s[i]=='k') to if(s[i]==k) .

Full example:

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

int main()
{
    char s[1000];
    int i,j=0,l; 
    char k;

    gets(s);
    l = strlen(s)+1;
    scanf("%c",&k);

    for(i=0; i<l; i++)
    {
        if(s[i]== k)
            j++;
    }
    printf("\n%c is %d time(s) in string",k,j);
    return 0;
}

The datatype of the variable l is char.It should be declared of the type int. You have initialised j with value 1 when it should have been initialised with 0 . The for loop is incorrect. Instead of s[i] use i and check the condition i < l . And finally in the if condition replace 'k' by k I hope this will help you get desired result

I can see you made many mistakes, I will list them up:

  • if(c[i] == 'k') should be if(c[i] == k)
  • You should use fgets instead of gets, gets is not stable or safe
  • Please do use MACRO for 1000 in char s[1000]
  • for(s[i]=0; s[i] < l; i++) is wrong because you should be iterating with i so it should be for( i = 0; i < length; ++i)

The code example:

#include <stdio.h>     /* printf */
#include <stdlib.h>    /* fgets  */
#include <string.h>    /* strlen */

#define MAX_LINE_LENGTH  1000

int main()
{
    char k;
    char line[MAX_LINE_LENGTH];
    size_t count, length, i;

    /* Reading a line/string */
    printf("Please enter a line : ");
    if (!fgets (line, MAX_LINE_LENGTH, stdin)) 
    { 
           /* handle error */ 
           printf("Failed to read input\n");
           return 1;
    }

    /* calculating the length */
    length = strlen(line) + 1;

    /* Reading the letter to count its occurences */
    printf("Please enter a letter : ");
    scanf("%c",&k);

    /*
     * Counting the occurences of k in a string/line
     */
    count = 0;
    for(i = 0; i < length; ++i)
    {
        if(line[i] == k)
        {
            ++count;
        }
    }

    printf("%c is %d time(s) in string\n", k, count);

    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM