#include <stdio.h>
#include <stdlib.h>
int main() {
unsigned int n0;
scanf("%d", &n0);
const unsigned int n = n0;
short unsigned int A[n];
short unsigned int d, x, y, k;
short int l, r;
int i, j;
for (i = 0; i < n; i++) {
scanf("%d", &A[i]);
}
scanf("%d", &d);
for (i = 1; i <= d; i++) {
scanf("%d %d", &x, &y);
}
return 0;
}
Hi, I'm a total newbie with C and stumbled across a situation that amazed me a lot. In the above code, I would like to ask the user to input some number d, and then to input d pairs of point coordinates. But to my surprise the program ends executing after inputting first pair of (x,y), no matter what value of d greater than 1 is input first. It doesn't happen if I assign value to d in code (e.x. d = 5;). What may be the reason? Is the value assigned to the variable via the scanf statement somehow different and cannot be used in a loop condition?
Pay attention to the warnings that you get when compiling your code. One of the warnings should be as follows:
a.c:19:12: warning: format specifies type 'int *' but the argument has type
'unsigned short *' [-Wformat]
scanf("%d",&d);
~~ ^~
%hd
Using %d causes scanf cast a pointer to short as a pointer to int, leading to undefined behavior. It looks like in your case the upper portion of an int gets stored in a short, while the bottom portion gets dropped. For numbers undef 216 the upper part is zero, so the subsequent loop iterates zero times.
Fixing all warnings will eliminate this problem
scanf("%hu", &d);
... // Fix other scanf calls as well.
Note: There is no good reason for making loop variables short.
Related
the value of i resets after it reachers 7
#include <stdio.h>
int main(){
char marks[10];
int i;
printf("enter the numbers:\n");
printf("-------------------\n");
for (i=0;i<10;i++)
{
printf("%d\n",i);
printf("element %d-",i);
scanf("%d", &marks[i]);
}
printf("\n all %d",marks);
printf("\n second %d\n",marks[1]);
return 0;
}
output
Problem is here:
scanf("%d", &marks[i]);
Specifier "%d" expects a pointer to int, not char. Usually it will write 4 bytes what is a typical size of int.
Therefore on 8th iteration the elements of marks at index from 7 to 10 are touched. However, marks[10] is outside of marks array (only indices 0-9) are valid. Undefined Behaviour is invoked and the program can do anything, from crashing to infinite looping or conjuring nasal deamons.
To fix the program change the type of marks to int:
int marks[10];
Note:
UB is invoked even on the first iteration because "%d" expects a pointer to int while type of &marks[0] is char*. This operation is undefined by C standard because int* and char* may differ in size and/or representation and/or alignment. However it is a unlikely case for modern CPUs.
You have declared the marks as a character array and tried to get input from user using %d which asks asks for an integer,
#include <stdio.h>
int main(){
int marks[10];
int i;
printf("enter the numbers:\n");
printf("-------------------\n");
for (i=0;i<10;i++)
{
printf("%d\n",i);
printf("element %d-",i);
scanf("%d", &marks[i]);
}
printf("\n all %d",marks);
printf("\n second %d\n",marks[1]);
return 0;
}
Also I didn't understand the use of all so I couldn't find a solution for it. If you want to print a specific number then you have to specify it like you have done it for second or if you want to display the total you want to add a furthermore code to calculate the sum of elements in the array.
This is my code
#include <stdio.h>
int main() {
float percentage;
int sp;
int bp;
percentage = (sp-bp)/bp*100;
scanf("%d %d", &sp, &bp );
printf("%.2f%%", percentage);
return 0;
}
Sample input :
150 85
Sample output :
76.47%
but my output is :
-100.00%
Can someone help me fix this?
First of all, you should really read the values before using them:
scanf("%d %d", &sp, &bp);
percentage = ...
Secondly, this:
percentage = (sp-bp)/bp*100;
Does an integer division, so the rest of the division is totally discarded and you will end up with:
(150 - 85) / 85 == 0
0 * 100 == 0.
You should cast one end of the division to float before doing the operation:
percentage = (sp-bp)/(float)bp * 100;
Correct code:
#include <stdio.h>
int main() {
float percentage;
int sp;
int bp;
scanf("%d %d", &sp, &bp);
percentage = (sp-bp)/(float)bp * 100;
printf("%.2f%%", percentage);
return 0;
}
Explanation will add soon.
Code
#include <stdio.h>
int main()
{
float percentage=0;
int sp=0;
int bp=0;
scanf("%d%d", &sp, &bp );
//printf("\n%d%d", bp,sp);
percentage = (sp-bp)/(float)bp*100;
printf("%.2f%%", percentage);
}
Edit
Explain what i changed
As you scanning two integer with one scanf() function.
use scanf("%d%d", &sp, &bp );
Only remove space between two %d %d.
This white space is useless, because scanf() with %d format specifier consume any number of white space. but if you want to scan with %c use that.
scanf() consumes white space for all specifier except for %c, %n, %[…].
see more info on Jonathan Leffler answer
Initialize all variables like this (Declare and Define)
float percentage=0;
int sp=0;
int bp=0;
Because when we declare a variable inside function this is not initiate and have garbage value. This may cause undefined behavior.see C section
Suppose a situation that scanf() cant work properly and the integers sp and bp values remain with defaults. If we don't initiate them, garbage value remains.
Do declare and define at one time and initiate to zero. see
more on declare define
Add (float) explicit conversion to the division.
(sp-bp)/(float)bp*100;
In C result number of An integer that divides to another integer converted to integer and you lost decimal part because that is truncated.
see this
I'm new to C (programming in general). I was working on this for a while, my school assignment. I'm getting an output of many random numbers (e.g. 1xxxxxxxxx) instead of printed displays of input entered.
Here's the code in question:
#include<stdio.h>
int main()
{
char item[5][20];
double ppu[5], total, price[5], quantity[5];
int i;
for(i = 0; i < 5; i++)
{
printf("Enter item, price and quantity: ");
scanf("%s %f %f", &item[i], &ppu[i], &quantity[i]);
price[i] = ppu[i]*quantity[i];
total += price[i];
}
printf("ITEM\t\tPRICE PER UNIT\t\tQUANTITY\t\tPRICE\n");
for(i=0; i < 5; i++)
{
printf("%s\t\t%.2f\t\t%.0f\t\t%.2f\n", item[i], ppu[i], quantity[i], price[i]);
}
}
Change the format specifier to %lf. Don't forget to assign total with an initial value.
total hasn't been assigned (or initialized with) a relevant value.
Also, item[i] (a pointer to 20 chars) is converted to a pointer to char (what scanf expects) in the context of scanf. The & is wrong
scanf("%s %f %f", &item[i], &ppu[i], &quantity[i]);
// wrong ^^ ^^ ^
scanf("%s %lf %lf", item[i], &ppu[i], &quantity[i]); // thanks to Bpaul
Even better is making sure scanf did the right thing:
if (scanf("%s%lf%lf", item[i], &ppu[i], &quantity[i]) != 3) /* error */;
None of these variables and array members are initialized.
char item[5][20];
double ppu[5], total, price[5], quantity[5];
int i;
That means that they will contain random garbage values.
Now, the ones that you assign to with either scanf or the assignment operator will contain (possibly) useful data, but you are also missing out checking the return value of scanf, which will tell you how many values could be successfully read.
Also look at the way you use the 2-D array item. There is something wrong there.
I tried to read 2 variables from the keyboard and to write them on the screen and I have a problem, the program display me only one..
#include <stdio.h>
#include <stdlib.h>
int main()
{
short int n,x;
scanf("%d",&n);
scanf("%d",&x);
printf("%d %d",n,x);
return 0;
}
I introduced 14 and 15 and the program return me 0 and 15
can somebody tell me why?
Use %hd format specifier for short int
Use %hu format specifier for unsigned int
Use %d format specifier for int
Use %ld format specifier for long int
#include <stdio.h>
#include <stdlib.h>
int main() {
short int n, x;
scanf("%hd", &n); // Notice %hd instead of %d for short int
scanf("%hd", &x); // Notice %hd instead of %d for short int
printf("%hd%hd", n, x);// Notice %hd instead of %d for short int
return 0;
}
%d assumes the variable to be of data type int.
Use the data type int:
int main()
{
int n,x;
scanf("%d",&n);
scanf("%d",&x);
printf("%d %d",n,x);
return 0;
}
or use %hd instead of %d
int main()
{
short int n,x;
scanf("%hd",&n);
scanf("%hd",&x);
printf("%hd %hd",n,x);
return 0;
}
Note, scanf("%d",&x); read a value and stores it to the memory addressed by &x. Since &x is treated as a 4 byte memory, 4 bytes are written to the address specified by &x.
The formatters in scanf() and printf() doesn't match the type of your variables n and x.
%d uses the variables as they were int while int has probably the double number of bytes as short int. (Integer types)
Hence, with the wrong formatters, scanf() uses the provided addresses wrong.
For printf() it's a bit more complicated: The short ints are converted to int internally. (Default argument promotions) Hence, printing short int with %d (as they were int) doesn't fail.
So, it's the scanf() what must be fixed.
Either use correct formatters:
#include <stdio.h>
int main()
{
short int n,x;
scanf("%hd",&n);
scanf("%hd",&x);
printf("%d %d",n,x);
return 0;
}
Live Demo on ideone
or use correct variable type for the formatters:
#include <stdio.h>
int main()
{
int n,x;
scanf("%d",&n);
scanf("%d",&x);
printf("%d %d",n,x);
return 0;
}
Live Demo on ideone
The formatting of scanf() and printf() families are very powerful and flexible but unfortunately very error-prone as well. Using them wrong introduces Undefined Behavior. The compiler is (usually) unable to recognize errors as the evaluation of formatters happens at run-time and inside the scanf()/printf() functions. So, they have to be used caaarefully.
//o/p when i/p is 16 and 2 is 4 and if variable is int then o/p will be 20;
#define SETBIT(A,B) A|1<<B
int main(){
char n,pos;
printf("Enter a value");
scanf("%d",&n);
printf("Enter position");
scanf("%d",&pos);
printf("Value after setting %d",SETBIT(n,pos));
}
For the *scanf functions, the d conversion specifier expects its corresponding parameter to have type int *; if that's not the case, then the behavior is undefined, and pretty much any result is possible.
If you want to use char for pos and n, then you must use %hhd instead of %d in the scanf call.