Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Error in my code in my C program --- The goal is to print the sum of sophie germ

ID: 3818478 • Letter: E

Question

Error in my code in my C program ---

The goal is to print the sum of sophie germain numbers under a certain range. I'm having trouble accessing the ''i'' values that I need to count in order to establish how many prime numbers I have under a certain range. This is my code now and it doesn't give me access to the i values to count. I underlined the problem.

i.e if I were to enter r = 2, there should be an output value of 3,10 for the count.

#include
#include
#include


int main() {
    int prime, flag;
    int r, i,n,k,j;
    int low, high, count, range;
    int sg;
    high = pow(10,r);
    int A[high];
   
   
//Determining what the range will be    
printf("Please enter integer r ");
scanf("%d", &r);
printf(" ");

/*Finding prime numbers in range*/
high = pow(10,r);

for (i = 2; i <= high; i++){
    flag = 0;
   
    for (n = 2;n <= i/2; n++){
        if (i%n==0){
            flag++;
            break;
        }
    }
    if (flag == 0 && i!= 1){ //Testing for germain prime numbers
        sg = 2*i +1;
         for (k = 2;k <= i/2; k++){
        if (sg%k==0){
            flag++;
            break;
        }
       
       
    }
    if(flag==0 && sg!= 1){
            printf("-%d- ", i);
           
            }
         
        }
       

}
for (j = 1; j <= r; j++){
            range = pow(10,j);
     
           
           
           if (i > range){
               count++;
               printf("%d ", count);     

       
   
   
    }
   

  
        }
    return 0;
}

Explanation / Answer

As per my understanding i is defined in intial part. Also it is not been initialized to 0 (i=0) and so it will be containing a garbage value and that is the main reason for issue you are getting while accessing i.

The best solution to this problem is to define i locally in for loop. This is the most followed / adopted practise due to problem faced as experienced by you.

Hope this solves the problem. Declare local variable used in for loop going out of scope after ending of for loop in which it is declared and you won't have the problem you are currently experiencing.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote