Saturday 17 October 2015

Check whether a given Character is present in a String, Find Frequency & Position of Occurrence

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

int main()
{
    char a, word[50];
    int i, freq = 0, flag = 0;

    printf("Enter character: ");
    scanf("%c", &a);
    printf("Now enter the word: ");
    scanf("%s", word);
    printf("Positions of '%c' in %s are: ", a, word);
    for (i = 0; i < strlen(word); i++)
    {
        if (word[i] == a)
        {
            flag = 1;
            printf("%d  ", i + 1);
            freq++;
        }
    }
    if (flag)
    {
        printf("\nCharacter '%c' occured for %d times.\n", a, freq);
    }
    else
    {
        printf("None\n");
    }

    return 0;
}

Thursday 15 October 2015

Accepts two Strings & Compare them

#include <stdio.h>

void main()
{
    int count1 = 0, count2 = 0, flag = 0, i;
    char string1[10], string2[10];

    printf("Enter a string:");
    gets(string1);
    printf("Enter another string:");
    gets(string2);
    /*  Count the number of characters in string1 */
    while (string1[count1] != '\0')
        count1++;
    /*  Count the number of characters in string2 */
    while (string2[count2] != '\0')
        count2++;
    i = 0;

    while ((i < count1) && (i < count2))
    {
        if (string1[i] == string2[i])
        {
            i++;
            continue;
        }
        if (string1[i] < string2[i])
        {
            flag = -1;
            break;
        }
        if (string1[i] > string2[i])
        {
            flag = 1;
            break;
        }
    }
    if (flag == 0)
        printf("Both strings are equal \n");
    if (flag == 1)
        printf("String1 is greater than string2 \n", string1, string2);
    if (flag == -1)
        printf("String1 is less than string2 \n", string1, string2);
}

Sunday 11 October 2015

Printing Random Numbers

#include <stdio.h>#include <stdlib.h> int main() {  int c, n;   printf("Ten random numbers in [1,100]\n");   for (c = 1; c <= 10; c++) {    n = rand() % 100 + 1;    printf("%d\n", n);  }   return 0;}

Counting Frequency of character

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

int main()
{
   char string[100];
   int c = 0, count[26] = {0};

   printf("Enter a string\n");
   gets(string);

   while (string[c] != '\0')
   {
     

      if (string[c] >= 'a' && string[c] <= 'z') 
         count[string[c]-'a']++;

      c++;
   }

   for (c = 0; c < 26; c++)
   {
      

      if (count[c] != 0)
         printf("%c occurs %d times in the entered string.\n",c+'a',count[c]);
   }

   return 0;
}