Reverse Number in C
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program to Reverse a Number Using While and Do-While Loops

šŸ“‘ On this page:
  • Introduction
  • Reverse Number Using While Loop
  • Reverse Number Using Do-While Loop
  • Practice Exercises
  • Frequently Asked Questions
šŸ“š In this tutorial, you will learn:
  • How to reverse a number using while loop in C
  • How to reverse a number using do-while loop in C
  • The difference between while and do-while loops
  • How to extract digits using modulo and division operations
  • Practice exercises to strengthen your understanding

Introduction

In this tutorial, we'll learn how to reverse a number using while and do-while loops in C. Reversing a number is a common programming problem that helps you understand loops, modulo operations, and division.

The main idea is simple: we extract the last digit of the number using the modulo operator (%), build the reversed number by multiplying the existing reversed number by 10 and adding the extracted digit, and then remove the last digit from the original number using division (/).

šŸ’” Key Concept: To reverse a number, repeatedly extract the last digit using n % 10, append it to the reversed number, and remove it from the original number using n / 10.

1. Reverse Number Using While Loop

How to reverse a number with a while loop

In this program, we take a number input from the user and reverse it using a while loop. The loop continues as long as the number is not zero. Inside the loop, we extract the last digit, build the reversed number, and remove the last digit.

C Program Code to Reverse a Number Using While Loop

#include <stdio.h>

int main() {
    int n, rev = 0, rem;

    printf("Enter a number: ");
    scanf("%d", &n);

    while(n != 0) {
        rem = n % 10;
        rev = rev * 10 + rem;
        n = n / 10;
    }

    printf("Reversed number: %d\n", rev);
    return 0;
}
                                    

Output

Enter a number: 12345
Reversed number: 54321
                                

How This Program Works

When you run this program, it declares three integer variables: n (the input number), rev (initialized to 0, to store the reversed number), and rem (to store the remainder). The computer displays "Enter a number:" on the screen and pauses at the scanf function until you type a value. If you enter 12345, that value is saved directly into n.

Next, the execution path reaches the while loop and tests the condition n != 0. Since n is 12345, the test passes, and the program moves inside the loop block.

Inside the loop, it performs three operations:

  • rem = n % 10 — extracts the last digit (e.g., 12345 % 10 = 5)
  • rev = rev * 10 + rem — appends the digit to the reversed number
  • n = n / 10 — removes the last digit from the original number

This cycle repeats until n becomes 0. On each iteration, we extract, build, and remove. Finally, the loop stops, and the program prints the reversed number.


2. Reverse Number Using Do-While Loop

How to reverse a number with a do-while loop

The second program uses a do-while loop to reverse a number. The do-while loop ensures that the reversal process runs at least once, even if the input number is zero. The logic for reversing the number remains the same.

C Program Code to Reverse a Number Using Do-While Loop

#include <stdio.h>

int main() {
    int n, rev = 0, rem;

    printf("Enter a number: ");
    scanf("%d", &n);

    do {
        rem = n % 10;
        rev = rev * 10 + rem;
        n = n / 10;
    } while(n != 0);

    printf("Reversed number: %d\n", rev);
    return 0;
}
                                    

Output

Enter a number: 9876
Reversed number: 6789
                                

How This Program Works

When you run this program, it initializes the variables and prompts you to enter a number. If you enter 9876, that value is stored in n.

Next, the execution path enters the do block directly without checking any conditions upfront. It performs the same three operations: extracts the last digit, appends it to the reversed number, and removes it from the original number.

After completing the first pass, the program checks the condition while(n != 0) at the bottom. If the condition is true, it jumps back to the top of the loop. This cycle repeats until n becomes 0.

The key difference between while and do-while is that the do-while loop guarantees at least one iteration, making it useful when you want the loop to execute even if the condition is initially false.

Practice Exercises

šŸ“ Exercise 1: Reverse a Number with Leading Zeros

What happens if you reverse a number like 1000? Try to modify the program to handle this case.

Show Solution
#include <stdio.h>

int main() {
    int n, rev = 0, rem;
    printf("Enter a number: ");
    scanf("%d", &n);
    int original = n;
    
    while(n != 0) {
        rem = n % 10;
        rev = rev * 10 + rem;
        n = n / 10;
    }
    
    printf("Original: %d\n", original);
    printf("Reversed: %d\n", rev);
    return 0;
}
                                        

šŸ“ Exercise 2: Check if a Number is a Palindrome

Modify the program to check if the original number is equal to its reverse (palindrome).

Show Solution
#include <stdio.h>

int main() {
    int n, rev = 0, rem, temp;
    printf("Enter a number: ");
    scanf("%d", &n);
    temp = n;
    
    while(temp != 0) {
        rem = temp % 10;
        rev = rev * 10 + rem;
        temp = temp / 10;
    }
    
    if(n == rev)
        printf("%d is a palindrome\n", n);
    else
        printf("%d is not a palindrome\n", n);
    
    return 0;
}
                                        

Frequently Asked Questions

How does a C program reverse a number using a while loop?

To reverse a number using a while loop in C, the program takes a number input from the user, initializes rev = 0, and runs the loop as long as n != 0. Inside the loop, it extracts the last digit using n % 10, builds the reversed number using rev = rev * 10 + rem, and removes the last digit using n = n / 10.

What is the difference between while and do-while when reversing a number?

The while loop checks the condition first, so if the number is 0, it won't execute. The do-while loop executes at least once, which can be useful when you want to handle the number 0 as input.

Why do we use modulo (%) and division (/) to reverse a number?

