This blog is under construction

Sunday, 14 July 2013

C program to print the characters at even and odd positions of a string

Write a C program to print the characters at even and odd positions of a string.


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

  int main() {
        char string[100], even[100], odd[100], i, j, k;

        i = j = k = 0;

        /* get the input string from the user */
        printf("Enter your input string:");
        fgets(string, 100, stdin);
        string[strlen(string) - 1] = '\0';

        /* printing the input string */
        printf("Given Input string:%s\n", string);

        /*
         * print the characters at odd position in odd array.
         * Similarly, print the characters at even position in
         * even array.
         */
        while (string[i] != '\0') {
                if (i % 2 == 0) {
                        odd[j++] = string[i];
                } else {
                        even[k++] = string[i];
                }
                i++;
        }

        /* terminating even and odd string with NULL */
        odd[j] = even[k] = '\0';

        /* print the charactersa at odd position and even positions */
        printf("Characters at odd position: %s\n", odd);
        printf("Characters at even position: %s\n", even);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your input string:HelloWorld
  Given Input string:HelloWorld
  Characters at odd position: Hlool
  Characters at even position: elWrd


2 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. "I very much enjoyed this article.Nice article thanks for given this information. i hope it useful to many pepole.php jobs in hyderabad.
    "

    ReplyDelete