C Programming Examples Tutorial Index

C Loop Programs

Learn how to write a C program that can effectively identify and print all happy numbers up to a specified limit, N, with our simple and easy-to-follow tutorial.



What is a Happy Number?

A number is considered a happy number if it reaches 1 after being repeatedly replaced by the sum of the squares of its digits. For example, 23 is a happy number because:

2^2 + 3^2 = 13
1^2 + 3^2 = 10
1^2 + 0^2 = 1

C Program to Print All Happy Numbers Till N

Here's a C program that prints all happy numbers up to N:

// Include standard I/O and boolean header files
#include <stdio.h>
#include <stdbool.h>

// Function to check if a number is a happy number
bool isHappy(int num) {
    int sum, digit;
    // Loop until num becomes 1 or 4
    while (num != 1 && num != 4) {
        sum = 0;
        // Find the sum of the squares of the digits
        while (num > 0) {
            digit = num % 10;
            sum += digit * digit;
            num /= 10;
        }
        num = sum;
    }
    // Return true if num becomes 1, otherwise false
    return (num == 1);
}

// Main function
int main() {
    int N, i;
    // Ask the user for the upper limit
    printf("Enter the value of N: ");
    scanf("%d", &N);
    
    // Print all happy numbers up to N
    printf("Happy numbers till %d are: ", N);
    for (i = 1; i <= N; i++) {
        if (isHappy(i)) {
            printf("%d ", i);
        }
    }
    printf("\n");
    return 0;
}

Program Output:

Enter the value of N: 50
Happy numbers till 50 are: 1 7 10 13 19 23 28 31 32 44 49

Code Explanation:

The above program is split into two main parts: the isHappy function and the main function:

  • The isHappy function takes an integer and returns whether it's a happy number or not. It uses a while loop to repeatedly square and sum the digits until the sum is either 1 (happy) or 4 (not happy).
  • The main function asks for an upper limit " and iterates from 1 to the ", calling isHappy for each number. If the number is happy, it gets printed.

Conclusion

In this tutorial, you were guided through a C program that helps you identify and print happy numbers up to a specific numerical value, N. The program uses fundamental C programming concepts such as loops and functions, making it easily understandable and accessible to beginners. By following the instructions and implementing the code, you can gain a deeper understanding of these concepts and apply them to real-world scenarios.



Found This Page Useful? Share It!
Get the Latest Tutorials and Updates
Join us on Telegram