Reputation: 39
I was writing a C Program to find if a number is prime or not. Everytime I run it and enter a number, the value of the input changes. PLease point out the loopholes.
#include<stdio.h>
#include<conio.h>
int main()
{
int x;
int y;
y=getchar();
for(x=2;x<y;++x){
if(y%x != 0 && y!=x)
printf(" THE NUMBER %d is A PRIME \n", y);
else
printf(" \r THE NUMBER %d IS NOT A PRIME", y);
break;
}
}
I use the Code::Blocks IDE with GCC Compiler
Upvotes: 3
Views: 207
Reputation: 1666
Well, you are calling getchar()
which is used to input a single character and this is what happens in your case:
getchar()
returns a character.int
.3
will be stored as 51
that is the reason input changes.What you need to do is to input an integer instead of character. Try this:
scanf("%d", &y);
Hope this helps.
Upvotes: 2
Reputation: 11209
getchar
returns the ASCII code of a single character. Consequently, your program picks up the ASCII code of the first character of the number you input and checks if it is prime.
Instead, you need to read an integer:
scanf("%d", &y);
The complete program:
#include<stdio.h>
#include<conio.h>
int main()
{
int x;
int y;
scanf("%d", &y);
for(x=2;x<y;++x){
if(y%x != 0 && y!=x)
printf(" THE NUMBER %d is A PRIME \n", y);
else {
printf(" \r THE NUMBER %d IS NOT A PRIME", y);
break;
}
}
}
Note: You can stop when x >= sqrt(y)
Upvotes: 5
Reputation: 122383
As the name implies, getchar()
gets a single character from standard input. For example, if you enter 3, the y
gets the ASCII code of the character '3'
, which is obviously not what you want.
Try scanf
:
scanf("%d", &y);
Upvotes: 5
Reputation: 61
First answers are correct about input for y:
scanf("%d", &y);
Also, please note that you should loop until square root of x, and not more if your want to optimize your algorithm (I won't demonstrate here why, it's a mathematical property).
#include <stdio.h>
#include <math.h>
// ...
int x;
int x_max;
int y;
scanf("%d", &y);
x_max = (int)floor(sqrt(y));
for(x=2;x<=x_max;++x){
// ...
Upvotes: 1