Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C write number digits, one by one and in extension, in a new line

Tags:

c

I'm new in C and I can't do a simple exercise for school.

I want to do something like this:

 Please insert a number: 12345
 five
 four
 three
 two
 one

Basically, the user inputs a number and them the program writes, in a new line, the number from the last significant number to the most.

This is to do with the switch function and only basic programming skills.

I have this:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int num; printf("Please insert a number: "); scanf("%d", &num);
    switch(num){
    case 1:printf("One\n");break;
    case 2:printf("Two\n");break;
    case 3:printf("Three\n");break;
    case 4:printf("Four\n");break;
    case 5:printf("Five\n");break;
    case 6:printf("Six\n");break;
    case 7:printf("Seven\n");break;
    case 8:printf("Eight\n");break;
    case 9:printf("Nine\n");break;
    case 0:printf("Zero\n");break;
    }
} 

I I use a number between 0 and 9 it works ok but a number bigger then that it does not do nothing.

The first problem i cant solve is to, in a number, get the digit position. I believe that In my code, the break isn't doing nothing...

Sorry if I can't explain me better but English is not my native language.

Regards,

Favolas

############################## In Progress Solution (does not work if number % 10 gives 0¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬
#include <stdio.h>
#include <stdlib.h>

int main()
{
    int num; printf("Please insert a number: "); scanf("%d", &num);
    int i,digit;
    for (i = 0; num%10!=0;i++){
        digit = num % 10;
        switch(num){
        case 1:printf("One\n");break;
        case 2:printf("Two\n");break;
        case 3:printf("Three\n");break;
        case 4:printf("Four\n");break;
        case 5:printf("Five\n");break;
        case 6:printf("Six\n");break;
        case 7:printf("Seven\n");break;
        case 8:printf("Eight\n");break;
        case 9:printf("Nine\n");break;
        case 0:printf("Zero\n");break;
        }
        num = num / 10;
    }
} 
like image 670
Favolas Avatar asked Mar 02 '11 11:03

Favolas


1 Answers

The number 123 is 100 + 20 + 3 or 1*10^2 + 2*10^1 + 3*10^0.

You need to isolate the individual digits from the input.

Hint: use the / and % operators

 12345 % 10 ==> 5
 12345 / 10 ==> 1234

 1234 % 10 ==> 4
 1234 / 10 ==> 123

 123 ... ... ...
like image 134
pmg Avatar answered Sep 26 '22 15:09

pmg