Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

closed The following code doesn't show if a number is prime or not, where is the problem?

–2 votes
asked Jun 7, 2018 by KAUSTAV (720 points)
closed Jun 30, 2018 by KAUSTAV
#include <stdio.h>

int main()
    int n,i,sum =0;
    printf("Enter number = ");
            sum = sum + n + i;
    if(sum = 2*n+1)
    printf("Prime number");
    else printf("Not a prime number");
closed with the note: the answer by the below user is sufficient

1 Answer

0 votes
answered Jun 8, 2018 by Matheus Jahnke (440 points)
selected Jun 10, 2018 by KAUSTAV
Best answer
There is a "problem" in:
sum = 2*n+1(on the "if" just after the loop)
sum = 2*n+1 actually sets the value of sum to 2*n+1, and then evaluates if that is "true"(different from 0) or false(equals 0) .This is not "wrong" in the sense that it is actually valid code, however it is not intended behavior. To fix it you should put "==" instead of "=", because that will actually compare the numbers;
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.