SshauryaaDaGreat
SshauryaaDaGreat

Reputation: 11

I needed to answer a question in C language (About modulo operator) I'll list it below, I checked the answer of the question but couldn't understand

The question:

A 4 digit number is entered through keyboard. Write a C program to print a new number with digits reversed as of orignal one. E.g.-
Input: 1234 Output: 4321
Input: 5982 Output: 2895

and my code is:

#include <stdio.h>

int main()
{
    int x;
    printf("Enter number\n");
    scanf("%d", &x);
    int first_digit = x % 10;
    int second_digit = (x / 10) % 10;
    int third_digit = (x / 100) % 10;
    int fourth_digit = (x / 1000) % 10;
    int new_number = (first_digit * 1000) + (second_digit * 100) +
                     (third_digit * 10) + (fourth_digit * 1);
    printf("%d\n", new_number);
    return 0;
}

It will be appreciated if you could help me! Thanks! Explain me how this reverses the number!

Upvotes: 1

Views: 99

Answers (2)

Bananenk&#246;nig
Bananenk&#246;nig

Reputation: 543

I'll try to explain it to you in your code for example input 1234:

#include <stdio.h>

int main()
{
  int x;
  printf("Enter number\n");
  scanf("%d",&x);

  int first_digit  = x / 1;     // first_digit  = 1234
  int second_digit = x / 10;    // second_digit = 123
  int third_digit  = x / 100;   // third_digit  = 12
  int fourth_digit = x / 1000;  // fourth_digit = 1

  // obtain last digit
  first_digit  = first_digit  % 10;  // first_digit  = 4
  second_digit = second_digit % 10;  // second_digit = 3
  third_digit  = third_digit  % 10;  // third_digit  = 2
  fourth_digit = fourth_digit % 10;  // fourth_digit = 1

  first_digit  *= 1000;  // first_digit  = 4000
  second_digit *= 100;   // second_digit = 300
  third_digit  *= 10;    // third_digit  = 20
  fourth_digit *= 1;     // fourth_digit = 1

  // 4000 + 300 + 20 + 1 = 4321
  int new_number = first_digit + second_digit + third_digit + fourth_digit;
  printf("%d\n",new_number);
  return 0;
}

So as @pmg pointed out in his answer, the modulo operator does all the work.

Upvotes: 0

pmg
pmg

Reputation: 108978

For example

int third_digit = (x/100)%10;

if x is 1234, x / 100 is 1234 / 100 or 12 (and remainder 34), and 12 % 10 is 2 (with a quotient of 1).

x / 100 has the value of x divided by 100 (ignoring any decimals since it's all integers).
x % 10 has the remainder of the division of x by 10.

Upvotes: 1

Related Questions