Anon
Anon

Reputation: 33

Breaking out of a loop without a break statement [C]

How do you break out of a loop without a break statement? My professor HATES break statements and tells us not to use it. I'm just curious how would I break out of the while-loop if the number I got WAS NOT a prime number?

Here's my code:

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

/* Prototypes */
void primeChecker(int num1);

int main() {
    int num1 = 5;

    primeChecker(num1);

    return 0;
}

void primeChecker(int num1) {
    int i, flag = 0;

    printf("Enter a number to check for prime numbers: ");
    scanf("%d", &num1);

    /* Number to start with */
    i = 2;

    while (i <= num1/2) {
        if (num1 % i == 0) {
            flag = 1;
        } else {
            i++;
        }
    }

    if (flag == 0) {
        printf("The number is a prime number!");
    } else {
        printf("The number is NOT a prime number!");
    }
}

Upvotes: 1

Views: 2978

Answers (3)

BLE
BLE

Reputation: 161

Or

int prime = 1;
while (i <= num1/2 && prime) {
    if (num1 % i == 0){
       prime = 0;
    } else {
       i++;
    }
}

if(prime){
    printf("The number is a prime number!");
}else{
    printf("The number is not prime.");
}

I mean, you almost had it:

while (i <= num1/2 && !flag){

would have done the trick as well

Upvotes: 2

M Oehm
M Oehm

Reputation: 29126

In your case, you can use the value of flag as condition:

while (flag == 0 && i <= num1/2) {
    if (num1 % i == 0) {
        flag = 1;
    } else {
        i++;
    }
}

But that looks like Pascal rather than C. A better solution might be to refactor the loop so that it is in a separate function:

int is_prime(int num1)
{
    int i = 2;

    while (i <= num1/2) {
        if (num1 % i == 0) return 0;
        i++;
   }

   return 1;
}

This makes the code simpler and separates the input stuff in primeChecker from the actual prime checking.

Upvotes: 1

Haris
Haris

Reputation: 12270

You can do

while (i <= num1/2) {
    if (num1 % i == 0) {
        i = num1;
    } else {
        i++;
    }
}

This makes i larger then num1/2 and the while loop exits.

You probably need some more changes to make this work.

Upvotes: 1

Related Questions