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

Use for loop, while loop, and do while loops to generate a table of decimal numb

ID: 3666545 • Letter: U

Question

Use for loop, while loop, and do while loops to generate a table of decimal numbers,
as well as the binary, octal, and hexadecimal equivalents of the decimal numbers,
in the range 1-256.

Note: See Appendix for number systems.

The program should print the results to the Console without using any string formats .

Design Details:

The Main program should prompt the user for input.   
The output is shown in the sample output below.
           
Note: To generate the binary numbers your code should use a while loop to generate
the binary numbers, a “for” loop to generate the octal numbers and a “do .. while” to
generate the hexadecimal numbers.

Sample Output:

Enter the low number:
1
Enter the high number:
10
Decimal Binary          Octal   Hexadecimal
1       1               1       1
2       10              2       2
3       11              3       3
4       100             4       4
5       101             5       5
6       110             6       6
7       111             7       7
8       1000            10      8
9       1001            11      9
10      1010            12      A

****Resetting low and high ****
Low = 10, High = 15
Decimal Binary          Octal   hexadecimal
10      1010            12      A
11      1011            13      B
12      1100            14      C
13      1101            15      D
14      1110            16      E
15      1111            17      F

Press any key to continue . . .

Explanation / Answer

Code:

#include <stdio.h>

int main()
{
int low,high;
char c;
printf("enter the low number ");
scanf("%d",&low);
printf("enter the high number ");
scanf("%d",&high);
print(low,high);
printf("resetting low and high ");
printf("low =");
scanf("%d",&low);
printf("High = ");
scanf("%d",&high);
print(low,high);
printf("Enter any key to continue ");
scanf("%c",&c);
  
return 0;
}
void print(int low, int high)
{
char a[]="0123456789ABCDEF";
int power,digit,i,j,dec,oct,bin;
char c,hex[5];
printf(" Decimal Binary Octal hexadecimal ");
for( i=low;i<=high;i++)
{
// converting decimal to binary with while loop
bin=0;
dec=i;
power=1;
while(dec>0)
{
bin = bin + power*(dec%2);
dec/=2;
power*=10;
}
//converting decimal to octal with for loop
power=1;
oct =0;
for(dec=i;dec>0;dec=dec/8)
{
oct = oct + power*(dec%8);
power*=10;
}

// converting decimal to hex using do while loop
digit =0;
dec=i;
do
{
hex[digit]=a[dec%16];
digit++;
dec/=16;
}while(dec>0);
hex[digit]=0;
j=0;
digit--;
do
{
c=hex[digit];
hex[digit]=hex[j];
hex[j]=c;
digit--;
j++;
}while(digit>j);
printf("%d %d %d %s ",i,bin,oct,hex);
}
}

Output:

c