C Program To Check Palindrome Number Using For Loop
In this article, you will learn how to determine if a given integer is a palindrome number using a for loop in C. We will cover the core logic, provide a practical code example, and explain each step in detail.
Problem Statement
A palindrome number reads the same forwards and backward. For example, 121 is a palindrome, but 123 is not. The problem is to develop a C program that takes an integer as input and efficiently checks if it satisfies the palindrome property. This task is fundamental in understanding number manipulation and control flow in programming.
Example
Consider the input number 121.
Expected output: 121 is a palindrome number.
Consider the input number 123.
Expected output: 123 is not a palindrome number.
Background & Knowledge Prerequisites
To understand this article, you should have a basic understanding of:
- C Language Basics: Variables, data types (integers), input/output operations (
printf,scanf). - Arithmetic Operators: Modulo (
%) for getting the last digit, division (/) for removing the last digit. - Control Flow:
forloops for iteration andif-elsestatements for conditional logic.
No specific libraries are needed beyond the standard input/output library (stdio.h).
Use Cases or Case Studies
Checking for palindrome numbers can be applied in various scenarios:
- Data Validation: Ensuring user inputs conform to specific patterns, especially in systems where symmetrical IDs or codes are used.
- Algorithmic Challenges: A common problem in programming competitions and interviews to test basic logic and number manipulation skills.
- Educational Tools: Used as a simple example to teach concepts like loops, conditional statements, and numerical algorithms.
- Cryptography (Simplified context): While not directly used in modern cryptography, the underlying principles of reversing and comparing sequences are foundational in understanding more complex data transformations.
- Game Development: Certain game mechanics or puzzles might involve recognizing symmetrical numbers or patterns.
Solution Approaches
We will focus on the most common and efficient method for checking palindrome numbers: reversing the number and comparing it with the original. We will specifically implement this using a for loop.
Reversing a Number with a for Loop
This approach involves iteratively extracting the last digit of the number, building a new number in reverse, and then comparing this reversed number with the original.
One-line summary: Extract digits from the original number using modulo and division within a for loop to construct its reverse, then compare the reversed number with the original.
Code Example:
// Palindrome Number Check using For Loop
#include <stdio.h>
int main() {
int num, originalNum, reversedNum = 0, remainder;
// Step 1: Get input from the user
printf("Enter an integer: ");
scanf("%d", &num);
originalNum = num; // Store the original number for comparison later
// Step 2: Reverse the number using a for loop
// The loop continues as long as num is greater than 0
// In each iteration, num is divided by 10 to remove the last digit
for (; num > 0; num /= 10) {
remainder = num % 10; // Get the last digit
reversedNum = reversedNum * 10 + remainder; // Build the reversed number
}
// Step 3: Compare the original number with the reversed number
if (originalNum == reversedNum) {
printf("%d is a palindrome number.\\n", originalNum);
} else {
printf("%d is not a palindrome number.\\n", originalNum);
}
return 0;
}
Sample Output:
- Input:
121Enter an integer: 121 121 is a palindrome number.
- Input:
1234Enter an integer: 1234 1234 is not a palindrome number.
- Input:
5Enter an integer: 5 5 is a palindrome number.
Stepwise Explanation for Clarity:
- Variable Declaration:
-
num: Stores the integer entered by the user. -
originalNum: A copy ofnumis stored here becausenumwill be modified during the reversal process. This copy is essential for the final comparison. -
reversedNum: Initialized to0, this variable will store the number built in reverse. -
remainder: A temporary variable to hold the last digit extracted fromnum.
- Input: The program prompts the user to enter an integer using
printfand reads it usingscanf. - Number Reversal (using
forloop):
- The
forloop structurefor (; num > 0; num /= 10)is used. - The initialization part is empty because
numis already initialized. - The condition
num > 0ensures the loop continues as long as there are digits left innum. - The increment/decrement part
num /= 10effectively removes the last digit fromnumin each iteration. - Inside the loop:
-
remainder = num % 10;: This extracts the last digit ofnum. For example, ifnumis 123,remainderbecomes 3. -
reversedNum = reversedNum * 10 + remainder;: This line builds thereversedNum. It shifts the existingreversedNumone decimal place to the left (by multiplying by 10) and then adds theremainder(the current last digit fromnum). - Example:
-
num = 123,reversedNum = 0 - Iteration 1:
remainder = 3,reversedNum = 0 * 10 + 3 = 3,num = 12 - Iteration 2:
remainder = 2,reversedNum = 3 * 10 + 2 = 32,num = 1 - Iteration 3:
remainder = 1,reversedNum = 32 * 10 + 1 = 321,num = 0
- Comparison: After the loop finishes (when
numbecomes 0),reversedNumholds the reverse of theoriginalNum. Anif-elsestatement comparesoriginalNumwithreversedNumto determine if it's a palindrome. - Output: A message indicating whether the number is a palindrome or not is printed to the console.
Conclusion
Determining if a number is a palindrome is a classic programming problem that effectively uses arithmetic operations and looping constructs. By reversing the number digit by digit and comparing it with the original, we can efficiently check its palindrome property. The for loop provides a concise way to implement this reversal process.
Summary
- A palindrome number reads the same forwards and backward.
- The problem involves reversing an integer and comparing it to its original value.
- Key operations are modulo (
%) to get the last digit and division (/) to remove it. - A
forloop can effectively control the digit extraction and reversal process. - A copy of the original number must be stored before starting the reversal, as the original number is modified.