ADVERTISEMENT
Print Magic Numbers Till N
#include<stdio.h>
main()
{
int i,j,rows,k=1;
printf("Enter number of rows\n");
scanf("%d",&rows);
for(i=1;i<=rows;i++)
{
for(j=k;j>=1;j--)
{
printf("%d",j);
}
k++;
printf("\n");
}
}C Programming ExamplesCertainly! Let’s break down the code into a detailed explanation:
- Include Header File:
#include<stdio.h>
This line includes the necessary header file stdio.h for input/output operations.
- Function Declarations:
int GetSumOfDigits(int num);
int GetReverseOfNumber(int sumOfDigits);
These lines declare two functions:
GetSumOfDigits: Calculates and returns the sum of digits of a given number.GetReverseOfNumber: Calculates and returns the reverse of a given number.
- Main Function:
main()
{
The program execution begins from the main function.
- Variable Declarations:
int i, num, sumOfDigits, reverseOfNumber;
Variables are declared to store loop counter (i), user input (num), and intermediate results (sumOfDigits, reverseOfNumber).
- User Input:
printf("Enter number to find out all magic numbers till N\n");
scanf("%d", &num);
The user is prompted to enter a number (num), which represents the upper limit for finding “magic numbers.”
- Loop to Find Magic Numbers:
for(i = 1; i <= num; i++)
{
A for loop is initiated, running from 1 to the user-input number (num). This loop iterates over each number within the specified range.
- Calculations:
sumOfDigits = GetSumOfDigits(i);
reverseOfNumber = GetReverseOfNumber(sumOfDigits);
The GetSumOfDigits function is called to calculate the sum of digits of the current number (i). The result is stored in sumOfDigits. Then, the GetReverseOfNumber function is called to calculate the reverse of sumOfDigits, and the result is stored in reverseOfNumber.
- Check for Magic Number:
if(sumOfDigits * reverseOfNumber == i)
{
printf("%d\n", i);
}
The program checks if the product of sumOfDigits and reverseOfNumber is equal to the original number (i). If true, it means the current number is a “magic number,” and it is printed.
- Sum of Digits Calculation Function:
int GetSumOfDigits(int n)
{
int sum = 0, x;
while(n > 0)
{
x = n % 10;
sum = sum + x;
n = n / 10;
}
return sum;
}
This function, GetSumOfDigits, takes an integer n as an argument and calculates the sum of its digits using a while loop. The calculated sum is then returned.
- Reverse of Number Calculation Function:
int GetReverseOfNumber(int n)
{
int rev = 0, x;
while(n > 0)
{
x = n % 10;
rev = rev * 10 + x;
n = n / 10;
}
return rev;
}
This function, GetReverseOfNumber, takes an integer n as an argument and calculates its reverse using a while loop. The calculated reverse is then returned.
The program continues iterating through the loop, checking and printing “magic numbers,” until it completes for all numbers in the specified range. A “magic number” in this context is a number whose sum of digits, when reversed, equals the original number.