﻿ C Program: Non-negative integers with same last digit

# C Exercises: Check if two given non-negative integers have the same last digit

## C-programming basic algorithm: Exercise-13 with Solution

Write a C program to check if two given non-negative integers have the same last digit.

C Code:

``````#include <stdio.h> // Include standard input/output library
#include <stdlib.h> // Include standard library for additional functions

// Function declaration for 'test' with two integer parameters
int test(int x, int y);

int main(void){
// Call the function 'test' with arguments 123 and 456, and print the result
printf("%d",test(123, 456));
printf("\n"); // Print a newline for formatting

// Call the function 'test' with arguments 12 and 512, and print the result
printf("%d",test(12, 512));
printf("\n"); // Print a newline for formatting

// Call the function 'test' with arguments 7 and 87, and print the result
printf("%d",test(7, 87));
printf("\n"); // Print a newline for formatting

// Call the function 'test' with arguments 12 and 45, and print the result
printf("%d",test(12, 45));
}

// Function definition for 'test'
int test(int x, int y)
{
// Check if the absolute value of the last digit of 'x' is equal to the absolute value of the last digit of 'y'
return abs(x % 10) == abs(y % 10);
}
``````

Sample Output:

```0
1
1
0
```

Explanation:

```int test(int x, int y) {
return abs(x % 10) == abs(y % 10);
}
```

The above function takes two integers x and y as input and returns 1 if their last digits are equal, otherwise 0. The function first computes the remainder of x and y when divided by 10 using the modulus operator %. Then, it takes the absolute value of the remainders using the abs() function to make sure that the result is positive. Finally, it compares the remainders and returns the result of the comparison.

Time complexity and space complexity:

The Time complexity of the function is O(1) as it performs a fixed number of operations regardless of the input size.

The Space complexity of the the function is O(1) as it uses a constant amount of space.

Pictorial Presentation:

Flowchart:

C Programming Code Editor:

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

﻿