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

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

Related

Putchar character is appearing at the front of my printf function

Using this code
void echo_char_code() {
int x;
printf ("Please enter a character:\n");
x = getchar();
printf("The character code of '%c' is %d", putchar(x), putchar(x));
printf(". \n");
}
int main() {
echo_char_code();
return 0;
}
but for some reason my output is
AAThe character code of 'A' is 65.
and I'm wondering why the "AA" is appearing at the start and not just as the 'A' & 65 that I want it too.
You shouldn't pass putchar(x) as argument, instead use the variable x.
void echo_char_code() {
int x;
printf ("Please enter a character:\n");
x = getchar ();
printf("The character code of '%c' is %d", x, x)); // changing putchar(x) to x solves the problem.
printf (". \n");
}
int main() {
echo_char_code();
return 0;
}
In this line
printf("The character code of '%c' is %d",putchar(x),putchar(x));
you are calling putchar() twice, which outputs x twice.
You are also using the return values of those two calls to do a formatted output.
The return value of putchar() happens to be (in case of success) the written char, which makes it somewhat transparent.
The order of this is probably not predictable, but it does explain your observed result.
Compare https://en.cppreference.com/w/c/io/putchar
it states
Return value
On success, returns the written character.

C not reading values from input correctly

I am very new to C, and while working on a project which requires pulling an indeterminate amount of values from the console, I am finding that it is not pulling the correct values. It seems like addresses, which I believe means it is a pointer issue, but I can't seem to find it.
int getVals(int degree){
double sum;
double x;
double coefs[degree];
for(int counter = 0; counter<=degree; counter = counter+1){
double nxt;
scanf(" %d", &nxt);
coefs[counter] = nxt;
printf("coefs[%d] = %d\n", counter, coefs[counter]);
}
printf(" x ? ");
scanf(" %d", &x);
printf("degree %d x %d\n", degree, x);
sum = poly(x, degree, coefs);
printf ("polynomial evaluate to: %lf\n", sum);
int newDegree;
scanf(" %d", &newDegree);
degree = newDegree;
if(degree>-1){
getVals(degree);
}
else
return degree;
}
Note: poly returns a double result of the evaluated polynomial
I am getting the following infinite loop after entering a degree of 1 and a coefficient of 1.5. It does not allow me to enter an x.
Infinite loop
In scanf(" %d", &newDegree); you should use the "%lf" format specifier (since your values is a double, not an int). Change the format specifier in all your calls to scanf() and "%f" in calls to printf().
Please refer to the documentation at this links printf(3), scanf(3).

Scanf Runtime error, have to ctrl-alt-delete

int main()
{
double a = 1;
double b = 3;
int n = 128;
int answer = 0;
printf("select an option(1, 2) ");
scanf("%d", answer);
double y = calcIntegral (answer, a, b, n);
printf("%f \n", y);
system("pause");
return 0;
}
it gets to Scanf and then if accepts the answer but stalls completely and I have to force the task to end. What's going on? This is identical to other programs I've written, I think. I tried using %i as well, and using a char instead of a double for the variable "answer". It says it can't access the memory.
For scanf with modifier d, it matches an optionally signed decimal integer, and the next pointer must be a pointer to int. Says the standard. Also make sure always check scanf return value.
int ret = scanf("%d", &answer);
if (ret != 1) {
// failed to input the number
}
When using scanf(), the variable you read has to be a pointer . So your statement :
scanf("%d", answer);
should be :
scanf("%d", &answer);
as you have declared answer to be an int, so its memory address is a pointer to an int.
On the other hand, if you wanted to read a string and had declared :
char *str;
allocating some memory for it, then the statement would be :
scanf("%s", str);
as str is declared as a pointer to char.

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

Is there a way to use scanf with the "if" and "else" statements?

I have to create and call a function from main. Then I have to call scanf to read two integers and print out the bigger one. Then I have to do another scanf, but this time with doubles instead of integers.
int main()
{
int x, y;
scanf("%d%d", &x, &y);
if (x > y)
{
printf("%d", x);
}
scanf("%lf%lf", &w, &z);
if ( w > z)
{
printf("%f", w);
}
return 0;
}
I'm not sure if I did this right and how would I check the return value to see that the scanf worked? Thanks.
how would I check the return value to see that the scanf worked?
By checking the return value of scanf().
if( scanf("%d%d", &x, &y) != 2)
{
/* input error */
}
if (x > y)
{
printf("%d", x);
}
if(scanf("%lf%lf", &w, &z) != 2)
{
/* input error */
}
if ( w > z)
{
printf("%f", w);
}
From scanf() documentation:
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.
In your case, you can check whether scanf() has worked succesfully or not as follows,
if( scanf("%d%d", &x, &y) == 2)
{
if (x > y)
{
printf("%d", x);
}
}
else
{
printf("\nFailure");
}
scanf() returns the number of arguments successfuly read by it.
It says you're trying to call a function from main. Does that mean that your teacher wants a function besides main? In which case you want to create one as below. You will also have to do something similar only with double integers.
#include stdio.h
int bigger(void);
int main(void)
{
int larger;
larger = bigger(void);
printf("The Larger integer is: %d\n", larger);
return 0;
}
int bigger(void)
{
int x,y,z;
printf("Enter your first integer\n");
scanf("%d", &x);
printf("Enter your second integer\n");
scanf("%d", &x);
if(x > y)
{
z = x;
}
else
{
z = y;
}
return z;
}
sollution for
I have to create and call a function from main. Then I have to call scanf to read two integers and print out the bigger one. Then I have to do another scanf, but this time with doubles instead of integers.*/
#include<stdio.h>
#include<stdlib.h>
int main(){
int a,b;
printf("enter any two numbers");
scanf(" %d\n %d",&a,&b);
if(a>b){
printf("bigger number is %d",a);
}else{
printf("bigger number is %d\n",b);
}
float c,d;
printf("enter any two numbers");
scanf(" %f\n %f",&c,&d);
if(c>d){
printf("bigger number is %.2f",c);
}else{
printf("bigger number is %.2f\n",d);
}
system("pause");
return 0;`
}

Resources