where I made the mistake and how to fix it? - c

#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);

Related

Complex numbers through scanf in C

I have problem with following fragment of code:
int main()
{
int n = 3;
complex_t t[3];
for(int i = 0; i < n; i++)
{
double x, y;
printf("Enter complex number: ");
scanf("%f %f", &x, &y);
t[i].re = x;
t[i].im = y;
}
}
When I am trying to pass x, and y to the program, it doesn't change value, and is 0.00000.
Can you help me?
You've declared x and y as doubles, but then went on to use the format specifier for floats (%f). So the end result is reading them in as if they were regular floats, then jamming the result into a double leaving you with unexpected values when trying to actually use them.
You need to use the format specifier specifically for doubles (%lf) here.
scanf("%lf %lf", &x, &y);
See format string specifications for more information about different format specifiers.

Unexpected behavior after scanf() in do..while loop

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);

Scanf function in C with CodeBlocks IDE is buggy?

I'm running some simple code in my CodeBlocks and I wonder why scanf function cannot work with shorts correctly!
The code below is an example. The code takes from the user three int numbers and then prints them again, that simple — but the values printed don't match the values entered.
#include <stdio.h>
int main()
{
short x, y, z;
printf("Please enter three integers! ");
scanf("%d %d %d", &x, &y, &z);
printf("\n num1 = %d , num2 = %d , num3 = %d ", x, y, z);
return 0;
}
The specifier %d is only used for int variables, but in case of short you must use the %hi specifier instead of %d.
So your code must be :
#include <stdio.h>
int main() {
short x , y , z ;
printf("Please Enter three int Numbers ! ");
scanf("%hi %hi %hi",&x,&y,&z);
printf("\n num1 = %hi , num2 = %hi , num3 = %hi ",x,y,z);
return 0;
}
You can find more information about the C data types and their Specifiers here :
https://en.wikipedia.org/wiki/C_data_types
short != int
you pass the pointer to the (usually 2 byte) data, and scanf expects and writes 4 bytes
change short x , y , z ; to int x , y , z ;
as always scanf is not buggy, but the coder is :)
PS Forgot to add. you can also use h format modifier. There is hh as well if you want to scan char sized variables

Finding if a Number if Prime or not In C

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){
// ...

Creating my own calcutor but program doesnt work

I decided to make a calcutor using code but my program just wont work.
When i enter my operand and new number it wont seem to scan the operand and number and it wont start the loop.
Thanks for the help.
#include <stdio.h>
#include <math.h>
float add(float x,float y);
float sub(float x,float y);
float div(float x,float y);
float exp(float x,float y);
float mult(float x,float y);
int main(){
float y,x;
char op;
printf("Type in a number\n");
scanf("%f",&x);
printf("Type in your operand and desired number\n");
scanf("%c",&op);
scanf("%f",&y);
while (!(op=='q')){
if(op=='+'){
printf("Your result is %.1f\n",add(x,y));
scanf("%c",&op);
scanf("%f",&y);
}
else if(op=='-'){
printf("Your result is %.1f\n",sub(x,y));
scanf("%c",&op);
scanf("%f",&y);
}
else if(op=='*'){
printf("Your result is %.1f\n",mult(x,y));
scanf("%c",&op);
scanf("%f",&y);
}
else if(op=='/'){
printf("Your result is %.1f\n",div(x,y));
scanf("%c",&op);
scanf("%f",&y);
}
else if(op=='^'){
printf("Your result is %.1f\n",exp(x,y));
scanf("%c",&op);
scanf("%f",&y);
}
}
printf("Your final result is %.1f\n",x);
return(0);
}
float add(float x,float y){
return (x+y);
}
float sub(float x,float y){
return (x-y);
}
float div(float x,float y){
return (x/y);
}
float exp(float x,float y){
x=pow(x,y);
return(x);
}
float mult(float x,float y){
return (x*y);
}
when you do
scanf("%c",&op);
you read first char that is in the input buffer. previous scanf left \n char in it, so you read that char.
What you want to do, is to get rid of all what's left behind scanf.
while(getchar()!='\n')
continue;
That will empty the buffer before you try to read.
Every use of scanf here will leave new line character in the buffer so to get rid of him, use above loop every time you try to read a character from input and you know that newline is there.
I think what's happening is that the newline character (the return/enter key) is left over in the input stream after the scanf("%f",&y); call and that's what being stored as the single character in the scanf("%c",&op); call.
So you'll need to discard the newline character at that point. Simplest way is to call scanf("%c",&op); twice when you need to read the single character. This should work on Mac and Unix. For Windows, you may need to read the character three times because Windows often considers the sequence "\r\n" as a newline sequence.
For portability, you can use a loop like this:
do {
op = getchar();
} while (op == '\n' || op == '\r');
And remove the scanf("%c",&op);. This loop replaces it.
Another option is to ask scanf itself to discard initial whitespace.
scanf(" %c",&op);
// ^ space
Also, see my answer to this very similar question.

Resources