Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrote a program to print prime numbers, How do I make it better?

I started learning C the previous day and I wrote a program to print within a given range. Minimum and Maximum of range is given by user.

#include <stdio.h>
int check(int number)
{
    if (number == 1)
    {
        return 0;
    }
    int count = 2;
    while (count < number)
    {
        if (number%count == 0)
        {
            return 0;
        }
        count++;
    }
    return 1;
}
void main()
{
    int i,min,max;
    printf("Enter start of range: ");
    scanf("%d",&min);
    printf("Enter end of range: ");
    scanf("%d",&max);
    for (i = min;i < max;i++)
    {
        if (check(i) == 1)
        {
            printf("%d\n",i);
        }
    }
}

I am getting the output as expected, but I want to know if there is any better way to return 0 if the number entered is 1 or not as it appears like duct tape code to me.

I inserted this block of code before the program goes through a while loop to check for numbers>1.

if (number == 1)
    {
        return 0;
    }

I am getting the output as expected but I want to know if there is a better way than just placing an if statement.

My question is different from the suggested question because I want to know if there is any better way to figure out if 1 is not a prime number. The suggested question was using an if statement, just like how I did. If statement was present in suggested question, I wanted to know any other alternatives that does not use the if statement to check for 1.

I find my question different from the suggested question.

like image 784
nkminion Avatar asked Oct 16 '25 04:10

nkminion


1 Answers

More useful if you want to become a c programmer ... What happens if I enter "frog" as the min value . Now you enter the world of error detection and recovery

like image 148
pm100 Avatar answered Oct 17 '25 19:10

pm100



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!