Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

HELP WITH THIS CODE! I need to make sure when i input the number 0 i get out 0x0

ID: 3719748 • Letter: H

Question

HELP WITH THIS CODE! I need to make sure when i input the number 0 i get out 0x0. FOr some reason, I am getting 0x. Please make sure that the code edit doesn't mess with the rest of the code.

#include<iostream>
using namespace std;

int main() {
long int decnum, rem, quot; //variables declaration
int i = 1, j, temp; //variables declaration
char hexnumber[100]; //variables declaration

cout << "Enter a decimal number: ";
cin >> decnum; //reading the decimal number
quot = decnum;
while (quot != 0)
{
  temp = quot % 16;
  if (temp < 10) //for converting integer into character
   temp = temp + 48;
  else
   temp = temp + 55;

  hexnumber[i++] = temp;
  quot = quot / 16;
}
cout << "Your number in hex is 0x";
for (j = i - 1; j > 0; j--)
  cout << hexnumber[j];
cout <<"."<< endl;
return 0;
}

Explanation / Answer

Please find my corrected code.


#include<iostream>
using namespace std;

int main() {
int decnum, rem, quot; //variables declaration
int i = 1, j, temp; //variables declaration
char hexnumber[100]; //variables declaration

cout << "Enter a decimal number: ";
cin >> decnum; //reading the decimal number
quot = decnum;

if(quot == 0) {
    hexnumber[i++] = '0';
}else{
   while (quot != 0)
   {
      temp = quot % 16;
      if (temp < 10) //for converting integer into character
       temp = temp + 48;
      else
       temp = temp + 55;

      hexnumber[i++] = temp;
      quot = quot / 16;
   }
}
cout << "Your number in hex is 0x";
for (j = i - 1; j > 0; j--)
cout << hexnumber[j];
cout <<"."<< endl;
return 0;
}