the code doesn't work properly at output C - c

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.

Related

Infinite for loop? ()in c

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.

Input 12 digit number and save as int. C

I am new to C and memory allocation. I am trying to take a 12 digit input and save as int so later on I can do some calculations. So far I have:
#include <stdio.h>
void main(void){
char number[12];
do
{
printf("Credit Card Number: ");
scanf("%lli", number);
} while (number == 1);
printf("%lli", number);
}
Right now I use long long int since I can use 64 bits, but when I run it and type in 123 I get:
27583791809822484
Could someone explain what I am doing wrong, why the output is 27583791809822484 and if I have any styling errors.
scanf %lli expects a pointer to a long long int. You provided a pointer to an array of 12 char.
printf %lli expects a long long int. You provide a pointer.
long long int card_num;
scanf("%lli", &card_num);
printf("%lli", card_num);
If you wanted to portable code, you'd use
#include <stdint.h>
#include <inttypes.h>
uint64_t card_num;
scanf("%" SCNu64, &card_num);
printf("%" PRIu64, card_num);
If you wanted to store the number as a string (which is quite reasonable for a credit card number), then char number[12] makes sense, but you'd use %s. Actually, it would have to be char number[13] to be large enough to store 12 digits and the trailing NUL.
char card_num[13];
scanf("%12s", card_num);
printf("%s", card_num);
#include <stdio.h>
void main(void){
long long int creditcard;
printf("Credit Card Number: ");
scanf("%lli", &creditcard);
printf("%lli", creditcard);
}
this will work.
EDIT: As stated in the comments, if you have leading zeros, this won't work. Instead taking it as string like above is better.

loop condition with variable input with scanf - C

#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.

Why the below code is giving different output when variable type is different?

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

how to convert char to int

I'm trying to write a short program were:
#include <stdio.h>
void main()
{
char=a,b,c;
printf("please place 3 numbers:\n");
scanf("%c%c%c", &a,&b,&c);
}
The exercise I'm trying to solve is how to change the char to int so if I write in a the number 3, I will get the number 3 Printed.
at this point I'm only getting the value.
I would appreciate any help.
The answer depends somewhat on what you can assume about the character set. If it's something like ASCII (or really, any character set that includes the digits in sequential order), you just need to offset the character value by the value of the character 0:
int aValue = a - '0';
I'm sure that C# provides better ways to do what you're trying to do, though. For example, see this question for some examples of converting strings to integer values.
First of all your syntax need some checking
You should know that you declare a variable this way (a char in this example):
char a;
If you want to declare multiple variables of the same type in a row you do :
char a, b, c;
If you want to assign a value to a declared variable :
a = '3';
Now to print a char using printf (man printf is a must read, more infos are in coreutils) :
printf("%c", a);
If you want to get the char from the command line, I recommand you to use getchar() (man getchar) instead of scanf because if suits better what you are trying to achieve and doesn't require you to use a syntax in scanf that I am sure you don't fully understand yet.
Your question is incredibly light on details, so here are several options:
#include <stdio.h>
int main()
{
char a,b,c;
printf("please place 3 numbers:\n");
scanf("%c%c%c", &a,&b,&c);
printf("Printing ints (auto-promotion): %d %d %d\n", a, b, c);
printf("Printing ints (explicit-promotion): %d %d %d\n", (int)a, (int)b, (int)c);
printf("Printing digits: %d %d %d\n", a-0x30, b-0x30, c-0x30);
return 0;
}
If the input is 123,
I expect the output to be:
Printing ints (auto-promotion): 49 50 51
Printing ints (explicit-promotion): 49 50 51
Printing digits: 1 2 3
Some things I fixed along the way.
main should return an int, not be void.
char=a,b,c; is a syntax error. You meant char a,b,c;
added a return 0; at the end of main.
You question is not quite understandable. Still I'll try to help. I think that what you want is to store an integer value in the char variable. You can do so by using the following code:
#include<stdio.h>
void main()
{
char a,b,c;
printf("Enter three numbers:\n");
scanf(" %c %c %c",&a,&b,&c); //notice the spaces between %c
}
Or if you want to enter a character and print its ASCII value, you can use the following code:
#include<stdio.h>
#include<conio.h>
void main()
{
char a,b,c;
printf("Enter three characters:\n");
scanf(" %c %c %c",&a,&b,&c);
printf("Entered values: %d %d %d",a,b,c);
getch();
}

Resources