By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
431,943 Members | 1,875 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 431,943 IT Pros & Developers. It's quick & easy.

How to prevent the previous result from showing

P: 1
I'm 10th grade doing our project in IT.

It tasked us to convert decimal to binary and ask the user if he wants to try again or not.

I did that using the goto but when I type another decimal it shows the previous result

Expand|Select|Wrap|Line Numbers
  1. #include<stdio.h>
  3. int n, r, i=1, b=0; 
  4. char command;
  5. int main(void)
  7. {
  8. start:
  9.     printf("enter a decimal: ");
  10.     scanf(" %i", &n);
  12.     while(n>0)
  14.     { 
  15.     r=n%2;
  16.     n=n/2;
  17.     b=b+r*i;
  18.     i=i*10;
  20.     }
  21.     printf("%i", b);
  24.  char command;
  25.     printf("\n Would you like to try again?[Y/N] \n");
  27.     scanf(" %c", &command);    
  29.     while(command=='Y')
  30.     {
  31.         goto start;
  32.         break;
  33. }
  35.     printf("Goodbye!");
  39.     return 0;  
  40.     }
Sep 17 '17 #1
Share this Question
Share on Google+
2 Replies

Expert Mod 5K+
P: 9,197
I didn't do a complete debug but I did notice your variable i is not initialized when you start your loop. Therefore, i has the value from the first number when the loop starts the second number. The effect is to add the binary digits of the second number behind those of the first number.

Now when you display i as a char you see the bits from the first number.

I would display either define i as a char or leave it an int and display it as an int.

BTW you ask the user for a decimal but you are expecting an int. I would ask for an integer.
Sep 17 '17 #2

P: 1
It's quite simple, you need b to start at 0, and i at 1 everytime.
When you restart from the goto, it keeps their current values, so you should put b=0; i=1; straight after the start :
Sep 20 '17 #3

Post your reply

Sign in to post your reply or Sign up for a free account.