This blog is under construction

Tuesday, 16 July 2013

C program to print nth character of any given string

Write a C program to print nth character of any given string.

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

  int main() {
        char str[128];
        int position;

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

        /* get the position from the user */
        printf("Enter the position of the character:");
        scanf("%d", &position);

        /* boundary check */
        if (position > strlen(str) || position < 1) {
                printf("No Character available at the "
                        "position %d\n", position);
                return 0;

        /* print the character at the given position */
        printf("Character at the position %d is %c\n",
                position, str[position - 1]);

        return 0;

  jp@jp-VirtualBox:~/$ ./a.out
  Enter your input string:God Bless You 
  Enter the position of the character:11
  Character at the position 11 is Y

No comments:

Post a Comment