Here’s a C program to print the numbers that are divisible by a given number or multiples of a given number with output and proper explanation. The program uses for loop.
# include <stdio.h> # include <conio.h> void main() { int i, n, d ; clrscr() ; printf("Enter the limit : ") ; scanf("%d", &n) ; printf("\nEnter the number : ") ; scanf("%d", &d) ; printf("\nThe numbers divisible by %d are :\n\n", d) ; for(i = 1 ; i <= n ; i++) if(i % d == 0) printf("%d\t", i) ; getch() ; }
Output of above program
Enter the limit : 15
Enter the number : 3
The numbers divisible by 3 are : 3 6 9 12 15
Explanation of above program
The integer variable n is the limit determining when to stop the program’s execution, variable d is the number whose multiples are need to be calculate and i is the loop variable.
First, we ask the user to enter a limit (our for loop will start at 1 = 1 and will continue until loop variable exceeds the limit i.e. i > n) and a number (d). Inside the loop, we are checking if the current loop variable (i) is divisible by the variable d i.e. if i % d == 0 then we print the value of i but if the loop variable is not divisible by the variable d then the loop will continue with other values until the loop is terminated. In this way all the values are printed.
Tip: To understand the program you can also take different values and try the above process yourself. It will help you to understand the process much clearly and helps in improving your debugging ability.
Also look at: Program to Find Divisors of a Given Number.
You have explained it exelently
Hi Tanmay,
So bloody thorough! Ah! So happy and blessed out! I feel redeemed by reading out Program to Print Multiples of a Given Number. Keep up the good work!
I tried to move my C code from SUN OS to AIX. It complied successfully on AIX machine where as it throws some memory related error message during run time.
C has three types of storage: automatic, static and allocated. Variable having block scope and without static specifier have automatic storage duration. Variables with block scope, and with static specifier have static scope. Global variables (i.e., file scope) with or without the static specifier also have static scope. Memory obtained from calls to malloc(), alloc() or realloc() belongs to allocated storage class.
It was cool to see your article pop up in my google search for the process yesterday. Great Guide.
Keep up the good work!
Shukran,
Karl
I think this program is wrong
I would like a program that prints multiples of a number that are less than its square , the square of that number
Nice Post. Your article is extremely informative. I really enjoyed it so much. Here I am also giving out some information that might be useful beginners, if you want to know more details, check it out our website.
illegal start of expression
‘this’ is a reference variable in java that refers to the current object of the main method. Let’s make it clear with an example below:
instance