why my program isn't showing correct result? - c

I wrote the following code for
this
Given an integer number, Write a C program that displays the number as follows:
First line : all digits
Second line : all digits except first digit
Third line: all except first two digits
last line : the last digit
For eg.,
the number 5678 will be displayed as:
5 6 7 8
6 7 8
7 8
8
=>
#include<stdio.h>
#include<math.h>
main()
{
long int x,y,n,z,i=1;
printf("enter no. of digits=");
scanf("%d",&n);
printf("x=");
scanf("%d",&x);
while(i<=n)
{
y=x/pow(10,i);
z=y*pow(10,i);
printf("%d\n",(x-z));
i++;
}
}
The code works(if we ignore the formatting) but does some rounding of and stuff fr some output values ...don't know why??
There are solutions using array and all...but whts wrong with this one??

I'm assuming by "some values" with problems, you're referring to values that have zeroes in them, such as input like 50345, which will print:
50345
345
345
45
5
rather than:
50345
0345
345
45
5
The problem is that the integer representation of numerical values does not acknowledge leading zeroes as being a unique integer value.
If you must print the values, including leading zeroes, you're going to have to treat your number like a token or string, meaning that a value that has leading zeroes is a unique string value from the version without leading zeroes. This is why the array-versions, which treat the numeral value like a string, work, and your current version does not when presented with this type of input case.

The rounding off you are seeing could be because of the use of int as data type for all the variables. So something like (5/10) would be rounded to 0 and not 0.5.

#include<stdio.h>
#include<math.h>
main()
{
int num, count=0, x,no;
printf("Enter a number\n");
scanf("%d",&num);
no=num;
printf("The number you entered is:\n %d\n",num);
while(num){
num=num/10;
count++;
}
for(;count>1;count--){
x=pow(10,count-1);
printf("%d\n",no%x);
}
}

#include <stdio.h>
#include<conio.h>
void main()
{
int number,i=0;
int digits[8];
scanf("%d"&number);
while(number!=0)
{
digits[i]=numder%10;
number=number/10;
i++
}
for(i=i-1;i>=0;i--){
for(j=i;j>=0;j--){
printf("%d ",digits[j]);
}
printf("\n"):
}
}

Related

Couldn't get rid of multiple outputs in a C program

