﻿ C - Number sums and their reverses

# C Programming: Number sums and their reverses

## C Programming Mathematics: Exercise-32 with Solution

Write a C programming to check whether a given integer can be expressed as the sum of any non-negative integer and its reverse. Return true otherwise false.

Example:
Input: = 554
Output: true
Explanation: 371 + 173 = 554
Input: = 51
Output: false
Explanation: It cannot be expressed as per said condition.
Input: = 55
Output: true
Explanation: 41 + 14 = 55
Input: = 181
Output: true
Explanation: 140 + 041 = 181

Test Data:
(554) -> 1
(51) -> 0
(55) -> 1
(181) -> 1

Sample Solution:

C Code:

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

int rev(int n){
int result = 0, t, r;
for(t=n;n!=0;n=n/10){
r=n % 10;
result=result*10+r;
}
return result;
}

bool test(int n){
if(n==0) return true;
for(int i=n/2;i<n;i++){
if(i+rev(i)==n){
return true;
}
}
return false;
}

int main(void) {
int n = 544;
printf("n = %d",n);
printf("\nTest said number can be expressed as the sum of any non-negative integer and its reverse = %d", test(n));
n = 51;
printf("\nn = %d",n);
printf("\nTest said number can be expressed as the sum of any non-negative integer and its reverse = %d", test(n));
n = 55;
printf("\nn = %d",n);
printf("\nTest said number can be expressed as the sum of any non-negative integer and its reverse = %d", test(n));
n = 181;
printf("\nn = %d",n);
printf("\nTest said number can be expressed as the sum of any non-negative integer and its reverse = %d", test(n));
}
```
```

Sample Output:

```n = 544
Test said number can be expressed as the sum of any non-negative integer and its reverse = 1
n = 51
Test said number can be expressed as the sum of any non-negative integer and its reverse = 0
n = 55
Test said number can be expressed as the sum of any non-negative integer and its reverse = 1
n = 181
Test said number can be expressed as the sum of any non-negative integer and its reverse = 1

```

Flowchart: C Programming Code Editor:

Improve this sample solution and post your code through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

﻿

## C Programming: Tips of the Day

What's the point of const pointers?

const is a tool which you should use in pursuit of a very important C++ concept:

Find bugs at compile-time, rather than run-time, by getting the compiler to enforce what you mean.

Even though it does not change the functionality, adding const generates a compiler error when you're doing things you didn't mean to do. Imagine the following typo:

```void foo(int* ptr)
{
ptr = 0;// oops, I meant *ptr = 0
}
```

If you use int* const, this would generate a compiler error because you're changing the value to ptr. Adding restrictions via syntax is a good thing in general. Just don't take it too far -- the example you gave is a case where most people don't bother using const.

Ref : https://bit.ly/33Cdn3Q