C (programming language)

C program to print number between 1 to 10 in character Format

Understanding the Task

  • Goal: Create a C program that prints numbers from 1 to 10 as their corresponding English words (e.g., “One”, “Two”, “Three”).
  • Key Concepts:
    • Conditional statements (if-else): Choosing code blocks based on conditions.
    • Loops (for): Iterating through numbers.
    • Character arrays: Storing text strings.

Step-by-Step Guide

1. Header Inclusion

C

#include <stdio.h>
  • Explanation: Includes the standard input/output library for functions like printf.

2. Main Function

C

int main() {
    // Code statements here
    return 0;
}

3. Define Number-Character Mappings

C

#define NUMBER_WORDS 10

const char *number_chars[NUMBER_WORDS] = {
    "One", "Two", "Three", "Four", "Five",
    "Six", "Seven", "Eight", "Nine", "Ten"
};
  • Explanation:
    • NUMBER_WORDS: Constant for the number of words to map.
    • number_chars: Array of character pointers (strings) for each number’s word representation.

4. Use a Loop to Print Number Words

C

for (int i = 0; i < NUMBER_WORDS; i++) {
    printf("%s\n", number_chars[i]);  // Access and print each word
}

5. Complete Code

C

#include <stdio.h>

#define NUMBER_WORDS 10

const char *number_chars[NUMBER_WORDS] = {
    "One", "Two", "Three", "Four", "Five",
    "Six", "Seven", "Eight", "Nine", "Ten"
};

int main() {
    for (int i = 0; i < NUMBER_WORDS; i++) {
        printf("%s\n", number_chars[i]);
    }

    return 0;
}

Key Points

  • The number_chars array serves as a lookup table for number-word mappings.
  • The for loop iterates through indices 0 to 9, accessing the corresponding words in the array.
  • The printf function prints each word on a new line.
  • This approach avoids lengthy if-else chains for individual number checks.
  • It’s easily adaptable for different number ranges or languages by modifying the number_chars array.

CodeForHunger

Learn coding the easy way. Find programming guides, examples and solutions with explanations.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button