I couldn't share the original code but the below program is as similar to my problem.
#include<stdio.h>
#include<conio.h>
void clrscr(void);
int reverse_of(int t,int r)
{
int n=t;
r=0;
int count=0;
while (t!=0) /*Loop to check the number of digits*/
{
count++;
t=t/10;
}
if (count==4) /*if it is a 4 digit number then it proceeds*/
{
printf("Your number is: %d \n",n); /*displays the input*/
while (n!=0) /*This loop will reverse the input*/
{
int z=n%10;
r=r*10+z;
n=n/10;
}
return r; /*returns the value to main function*/
}
else /*This will execute when the input is not a 4 digit number */
{
printf("The number you entered is %d digit so please enter a four digit number \n",count);
main();
}
};
int main()
{
int n,r;
void clrscr();
printf("Enter a number: ");
scanf("%d",&n);
//while (n!=0) /*Use this for any number of digits*/
/* {
int z=n%10;
r=r*10+z;
n=n/10;
} */
r=reverse_of(n,r);
printf("The reverse of your number is: %d\n",r);
return 0;
};
This program displays the reverse of a 4 digit number. it works perfect when my first input is a 4 digit number. The output is as below.
(Keep in mind that i dont want this program to display the reverse of
a number unless its 4 digit)
Enter a number: 1234
Your number is: 1234
The reverse of your number is: 4321
Now when i give a non 4 digit number as the first input the program displays that it is not a 4 digit number and asks me for a 4 digit number. Now when i give a 4 digit number as the second input. It returns the correct answer along with another answer which is supposed to be the answer for the first input. (since the program cannot find the reverse value of a non 4 digit number the output always return 0 in that particular case). If i give 5 wrong inputs it displays 5 extra answers. Help me get rid of this.
Below is the output when i give multiple wrong inputs.
Enter a number: 12
The number you entered is 2 digit so please enter a four digit number
Enter a number: 35
The number you entered is 2 digit so please enter a four digit number
Enter a number: 455
The number you entered is 3 digit so please enter a four digit number
Enter a number: 65555
The number you entered is 5 digit so please enter a four digit number
Enter a number: 2354
Your number is: 2354
The reverse of your number is: 4532
The reverse of your number is: 0
The reverse of your number is: 0
The reverse of your number is: 0
The reverse of your number is: 0
Help me remove these extra outputs btw im using visual studio code and mingw compiler.
The problem lies here:
else /*This will execute when the input is not a 4 digit number */
{
printf("The number you entered is %d digit so please enter a four digit number \n",count);
main();
}
You're calling main() from reverse_of().
Try replacing the main(); with return 0; and in main(), do this:
int n,r;
do{
printf("Enter a number: ");
scanf("%d",&n);
r=reverse_of(n,r);
}while(r==0);
printf("The reverse of your number is: %d\n",r);
This happens because of the multiple recursion caused by the call of main() inside of the reverse_of function.
To avoid such thing you can move the printf("The reverse of your number is: %d\n", r); to the inside of the if(count==4){} and your problem is solved!
Also, note that your reverse_of functions does not need to receive the int r, instead it can be written like this:
#include <stdio.h>
int reverse_of(int t)
{
int n = t;
int r = 0;
int count = 0;
while (t != 0) /*Loop to check the number of digits*/
{
count++;
t = t / 10;
}
if (count == 4) /*if it is a 4 digit number then it proceeds*/
{
printf("Your number is: %d \n", n); /*displays the input*/
while (n != 0) /*This loop will reverse the input*/
{
int z = n % 10;
r = r * 10 + z;
n = n / 10;
}
printf("The reverse of your number is: %d\n", r);
return 1;
}
else /*This will execute when the input is not a 4 digit number */
{
printf("The number you entered is %d digit so please enter a four digit number \n", count);
return 0;
}
};
int main()
{
int n, r=0;
while (r!=1){
printf("Enter a number: ");
scanf("%d", &n);
r=reverse_of(n);
}
return 0;
};
Hope it helped!
Well, your program has some ambiguity: If you stop as soon as you get 0, then the reverse of 1300, 130 and 13 will be the same number, '31'.
So, first of all you need two parameters in your function, to deal with the number of digits you are considering, so you don't stop as soon as the input number is zero, but when all digits have been processed. Then you extract digits from the least significant, and add them to the result in the least significant place. This can be done with this routine:
int reverse_digits(int source, int digits, int base)
{
int i, result = 0;
for (i = 0; i < digits; i++) {
int dig = source % base; /* extract the digit from source */
source /= base; /* shift the source to the right one digit */
result *= base; /* shift the result to the left one digit */
result += dig; /* add the digit to the result on the right */
}
return result;
}
The extra parameter base will allow you to operate in any base you can represent the number. Voila!!!! :)
#include <stdio.h>
int main()
{
int src;
while (scanf("%d", &src) == 1) {
printf("%d => %d\n",
src,
reverse_digits(src, 5, 10));
}
}
will provide you a main() to test it.
In contrast to C++, in C, it is allowed to call main recursively. But it is still not recommended. There are only a few situations where it may be meaningful to do this. This is not one of them.
Recursion should only be used if you somehow limit the depth of the recursion, otherwise you risk a stack overflow. In this case, you would probably have to call the function main recursively several thousand times in order for it to become a problem, which would mean that the user would have to enter a value that is not 4 digits several thousand times, in order to make your program crash. Therefore, it is highly unlikely that this will ever become a problem. But it is still bad program design which may bite you some day. For example, if you ever change your program so that it doesn't take input from the user, but instead takes input from a file, and that file provides bad input several thousand times, then this may cause your program to crash.
Therefore, you should not use recursion to solve this problem.
The other answers have solved the problem in the following ways:
This answer solves the problem by making the function reverse_of not return the reversed value, but to instead directly print it to the screen, so that it does not have to be returned. Therefore, the return value of the function reverse_of can be used for the sole purpose of indicating to the calling function whether the function failed due to bad input or not, so that the calling function knows whether the input must be repeated. However, this solution may not be ideal, because normally, you probably want the individual functions to have a clear area of responsibility. To achieve this clear area of responsibility, you may want the function main to handle all the input and output and you may want the function reverse_of to do nothing else than calculate the reverse number (or indicate a failure if that is not possible). The fact that you defined your function reverse_of to return an int indicates that this may be what you originally intended your function to do.
This answer solves the problem by reserving a special return value (in this case 0) of the function reverse_of to indicate that the function failed due to bad input, so that the calling function knows that the input must be repeated. For all other values, the calling function knows that the function reverse_of succeeded. In this case, that solution works, because the value 0 cannot be returned on success, so the calling function can be sure that this value must indicate a failure. Therefore, in your particular case, this is a good solution. However, it is not very flexible, as it relies on the fact that a return value exists that unambiguously indicates a failure (i.e. a value that cannot be returned on success).
A more flexible solution, which keeps a clear area of responsibility among the two functions as stated above, would be for the function reverse_of to not always return a single value, but rather to return up to two values: It will return one value to indicate whether it was successful or not, and if it was successful, it will return a second value, which will be the result (i.e. the reversed value).
However, in C, stricly speaking, functions are only able to return a single value. However, it is possible for the caller to pass the function an additional variable by reference, by passing a pointer to a variable.
In your code, you are declaring your function like this:
int reverse_of(int t,int r)
However, since you are not using the argument r as a function argument, but rather as a normal variable, the declaration is effectively the following:
int reverse_of( int t )
If you change this declaration to
bool reverse_of( int t, int *result )
then the calling function will now receive two pieces of information from the function reverse_of:
The bool return value will indicate whether the function was successful or not.
If the function was successful, then *result will indicate the actual result of the function, i.e. the reversed number.
I believe that this solution is cleaner than trying to pack both pieces of information into one variable.
Note that you must #include <stdbool.h> to be able to use the data type bool.
If you apply this to your code, then your code will look like this:
#include <stdio.h>
#include <stdbool.h>
bool reverse_of( int t, int *result )
{
int n=t;
int r=0;
int count=0;
while (t!=0) /*Loop to check the number of digits*/
{
count++;
t=t/10;
}
if (count==4) /*if it is a 4 digit number then it proceeds*/
{
while (n!=0) /*This loop will reverse the input*/
{
int z=n%10;
r=r*10+z;
n=n/10;
}
*result = r;
return true;
}
else /*This will execute when the input is not a 4 digit number */
{
return false;
}
};
int main()
{
int n, result;
for (;;) //infinite loop
{
//prompt user for input
printf( "Enter a number: " );
//attempt to read number from user
if ( scanf( "%d",&n ) != 1 )
{
printf( "Invalid input!\n" );
//discard remainder of line
while ( getchar() != '\n' )
;
continue;
}
printf( "Your input is: %d\n", n );
//attempt to reverse the digits
if ( reverse_of( n, &result) )
break;
printf( "Reversing digits failed due to wrong number digits!\n" );
}
printf("The reverse of your number is: %d\n", result );
return 0;
};
Although the code is now cleaner in the sense that the area of responsibility of the functions is now clearer, it does have one disadvantage: In your original code, the function reverse_of provided error messages such as:
The number you entered is 5 digit so please enter a four digit number
However, since the function main is now handling all input and output, and it is unaware of the total number of digits that the function reverse_of found, it can only print this less specific error message:
Reversing digits failed due to wrong number digits!
If you really want to provide the same error message in your code, which specifies the number of digits that the user entered, then you could change the behavior of the function reverse_of in such a way that on success, it continues to write the reversed number to the address of result, but on failure, it instead writes the number of digits that the user entered. That way, the function main will be able to specify that number in the error message it generates for the user.
However, this is getting a bit complicated, and I am not sure if it is worth it. Therefore, if you really want main to print the number of digits that the user entered, then you may prefer to not restrict input and output to the function main as I have done in my code, but to keep your code structure as it is.

