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
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);
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)
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.
Character is then converted into integer when you store it in variable of type int.
Hence that integer contains the ASCII of input character i.e. 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.
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){
// ...
Related
#include <stdio.h>
float result(int x, int y);
float result1(int x, int y);
int main()
{
int x,y;
char z;
printf("enter x:\n");
scanf("%d",&x);
printf("enter y:\n");
scanf("%d",&y);
printf("enter z:\n");
scanf("%s",&z);
if (z=='*')
{printf("the result is %.2f",result(x,y));}
else if (z=='/')
{printf("the result is %.2f",result1(x,y));}
else
{printf("there is an error");}
return 0;
}
float result(int x, int y)
{
float r=x*y;
return r;
}
float result1(int x, int y)
{
float r1=x/y;
return r1;
}
```so this is my code. my out put is ---
enter x:
4
enter y:
5
enter z:
*
the result is 0.00
Question was -
take two integer number from user x and y and a character z. the result should be in float.
if z is * then it should be x*y
if z is / then it should be x/y
if z is none of the above then it will return 0
you need to use function .
so it was the question, I know it can be done by switch case but I wanted to try if else.
The problem is this:
scanf("%s",&z);
The format specifier %s is used to read null-terminated strings. The variable z is a single character, it can only hold the empty string (which is only the null-terminator and nothing else).
Any other input will write somewhere in memory and lead to undefined behavior.
If you want to read a single character use the format %c. But be careful, the newline that the Enter key added from previous input will also be read with %c, and you need to ask scanf to skip and ignore it. This is done by adding a leading space to the format string.
So the call should be:
scanf(" %c",&z);
Hi I am studying C language by myself.
My question is, is there something I missed which need to know when working with scanf() that takes char value?
To practice do...while loop, I wrote some code like below but it did not work as I expected.
#include <stdio.h>
int main()
{
char y_or_n;
int x =1;
int y;
do
{
printf("ENTER A NUMBER\n");
scanf("%d", &y);
printf("THE NUMBER WILL BE ADDED TO x WHICH IS %d\n", x);
x = x+y;
printf("x TURNED INTO %d\n", x);
printf("KEEP DOING THIS?(y/n)\n");
scanf(" %s", &y_or_n);
printf("x is %d\n", x);
}
while(y_or_n =='y');
printf("GOOD BYE\n");
return 0;
}
For the first loop, it worked as I expected.
For example, when I entered 7, x turned into 8. But after scanf() was executed, value of x was changed into 0.
So from second loop, value of x changed temporarily into value of y and changed again into 0.
I guessed that there is something wrong with scanf() function and modified the code slightly: changed type of y_or_n into integer so that scanf() takes integer value.
The modified code is like below
include <stdio.h>
int main()
{
int y_or_n;
int x =1;
int y;
do
{
printf("ENTER A NUMBER\n");
scanf("%d", &y);
printf("THE NUMBER WILL BE ADDED TO x WHICH IS %d\n", x);
x = x+y;
printf("x TURNED INTO %d\n", x);
printf("KEEP DOING THIS?(y/n)\n");
scanf(" %d", &y_or_n);
printf("x is %d\n", x);
}
while(y_or_n ==1);
printf("GOOD BYE\n");
return 0;
}
This time the code worked as I expected.
Value of x was not changed into 0 even after an execution of scanf() and every time I entered a number that number was added to x.
If my question is not clear, please let me know.
Thank you for reading.
%s is for reading null-terminated strings, so passing pointer to one-byte buffer for that is bad.
It seems the variable x is placed just after the variable y_or_n on the memory and writing of terminating null-character by scanf() is setting value of x to 0.
To read one character, use %c instead.
char y_or_n;
/* ... */
scanf(" %c", &y_or_n);
I am new to c ,while i am writing a basic program in c ,it is showing two answers ..1)when i declare and intialize variables separately 2)when I declare and initialize variable in a same line.can any one tell me my mistake please?
#include <stdio.h>
#include <stdlib.h>
void sum()
{
printf("enter the numbers to be added\n");
int x=scanf("%d",&x);
int y=scanf("%d",&y);
int sum=(x+y);
printf("the sum of two numbers is %d\n",sum);
}
int main()
{
printf("welcome to addition calculator\n");
sum();
return 0;
}
I am getting 2 as answer when i gave 3 and 4 as inputs
scanf("%d", &x) will store the read number into x. It will return the number of successfully read fields (1 in your case). If you assign that return value to x afterwards, you overwrite whatever the user entered with that 1. And 1 + 1 produce 2.
Solution:
int x;
int y;
scanf("%d",&x);
scanf("%d",&y);
As David reminds in comments, you might want to check that all fields were read successfully. For example, in your case, if you enter a non-digit, scanf will not resolve the %d field as successful, and will return 0. You can test this result to make sure the user did what they were supposed to do:
int x;
int y;
while (scanf("%d", &x) != 1) {
printf("Enter a NUMBER, you illiterate buffoon!\n");
}
while (scanf("%d", &y) != 1) {
printf("Enter a NUMBER! You managed with %d, how is this suddenly hard now?!\n", x);
}
scanf() function returns 1 if it scan successfully otherwise it return 0. That's why when you put an integer to x, scanf() return 1 and assign it to x(x=1). Same for y(y=1).
As x=1 and y=1.
sum = 2
Purpose:
If user input b is a float number prints floor(b), round(b), ceil(b).
Else prints scanf error: (%d)\n.
The instruction (provided by our teacher) has a code like this, which I don't understand.
Here's my code:
`
#include <stdio.h>
#include <math.h>
int main(void) {
float b;
printf("Eneter a float number");
int a=0;
a=5;
a=scanf("%d", &b);
if (a=0)
{
printf("scanf error: (%d)\n",a);
}
else
{
printf("%g %g %g",floor(b), round(b), ceil(b));
}
return 0
}
Mistake # 1
if (a=0) // condition will be always FALSE
must be
if (a==0)
or better
if (0 == a)
Mistake # 2
scanf("%d", &b); // when b is float
instead of
scanf("%f", &b);
UPDATE:
Actually, for case of checking results of scanf I personally prefer to use != with number of values entered with the last scanf. E.g. if two comma separated integers required to continue calculation snippet can be:
int x, y;
int check;
do{
printf("Enter x,y:");
check = scanf("%d,%d", &x, &y); // enter format is x,y
while(getchar()!='\n'); // clean the input buffer
}while(check != 2);
that loop will re-ask for input if check is not 2, i.e. if it is 0 (when even the first value is incorrect, e.g. abc,12) or if it is 1 (when user forgot comma or enter not a number after comma, e.g. 12,y
Code with corrections and comments - also available here - http://ideone.com/eqzRQe
#include <stdio.h>
#include <math.h>
int main(void) {
float b;
// printf("Eneter a float number");
printf("Enter a float number"); // Corrected typo
fflush(stdout); // Send the buffer to the console so the user can see it
int a=0;
// a=5; -- Not required
a=scanf("%f", &b); // See the manual page for reading floats
if (a==0) // Need comparison operator not assignemnt
{
printf("scanf error: (%d)\n",a); // A better error message could be placed here
}
else
{
printf("%g\n", b); // Just to check the input with ideone - debugging
printf("%g %g %g",floor(b), round(b), ceil(b));
}
return 0; // You need the semi-colon here
}
For VenuKant Sahu benefit
Return Value
These functions return the number of input items successfully matched
and assigned, which can be fewer than provided for, or even zero in
the event of an early matching failure.
The value EOF is returned if the end of input is reached before either
the first successful conversion or a matching failure occurs. EOF is
also returned if a read error occurs, in which case the error
indicator for the stream (see ferror(3)) is set, and errno is set
indicate the error.
I'm running this program in C to convert Fahrenheit to Celsius and need to accept only integer value from the user.
Please tell me how I can modify this?
int main() {
int x;
double y;
while(x>0) {
printf("Enter the temperature in Fahrenheit:");
scanf("%d", &x);
y=((x-32)/1.8)
printf("%f\n",y);
}
}
The reason your code does not work is that sometimes scanf does not read anything, so it does not modify x.
You know that scanf read something by checking its return value. It returns the number of "scanned" items. In this case, the number must be 1.
When scanf returns 0 instead, you should read and discard the data in the buffer. You do it by supplying %*[^\n] format specifier, which means "read and discard input up to '\n' character. The complete snippet that reads an int until success looks like this:
while (scanf("%d", &x) != 1) {
printf("Please enter a valid number:");
scanf("%*[^\n]");
}
Note: It goes without saying that you should fix your syntax error with the missing semicolon ; on the line that computes y.
You can use below code.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x;
double y;
char str1[5];
int num1,i;
bool yes = true;
while(x>0)
{
printf("Enter the temperature in Fahrenheit:");
scanf("%s",str1);
for(i=0;str1[i]!='\0';i++)
if(!(str1[i]>=48&&str1[i]<=56))
{
printf("The value is invalid \n");
yes = false;
}
num1 = atoi(str1);
if(yes == true)
{
printf("This Number is %d\n",num1);
y=((num1-32)/1.8);
printf("%f\n",y);
}
}
}