so essentially i made a program that allows that use to convert any number from base n to base 10. im soley using base 5 in this instance. the issue is, is that im trying to rewrite my function, in two ways. one way, is that it replaces the for loop with a while loop, and the for loop with a dowhile loop. i did it, but i dont receive the same results. i've been gnawing my fingers for the past 3 hours trying to figure this out but no dice. here's the code:
#include "stdafx.h"
#include <conio.h>
#include <stdlib.h>
int convert(int a,int base);
int main()
{
int a,base,ans;
printf("\nEnter your preferred number: ");
scanf("%d", &a);
printf("\nEnter the base of that number: ");
scanf("%d", &base);
ans=convert(a,base);
printf("The converted base 10 is: %d", ans);
getch();
return 0;
}
int convert(int a,int base)
{
int sum=a%10;
for(int i=base;(a/=10)!=0;i*=base)
sum+=a*i;
return sum;
}
/// Input 12, 5, Output, 7. Correct.
^^everything in that fragment of code functions correctly and should remain unmodified, but the dilemma is trying to switch the for cycle with a dowhile and a while. here's what i tried:
1 2 3 4 5 6 7 8 9 10 11 12
int convert(int a,int base)
{
int sum=a%10;
int i = base;
while((a/=10)!=0){
i*=base; //added that outside of this while method, but nothing new.
sum+=a*i; //with or without the brackets, different wrong results.
}
return sum;
}
///////////////////////////
1 2 3 4 5 6 7 8 9 10 11 12 13
int convert(int a,int base)
{
int sum=a%10;
int i = base;
do{
i*=base;
sum+=a*i;
}while((a/=10)!=0);
return sum;
}
//////////////////////Input 12,5 Output, 427. Incorrect.
Well the only difference between between a while and a do while is that that the former pretest and the latter is a post test. You have to account for this when programming. Now, have you tried moving the i*=base to after the sum+=a*i?
and thank you reed for the elaboration of the problem. but what about the dowhile cycle, is there a similar complication with that cycle, or is it more intrinsic?
Just think about it a bit, a do while is a POST TEST, meaning it checks the condition AFTER it runs through it's loop. The only real difference is that a do while will always run through at least once. This is handy in some situations, sometimes it's irrelevant, and sometimes it causes problems.
In every control statement except the do while you are performing (a/=10) first. As you now have noticed the do while executes this instruction After all other computations. you will need to perform (a/=10) before entering the do while and also check that it is not zero... to keep your same logic.
but the only way i can do that is through another while statement. or if statement. im trying but according to the instructions of the assignment, i cant use anything besides the do while cycle.