Please edit the codes the I've written here for me to have the correct answer I need. Anyways this program aims to give all the factors of a given positive integer. Example, I entered 6. Then it should output 1,2,3 as its factors.
I'll help with your homework, but I won't write it for you.
Here's the code:
#include <stdio.h>
#include <conio.h>
Get rid of this; it's not C.
int main ()
{
int num, rem, factor = 1, ctr = 1;
printf("Enter a number: ");
scanf("%d", &num);
Check the value returned by scanf(), which tells you how
many numbers it managed to convert. For example, if the user
responds to "Enter a number: " by typing "forty-two", scanf()
will not understand it and will return 0 to tell you that it
couldn't convert anything. You shouldn't go on to check `num'
until you're sure a value has actually been stored in it.
(General note: Although scanf() looks fairly straightforward,
it is startlingly difficult to use for interactive input. Use
it in "toy" programs like this one, but don't expect to be able
to go much further with it.)
if (num < 0 )
printf("The number you have entered is invalid");
... and after this test, the program runs happily onward
with the invalid `num'. Perhaps you should halt the program
here if the test fails.
if (num == 0)
printf("The factor is %d", factor);
else
rem = num % ctr;
Here's where the serious difficulty begins. It looks like
you want to test whether `num' is divisible by `ctr', and keep
on trying successively larger `ctr' values. But the divisibility
check is outside the loop that increases `ctr', so it's only made
for the very first `ctr' value (and always says "Yes, 1 is a
factor." You need to reorganize the code so that it checks each
new `ctr' value for divisibility as it's encountered.
Here's another problem: The `=' and `==' operators mean
different things. As written, this line sets `rem' to 0 and
then says "The test always comes out false."
for(ctr = 1; ctr <= num; ctr++)
{
factor = num / ctr;
Since this loop never executes (because of the faulty `if'
above) you haven't seen that it doesn't work. I'm not sure just
what you want it to do; perhaps it's a confused attempt at a
divisibility test.
printf("The factor: %d", factor);
}
else
ctr = ctr + 1;
getch();
Get rid of this; it's not C.
General outline of a solution to your homework problem:
Read a value
if (reading was unsuccessful) {
emit a complaint
} else if (the value is invalid) {
emit a complaint
} else {
for (each candidate divisor) {
if (it divides the value evenly) {
print it
}
}
}