Modulo (%) extracts the last digit, and division (/) removes the last digit. This process repeats until all digits are processed.

Can we reverse a number without using loops?

Yes, you can use recursion or convert the number to a string and reverse it, but loops are the most efficient and commonly used method in C.

šŸ’” Tip: Always store the original number in a temporary variable if you need to preserve it for later use.

šŸŽÆ Key Takeaway: Reversing a number using loops is a fundamental programming skill. It helps you understand how to extract and manipulate digits, which is useful for many other problems like checking palindromes, finding Armstrong numbers, and more.

šŸ“– Related Tutorials

  • While Loop in C
  • Do-While Loop in C
  • Factorial Using While Loop
  • Prime Numbers in C

Previous Topic: -->> Leap Year in C   ||   Next topic: -->> Armstrong Number in C


šŸ”„ C While & Do-While Loop Programs (Practice Set 1)

šŸš€ Practice the most important C while loop and do-while loop programs asked in exams and interviews. These beginner-to-advanced problems will help you master loop concepts quickly.

  1. C Program to Print Odd Numbers from 1 to N (While & Do-While)

    Learn how to print odd numbers using loops in C. A basic problem to understand loop iteration.

  2. C Program to Print Even Numbers from 1 to N

    Understand how to display even numbers using while and do-while loops in C.

  3. C Program to Print Uppercase Alphabets (A to Z)

    Print all uppercase letters using loops. Helps in understanding ASCII values and iteration.

  4. C Program to Print Lowercase Alphabets (a to z)

    Simple loop program to print lowercase alphabets in C.

  5. C Program to Print Numbers from 1 to 10

    Basic beginner example to understand number printing using loops.

  6. C Program to Print Multiplication Table using While Loop

    Take user input and generate a multiplication table. Common interview question.

  7. C Program to Check Positive, Negative or Zero

    Check number type continuously using loops until user exits.

  8. C Program to Find Factorial using While Loop

    Calculate factorial using loops. Important for coding interviews.

  9. C Program to Find Sum of First N Natural Numbers

    Compute sum from 1 to N using loop logic. Core beginner problem.

  10. C Program to Print Prime Numbers from 1 to N

    Learn prime number logic using nested loops in C programming.

  11. C Program to Print Armstrong Numbers from 1 to N

    Understand Armstrong number logic using loops and mathematical operations.

  12. C Program to Print Leap Years using While Loop

    Find leap years using conditions and loops. Useful for real-world logic building.

  13. C Program to Reverse a Number using While Loop

    Reverse digits of a number using loops. Frequently asked interview question.

šŸ“˜ Practice/Assignment Set 2: C While & Do-While Loop Series Programs

1. C Program to Find Sum of Squares from 1 to N using While Loop
Learn how to calculate the sum of squares (1² + 2² + 3² + ... + N²) using while and do-while loops in C. This is a commonly asked logic-building problem in exams and coding interviews.

2. C Program to Find Sum of First N Natural Numbers using While Loop
Write a C program to calculate the sum of natural numbers (1 + 2 + 3 + ... + N) using loops. A basic and important program for beginners learning loop concepts.

3. C Program to Find Sum of Series (1/1! + 2/2! + ... + N/N!)
Practice a slightly advanced loop problem by computing the sum of factorial-based series using while or do-while loops. Helps strengthen logic and mathematical programming skills.

4. C Program to Find Sum of Harmonic Series (1 + 1/2 + 1/3 + ... + 1/N)
Learn how to calculate the harmonic series using loops in C. This program improves understanding of floating-point calculations and loop control.

5. C Program to Find Sum of Series (1 + 3²/3³ + 5²/5³ + ... up to N Terms)
Solve an advanced series-based problem using while loop logic. This type of question is frequently asked in competitive programming and technical interviews.

Other Tutorials
SQL FAQ  Java FAQ  Python FAQ

šŸ“š Explore More Topics

šŸ—„ļø SQL Interview Questions & Answers

SQL SELECT Statement FAQ SQL Restricting & Sorting Data FAQ SQL Group Functions & Aggregated Data FAQ SQL Multiple Tables (JOINs) FAQ SQL Subqueries FAQ SQL DML Statements (Managing Tables) FAQ SQL Indexes, Synonyms & Sequences FAQ SQL DDL (Tables & Relationships) FAQ SQL Views FAQ SQL Indexing Best Practices FAQ SQL Window & Analytic Functions FAQ

šŸ Python Interview Questions & Answers

Python Interview Questions Python Syntax & Variables FAQ Python Data Types FAQ Python If-Else FAQ Python Loops FAQ Python Functions Interview Q Python String Manipulation FAQ Python Lists & Dictionaries FAQ Python Tuples & Sets FAQ Python Exception Handling FAQ Python OOP Interview Questions

ā˜• Java Interview Questions & Answers

Java Introduction Interview Q Java Development Environment FAQ Java Data Types FAQ Java Control Flow & Operators FAQ Java Basic Input/Output FAQ Java Arrays FAQ Java Strings FAQ Java Methods FAQ Java Basic OOP Concepts FAQ Java Advanced OOP Concepts FAQ Java OOP Best Practices FAQ Java Exception Handling FAQ Java Synchronization FAQ Java Threads & Concurrency FAQ Java Collection Framework FAQ Java File I/O & Serialization FAQ Java Serialization & Deserialization FAQ Java Features FAQ Java Inner & Anonymous Classes FAQ Java Memory Management FAQ Java Packages FAQ Java Wrapper Classes FAQ Java Streams & Lambda FAQ

C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • Conditional Statements
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • Loops Statements
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processing
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.