C Program to Display All Characters Present in the Prime Position of a String

This is a C Program to display the characters in prime position of a given string.

Problem Description

This program prints the characters in prime position of a given string.

Problem Solution

1. Take a string as input.
2. Find the number which gets divided only once and consecutively print the character of the obtained position.

Program/Source Code

Here is source code of the C Program to display the characters in prime position a given string. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C Program to Display the Characters in Prime Position a given String
  3.  */
  4. #include <stdio.h>
  5. #include <string.h>
  7. void main()
  8. {
  9.     int i, j, k, count = 0;
  10.     char str[50];
  12.     printf("enter string\n");
  13.     scanf("%[^\n]s", str);
  14.     k = strlen(str);
  15.     printf("prime characters in a string are\n");
  16.     for (i = 2;i <= k;i++)
  17.     {    
  18.         count = 0;
  19.         for (j = 2;j <= k;j++)
  20.         {
  21.             if (i % j == 0)
  22.             {
  23.                 count++;
  24.             }
  25.         }
  26.         if (count == 1)
  27.         {
  28.             printf("%c\n", str[i - 1]);
  29.         }
  30.     }
  31. }
Program Explanation

1. Take a string as input and store it in the array str[].
2. Store the length of the input string in the variable k.
3. Use two loops to divide the numbers upto the value of k.
4. Increment the variable count when the remainder is zero.
5. If the variable count is equal to 1, then print the corresponding character.

Runtime Test Cases
enter string
welcome to sanfoundry c-programming class!
prime characters in a string are

Sanfoundry Global Education & Learning Series – 1000 C Programs.

Here’s the list of Best Books in C Programming, Data-Structures and Algorithms

If you wish to look at programming examples on all topics, go to C Programming Examples.

If you find any mistake above, kindly email to [email protected]

Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.