-
Spelling Out Numbers
Code:
//Program requires user to enter a number
//program should then print out the name of each digit
//I cant seem to get my program to work it keeps spelling out
//each digit as "zero"
//does anyone see any mistakes?
//sorry Im a newbie at this.
#include<stdio.h>
#include <math.h>
int main(void)
{
long long int n,k,i,d,a;
printf("please enter your phone number: ");
scanf("%llu",&n);
a=n;
for ( i=0; n>0; i++) //for loop
{ n=n/10; }
for (k=i; k>=1; k--)
{ d=n/pow(10,k-1);
switch (n)
{
case 0:
printf("zero");
break;
case 1:
printf("one");
break;
case 2:
printf("two");
break;
case 3:
printf("three");
break;
case 4:
printf("four");
break;
case 5:
printf("five");
break;
case 6:
printf("six");
break;
case 7:
printf("seven");
break;
case 8:
printf("eight");
break;
case 9:
printf("nine");
break; }
a=a-d*pow(10,k-1);
}
return(0);
}
-
d=n/pow(10,k-1);
switch (n)
Are you sure?
-
Do you know about / are you allowed to use arrays?
-
No, we have not learned arrays yet.
-
I have no idea what you're trying to do with pow(), OK.
Normal idiom would be to % 10, and save the result, for use in your switch statement.
You can't save it as n, (maybe name it digit), because you're using n<0; as your test condition in the for loop.
Then divide n by 10, and loop back.
logic:
Code:
while n is > 0 (for loop is fine, also)
digit = n mod 10
switch (digit) {
};
n = n divided by 10
end of loop
While i, j, n and x, are very standard variable names for simple loop counter or indexers, or numbers, using single letters which have no bearing on the use of the variable, is a terrible idea. Make your variable names *meaningful* names.
We have the memory to add a great deal of clarity to our programs, by doing this. Why not use it?
P.S. It doesn't matter where you divide n by 10, as long as you do it AFTER the mod statement.
-
Think about when this loop will stop:
Code:
for ( i=0; n>0; i++) //for loop
{ n=n/10; }
It will stop when n is not greater than zero. What cases are those? Well considering that n is only ever reduced in magnitude and thus will not become negative, the only option is zero.
Ooops!?!
-
Both run OK.
Code:
#include <stdio.h>
int main(void) {
int n=1234567, digit;
printf("\nWhile loop:\n");
while(n>0) {
digit = n % 10;
printf("%d\n", digit);
n /= 10;
}
//or
n = 1234567;
printf("\nFor loop:\n");
for(;n>0;) {
digit = n % 10;
printf("%d\n", digit);
n /= 10;
}
return 0;
}