Home > Software design >  How to take value from a variable and store them in different variables
How to take value from a variable and store them in different variables

Time:10-10

Ok so my question is that if a variable for e.g lets say num = 1562 (num is an integer variable) and I want to take 1 and store it into a different variable and take 5 and store it into a different variable same for 6 and 2 so how can I do this in C-language as I don't think we can use LEFT,MID and Right functions in c language

CodePudding user response:

you can loop through the number and store each digit in an array and on every iteration you can divide by 10 and store the number mod 10 in an index in the array

CodePudding user response:

how can I do this in C-language as I don't think we can use LEFT,MID and Right functions in c language

You can use any functions you wish - simply some are not available in the standard library and you have to write them yourself.

int left(int num)
{
    while(num / 10) num /= 10;
    return abs(num);
}

int right(int num)
{
    return abs(num % 10);
}

int main(void)
{
    int num = 1562;
    int leftVal = left(num);
    int rightVal = right(num);

    printf("left = %d right = %d\n", leftVal, rightVal);
}
  • Related