Thursday, October 30, 2014

BETTER C PROGRAM



Find the Length of a String without using the Built-in Function

#include 
#include 
void main()
{
    char string[50];
    int i, length = 0;
    clrscr();
    printf("Enter a string \n");
    gets(string);
        for (i = 0; string[i] != '\0'; i++)
    {
        length++;
    }
    printf("The length of a string is the number of characters in it \n");
    printf("So, the length of %s = %d\n", string, length);
    getch();
}

Output

Enter a string
Sanfoundry
The length of a string is the number of characters in it
So, the length of Sanfoundry = 10

Find the Frequency of the Word ‘the’ in a given Sentence

#include 
#include  
void main()
{
    int count = 0, i, times = 0, t, h, e, space;
    char string[100];
    clrscr();
    puts("Enter a string:");
    gets(string);
    while (string[count] != '\0')
    {
        count++;
    }
   
    for (i = 0; i <= count - 3; i++)
    {
        t =(string[i] == 't' || string[i] == 'T');
        h =(string[i + 1] == 'h' || string[i + 1] == 'H');
        e =(string[i + 2] == 'e'|| string[i + 2] == 'E');
        space =(string[i + 3] == ' ' || string[i + 3] == '\0');
        if ((t && h && e && space) == 1)
            times++;
    }
    printf("Frequency of the word 'the' is %d\n", times);
    getch();
}

Output

Enter a string:
The gandhi jayanthi is celeberated on october 2 is the day
that he has born.
Frequency of the word 'the' is 2

Read a String and find the Sum of all Digits in the String

#include 
#include 
void main()
{
    char string[80];
    int count, nc = 0, sum = 0;
    clrscr();
   printf("Enter the string containing both digits and alphabet \n");
    scanf("%s", string);
    for (count = 0; string[count] != '\0'; count++)
    {
        if ((string[count] >= '0') && (string[count] <= '9'))
        {
            nc += 1;
            sum += (string[count] - '0');
        }
    }
    printf("NO. of Digits in the string = %d\n", nc);
    printf("Sum of all digits = %d\n", sum);
    getch();
}

Output

Enter the string containing both digits and alphabet
hello100
NO. of Digits in the string = 3
Sum of all digits = 1

No comments:

Post a Comment