Problem in C language, issue with prime numbers

Asked

Viewed 350 times

2

I am solving exercises, in C language, on vectors. The exercise is as follows: Make an algorithm that uses a menu with the following options: sort an ascending 5-position vector, sort a descending 5-position vector, and store the prime numbers in a vector 2. The problem occurs when the third option of the menu is selected, being that of storing the primes in a second vector. I wanted you to take a look at my 'case 3' switch and point out the error(s). Thank you in advance.

#include<stdio.h>
#include<stdlib.h>
#include<locale.h>
#include<math.h>

int main(){
setlocale(LC_ALL,"portuguese");
int op, vetor[5], i, x, y, w=0, aux, cont=0, primos[5]; 

    do{

        printf("\n      Menu    \n");
        printf("0. Sair. \n");
        printf("1. Ordenar de forma crescente. \n");
        printf("2. Ordenar de forma decrescente. \n");
        printf("3. Armazenar os números primos. \n");

        printf("Digite a opção desejada: ");
        scanf("%d", &op);

        if(op==0){

            break;

        }

        system("cls");

        switch(op){

            case 1: printf("Você escolheu ordenar de forma crescente. \n");

                    for(i=0; i<5; i++){

                        printf("Digite o elemento [%d]: ", i);
                        scanf("%d", &vetor[i]);

                    }

                    for(i=0; i<5; i++){
                        for(x=0; x<=5; x++){

                            if(vetor[i]<vetor[x]){

                                aux = vetor[i];
                                vetor[i] = vetor[x]; 
                                vetor[x] = aux;

                            }                               
                        }                           
                    }

                    for(i=0; i<5; i++){
                        printf("\nv[%d] = %d\n", i, vetor[i]); 
                    }

                    break;

            case 2: printf("Você escolheu ordenar de forma decrescente. \n");

                    for(i=0; i<5; i++){

                        printf("Digite o elemento [%d]: ", i);
                        scanf("%d", &vetor[i]);

                    }

                    for(i=0; i<5; i++){
                        for(x=0; x<=4; x++){

                            if(vetor[x]<vetor[i]){

                                aux = vetor[x];
                                vetor[x] = vetor[i]; 
                                vetor[i] = aux;

                            }                               
                        }                           
                    }

                    for(i=0; i<5; i++){
                        printf("\nv[%d] = %d\n", i, vetor[i]); 
                    }

                    break;

            case 3: printf("Você escolheu armazenar os números primos. \n");

                    for(i=0; i<5; i++){

                        printf("Digite o elemento [%d]: ", i);
                        scanf("%d", &vetor[i]);

                    }

                    for(i=0; i<5; i++){
                        for(y=1; y<=vetor[i]; i++){

                            if(vetor[i]%y==0){
                                cont++;
                            }
                            w=0;
                            if(cont==2){

                                primos[w] = vetor[i];
                                w++; 

                            }


                        }

                        for(i=0; i<5; i++){

                            printf("primo[%d] = %d\n", i, primos[i]);

                        }

                    break;



                    }

        }

        }while(op!=0);  

system("pause");
return 0;
}
  • 2

    But what’s the problem?

1 answer

4

Well, first I recommend you to learn how to code properly. Another point is that you exaggerate the use of blank lines.

But as for the mistakes, the first is in the case 1:

for(x=0; x<=5; x++){

Ali, the <=5 should be < 5 or else <= 4.

Now, let’s take a look at your case 3. I already tidied up the excess of blank lines and arranged the indentation to understand better:

printf("Você escolheu armazenar os números primos. \n");

for (i = 0; i < 5; i++) {
    printf("Digite o elemento [%d]: ", i);
    scanf("%d", &vetor[i]);
}

for (i = 0; i < 5; i++) {
    for (y = 1; y <= vetor[i]; i++) {
        if (vetor[i] % y == 0) {
            cont++;
        }
        w = 0;
        if (cont == 2) {
            primos[w] = vetor[i];
            w++; 
        }
    }

    for (i = 0; i < 5; i++) {
        printf("primo[%d] = %d\n", i, primos[i]);
    }
    break;
}

And look at what the correct identation has revealed to us: You have a loop iterating on i within another iterating loop also in the i. Also, the fact that the break be inside the for when he should be interrupting the switch instead of for shows there’s something very wrong with that. The lesson learned here is to avoid excess blank lines and correct ident, as these two simple steps were enough to make this problem obvious.

Okay, let’s fix this. The first loop that contains the scanfs is correct. Already the second loop is closing very late, as it should contain only the internal loop that iterates in the y and nothing else. So, your code for the time being:

printf("Você escolheu armazenar os números primos. \n");

for (i = 0; i < 5; i++) {
    printf("Digite o elemento [%d]: ", i);
    scanf("%d", &vetor[i]);
}

for (i = 0; i < 5; i++) {
    for (y = 1; y <= vetor[i]; i++) {
        if (vetor[i] % y == 0) {
            cont++;
        }
        w = 0;
        if (cont == 2) {
            primos[w] = vetor[i];
            w++; 
        }
    }
}

for (i = 0; i < 5; i++) {
    printf("primo[%d] = %d\n", i, primos[i]);
}
break;

Another problem is the w. The purpose of w is to mark how many cousins you have found. But the inner loop (the y) checks every possibility of division and for each one it returns the w to zero again, which causes it to always be stuck at zero at the end. In fact, the w = 0; should be before this tie.

By the way, looking at the inner loop, you initialize y = 0, checks the stopping condition with y <= vetor[i], but increases with i++ instead of y++. Obviously, the correct is to increase with y++.

Looking at the if, the purpose of it is to register that a cousin has only been found if exactly two divisors have been found in the loop of the y. However, this means that he should be after the loop of y, and not inside.

The last for traverses the array with the found cousins. How to know how many cousins were found? Well, that’s the purpose of w. That means the last for should iterate for w array elements, not by 5.

And finally, the variable cont should have its value reset to zero in each iteration of the intermediate loop that finds out if the number is prime. After all, if this value is not reset, it accumulates from one number to another and between different executions of case 3 and that makes no sense. Therefore, it has to be set at zero at the beginning of the intermediate loop.

So here’s how your corrected code looks:

printf("Você escolheu armazenar os números primos. \n");

for (i = 0; i < 5; i++) {
    printf("Digite o elemento [%d]: ", i);
    scanf("%d", &vetor[i]);
}

w = 0;
for (i = 0; i < 5; i++) {
    cont = 0;
    for (y = 1; y <= vetor[i]; y++) {
        if (vetor[i] % y == 0) {
            cont++;
        }
    }
    if (cont == 2) {
        primos[w] = vetor[i];
        w++; 
    }
}

for (i = 0; i < w; i++) {
    printf("primo[%d] = %d\n", i, primos[i]);
}
break;
  • I appreciate your advice regarding identation and the use of the lines, I had no awareness about identation and as I am beginner, I will soon learn about. The lines I use for the sake of personal organization, I can not pay attention when the code is very "stuck", but I will improve in this aspect.

  • in relation to the code itself, I made the appropriate modifications and continues to give error. Previously, the result fell into trash, and now displays absolutely nothing.

  • @Milenateixeira Reply edited and corrected. Is that in for of y you were using i++ instead of y++ and this mistake had passed me unnoticed.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.