TechTorch

Location:HOME > Technology > content

Technology

How to Write C Code to Find the Index of the Second Occurrence of a Prime Number

March 27, 2025Technology3306
How to Write C Code to Find the Index of the Second Occurrence of a Pr

How to Write C Code to Find the Index of the Second Occurrence of a Prime Number

Suppose we have an array of 25 prime numbers. We want to find out the index number of the second occurrence of the prime number 7. In this article, we will provide a step-by-step method to write the appropriate C code for this task.

Step-by-Step Method

The following steps will guide you through the process of writing the C code:

Declare an array of size 25 called prime. Declare an integer type variable called p. Since we want to find out the index number of the second occurrence of 7, initialize p with 7. Declare an integer type variable called cnt and initialize it with 0. Use this variable to track how many times you have encountered 7 in the prime array. Now iterate through the whole prime array and check the current element whether it is equal to p (in this case, p 7) or not. If it is equal to p, increase the value of cnt by 1 and check that whether the value of cnt is 2 or not. If the value of cnt is 2, print the value of i (the index).

Source Code in C

Here is the C code for the above method:

#include stdio.hint main() {    int prime[25]  {3, 7, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127};    int cnt  0;    int p  7;    for (int i  0; i  25; i  ) {        if (prime[i]  p) {            cnt  ;            if (cnt  2) {                printf("The index of the second occurrence of 7 is: %d
", i);                break;            }        }    }    return 0;}

Explanation of the Code

The code begins with the #include stdio.h statement to include the standard input-output library. This is necessary for using the printf function to print output to the console.

In the main function, we declare the prime array and initialize it with a list of 25 prime numbers. The variable cnt is initialized to 0. The variable p is assigned the value 7, as we are looking for the second occurrence of this prime number.

The for loop iterates through the prime array. Inside the loop, the current element prime[i] is checked against the value of p. If they are equal, the cnt counter is incremented. Once cnt reaches 2, the index i is printed, and the loop is exited using the break statement.

This C code will output the index of the second occurrence of 7 in the prime array, which is typically 11 (considering 0-based indexing).

Feel free to run this code on your local machine or in an online C compiler to verify its functionality.

References:
[1] "Prime Numbers in C" on GeeksforGeeks
[2] "C Programming: For Loop" on TutorialsPoint