coderfromhell
coderfromhell

Reputation: 455

No compilation errors but not getting any output in C

This has been bugging me a lot. It is a simple function to detect a prime number but I'm not getting any output on my console, despite there being no compilation errors. Can someone please detect what is wrong with this code?

#include<stdio.h>
int isprime(int);

int main()
{
    int n;
    scanf("%d", &n);

    if (isprime(n))
        printf("Yes");
    else
        printf("No");

    return 0;
}

int isprime(int num)
{
    int flag = 1;

    for(int i = 2; i <= num/2; i++)
    {
        if(num % i == 0)
        {
            flag = 0;
            break;
        }
    }

    return flag;
}

Upvotes: 0

Views: 105

Answers (3)

i486
i486

Reputation: 6563

I bet you don't see the output but it is shown. There is no new line and command prompt follows the answer like NoC:\> instead of C:\>.

Upvotes: 0

Vlad from Moscow
Vlad from Moscow

Reputation: 311038

For starters the function isprime is invalid. It returns 1 for the non-prime number 1.:)

And the function should be declared at least like

int isprime( unsigned int num );

As for your question then the output buffer is not flushed until the new line character is not encountered.

Write instead

if (isprime(n))
    printf("Yes\n");
else
    printf("No\n");

or

if (isprime(n))
    puts("Yes");
else
    puts("No");

Upvotes: 0

John
John

Reputation: 1032

There's nothing wrong with the program. The output is not formatted well due to missing new lines, so perhaps by adding them you'd be able to see something as the output may be right at the beginning of the console prompt.

int n;
printf("Input a number: ");
scanf("%d", &n);

if (isprime(n))
    printf("Yes\n");
else
    printf("No\n");

Upvotes: 2

Related Questions