63.6k views
3 votes
Assume that an int variable x that has already been declared,and initialized to a non-negative value. write an expression whose value is the last (rightmost) digit of x.

2 Answers

2 votes

Answer:

x % 10

Explanation:

Given that an int variable x has been declared and initialized to a non-negative value. In order to determine the last digit of x, we need to find the remainder of x when divided by 10. In programming languages such an operation is represented using the modulus(%) operator. So the required expression is given by x%10.

For example , if x = 29, then x%10 will be 9, that is remainder of 29 when divided by 10.

User MrLeeh
by
5.1k points
5 votes

We know that an int variable, x, has been declared

It has been assigned a non-negative value

We need to write an expression that extracts the rightmost digit of x

The logic for doing so would be to divide the number by 10, and checking the remainder. The remainder will always yield the rightmost digit. In case the number is a multiple of 10 then the remainder would be 0 (which would be the rightmost digit of the number)

So we can do so by:

int y = x % 10;

% is the modulo function, which returns the remainder after carrying out division

we have declared y to be int, as % will always return int values.