Convert decimal number into binary using recursion in C

I had this code. Everything is fine with the code. The only thing is I am not getting why we are multiplying by 10 in last second line when the function convert() is being called recursively.
#include<stdio.h>
int convert(int);
int main()
{
int dec,bin;
printf("\n Enter the decimal no.:");
scanf("%d",&dec);
bin=convert(dec);
printf("\n The binary equivalent is %d",bin);
return 0;
}
int convert(int dec)
{
if(dec==0)
return 0;
else
return ((dec%2)+10 * convert(dec/2));
}
Someone help me. Thanks in advance.
You seem not to understand what is happening:
Imagine you are converting the number 9 into binary digits, then you should get "1001", which you are (using your program).
However, the "1001" (one zero zero one) is shown as 1001 (one thousand and one).
Oh, maybe you don't understand that multiplying by ten and adding something is the way to append something at the end: if I ask to you append the digit 2 to the digit 3, you will do the following:
3 * 10 + 2 = 32
You are doing the same thing here (but the digits "pretend" to be binary digits).

getting different output from different compilers

The question was:
Define a function getint(), which would receive a numeric string from keyboard, convert it to an integer number and return the integer to the calling function.
My code is:
#include<stdio.h>
#include<math.h>
#include<string.h>
int getint();
int main()
{
int a;
a = getint();
printf("you entered %d",a);
return 0;
}
int getint()
{
char str[10];
printf("Enter number: ");
gets(str);
int d=0,len = strlen(str),r = len-1;
for(int i=0;str[i] != '\0';i++,r--)
d += (str[i]-48)*pow(10,r);
return d;
}
while I run this program from sublime text or code block the output was coming wrong
output(from sublime and codeblocks):
Enter number: 123
you entered 122
But when I used onlinegdb.com/online_c_compiler the output was coming correct
So how can output differ from compiler to compiler for the same program
The pow function works with floating point numbers. As such, the result may not be exactly equal to what you expect the numerical result to be. For example, pow(10,2) could output a number slightly larger or slightly smaller than 100. If the result is just below 100, the fractional part gets truncated and you're left with 99.
Rather than using pow for an integer power, just multiply the current value of d by 10 before adding the value for the next digit.
d = 10 * d + (str[i]-'0')

