Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
C program to write all digits into words using for loop
In C programming, converting digits to their word equivalents is a common task that helps beginners understand conditional statements and loops. This program takes a range of digits and prints each digit as its corresponding word using a for loop.
Syntax
for(initialization; condition; increment) {
// Convert digit to word using if-else statements
}
Example: Converting Digits to Words in a Range
This example demonstrates how to convert all digits from 3 to 8 into their word representations using a for loop −
#include <stdio.h>
void digitToWord(int digit) {
if(digit < 0 || digit > 9) {
printf("Beyond range of 0 - 9");
} else if(digit == 0) {
printf("Zero");
} else if(digit == 1) {
printf("One");
} else if(digit == 2) {
printf("Two");
} else if(digit == 3) {
printf("Three");
} else if(digit == 4) {
printf("Four");
} else if(digit == 5) {
printf("Five");
} else if(digit == 6) {
printf("Six");
} else if(digit == 7) {
printf("Seven");
} else if(digit == 8) {
printf("Eight");
} else if(digit == 9) {
printf("Nine");
}
}
int main() {
int start = 3, end = 8;
printf("Converting digits %d to %d into words:<br>", start, end);
for(int i = start; i <= end; i++) {
digitToWord(i);
printf("<br>");
}
return 0;
}
Converting digits 3 to 8 into words: Three Four Five Six Seven Eight
Example: Using Array-Based Approach
A more efficient approach uses an array to store digit words, eliminating multiple if-else conditions −
#include <stdio.h>
int main() {
char *digitWords[] = {"Zero", "One", "Two", "Three", "Four",
"Five", "Six", "Seven", "Eight", "Nine"};
int start = 3, end = 8;
printf("Using array approach:<br>");
for(int i = start; i <= end; i++) {
if(i >= 0 && i <= 9) {
printf("%s<br>", digitWords[i]);
} else {
printf("Invalid digit<br>");
}
}
return 0;
}
Using array approach: Three Four Five Six Seven Eight
Key Points
- The if-else ladder approach is beginner-friendly but verbose for larger ranges.
- The array approach is more efficient and scalable with O(1) lookup time.
- Always validate input to ensure digits are within the valid range (0-9).
- The for loop iterates through the specified range, calling the conversion function for each digit.
Conclusion
Converting digits to words using a for loop demonstrates fundamental programming concepts like loops, conditional statements, and functions. The array-based approach provides a cleaner and more maintainable solution for digit-to-word conversion.
