For structure not working properly, not printing the phrase after a non prime number

So, im developing an algorithm that shows if a number is a prime number or not. But when i type the first non prime number, it stops recognizing what is a prime number (or at least stops printing, idk). pls help

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

void main(){
    int num, i, p, soma=0;

    //Repeticao para o algoritmo todo
    for(i=1; i<=100; i++){
        printf("\nDigite o %do numero: \n",i);
        scanf("%i", &num);
        //Decobrir se eh primo ou nao
        for(p = 2; p <= num / 2; p++) {
            if(num % p==0){
                soma++;
            }
        }
        //saida
        if (soma == 0){
            printf("%d eh um numero primo!", num);
        }
    }
    system("pause");
}

Upvotes: 0

Views: 46

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 310970

At least the variable soma must be declared within the outer for loop before the inner for loop

//Repeticao para o algoritmo todo
for(i=1; i<=100; i++){
    int soma = 0;

But in any case the approach is incorrect because if the user will enter 0 or 1 (that are not prime numbers) your program will say that it is a prime number. Also It is evident that any even number except 2 is not a prime number.

Also declare variables where they are used. And the variable num should be declared as having the type unsigned int.

I would rewrite the loops the following way

//Repeticao para o algoritmo todo
for( int i=1; i<=100; i++){
    unsigned int num;

    printf("\nDigite o %do numero: \n",i);
    scanf("%u", &num);

    int soma = num % 2 == 0 ? num == 2 : num != 1;

    //Decobrir se eh primo ou nao
    for( unsigned int p = 2; soma &&  p <= num / p; p++) {
        if(num % p==0) soma = 0;
    }
    //saida
    if ( soma ){
        printf("%d eh um numero primo!", num);
    }
}

Upvotes: 1

Eric Postpischil
Eric Postpischil

Reputation: 222640

You never reset soma to zero. The first time a factor is found, soma is incremented. Forever after that, it is non-zero, so the test in if (soma == 0) is never true.

You should reset soma to zero for each new number to be tested.

One method to help avoid mistakes like this is not to declare variables before you need them:

// You do not need any of these here:
//    int num, i, p, soma=0;

// You can declare i here:
    //Repeticao para o algoritmo todo
    for(int i=1; i<=100; i++){
// You need num here:
        int num;
        printf("\nDigite o %do numero: \n",i);
        scanf("%i", &num);
        //Decobrir se eh primo ou nao
// Now you need soma:
        int soma = 0;
// You need p here:
        for(int p = 2; p <= num / 2; p++) {
            if(num % p==0){
                soma++;
            }
        }
        //saida
        if (soma == 0){
            printf("%d eh um numero primo!", num);
        }
    }

Upvotes: 2

Related Questions