How to sum all values in a same variable?

I am working on an assignment but the code is doing some weird stuff. It is my 7th day "programming", so it might be just an obvious mistake, which I simply cannot see.
I want the program to sum all values stored in a same variable. I tried to replicate some code from here: https://stackoverflow.com/a/42166389, but it did not work as expected.
So, given a set of values -let's say 012345-, the program should take every other number -4, 2, and 0-, and sum them -giving back "6"-. And, although it does identify the digits, it does not sum them... at least properly.
I do not understand why, but it gives back 48.
I have tried different inputs, and while identifying the digits properly, in all cases the sum was wrong.
I would really appreciate any help.
Oh, and here is my code!:
#include <cs50.h>
#include <stdio.h>
#include <string.h>
int main(void) {
char c;
string number;
int length, i, sum = 0;
printf("Type card number: ");
number = get_string();
printf("Tell us how many characters long was your number: ");
length = get_int();
for (i = 1; i <= length / 2; i++) {
c = number[(strlen(number) - i * 2)];
sum = c;
printf("%c %i %s\n", c, sum, number);
}
}
Some examples:
For input 012345 and length=6, the output is:
4 52 012345
2 50 012345
0 48 012345
For input 9876543210 and length=10, the output is:
1 49 9876543210
3 51 9876543210
5 53 9876543210
7 55 9876543210
9 57 9876543210
And, just to summarize, what I want is a way of summing all the values in a same variable.
sum = c;
You are assigning ASCII value to sum.You should get the corresponding number and also add it to sum, not just assign.
4 52 012345 //52 is ASCII value of 4
2 50 012345 //50 is ASCII value of 2
0 48 012345 //48 is ASCII value of 0
Try this,
sum+=c-'0';

How to increase the potential value of an variable in a 16 bit machine using C

I have created a binary to decimal converter but even small numbers written in binary have many digits and thus are too large to be held by an integer variable on a 16 bit machine. Is there any way around this. The program is in C. Here is the code, thanks:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
clrscr();
int a,b,d=0,x=1;
int check(int y);
printf("Enter your number in Binary:");
scanf("%d",&a);
if(check(a)==0)
{
printf("Number tolerable. Conversion Process Initiated.");
}
else
{
printf("Number not binary. Try again.");
exit(1);
}
while(a!=0)
{
if(a%10==1)
{
d=d+x;
}
a=a/10;
x=x*2;
}
printf("\nDecimal:%d",d);
getch();
}
int check(int y)
{
while(y!=0)
{
if(y%10!=0&&y%10!=1)
{
return 1;
}
else
{
y=y/10;
}
}
return 0;
}
A simple way would be to store binary number into a character array.And to convert it into number see following steps-
1.Loop starting from i=n-1 to i>=0 ( array of size n).
2.Check if character at index i is 0 or 1.
Recognize 0 and 1 as follows-
3.If 0 then digit is 0.
4.If 1 then digit will be equal to 2^i (i being the index).
5.Last step would be add them.
Else use an integer array.
The %d format specifier to scanf expects a number to be entered in decimal format. There is no binary format specifier, so you have to read in the number as a string and parse through it.
For example, if the user enters "101011", you need to recognize this as 2^5 + 2^3 + 2^1 + 2^0 and add those value to the resulting number (to be clear, I'm using ^ to denote exponentiation instead of bitwise xor).
there's no real need to store the binary digits.
#include <string.h>
int n=0,c;
printf("Enter your number in Binary:");
while(strchr("01",c=getch()))
n+=n+c-'0';

Resources