LearnFrenzy
Sign in Take a free test

Operators and Expressions · Operator Programs · Question 8

Reverse a three-digit number without loops in C Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 8 Back to Exercise

Reverse any three-digit number using only / and %.

Solution
main.c
#include <stdio.h>

int reverse3(int n) {
    return n % 10 * 100 + n / 10 % 10 * 10 + n / 100;
}

int main(void) {
    printf("%d %d %d\n", reverse3(472), reverse3(905), reverse3(100));
    return 0;
}

Output Verified by compiling and running

274 509 1

Units become hundreds, tens stay tens, hundreds become units. n / 10 % 10 is the tens digit (left to right: divide, then take the remainder). Reversing 100 gives 001, which as a number is 1.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links