0

I am completely new to C and also programming, and I have to make algorithm for: a=2 , b=3 and add "b" to "a" and display results of it until its divisible by 7

I tried something like this but I cant do better, and its sure not working.

#include <stdio.h>
#include <stdlib.h>

{
    float a,b,result;
    a = 2;
    b = 3;
        do { result=a+b;
        } while (result <=7);
    printf("%f\n",result);

return(0);
}

Could you help me please?

Thanks a lot.

2 Answers 2

1

You can check divisibility like this

div = result % 7;

And I think you need to use integer instead float

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    int a, b, result;
    a = 2;
    b = 3;
    do
    { 
        result = a + b;
    }
    while ((result % 7) != 0);
    printf("%f\n", result);
    return(0);
} 
1

My bet is that when you tried to run it, it just sat there, looking like it is doing nothing. Actually, this is an infinite loop. It's running the loop thousands to millions of times over, depending on how long you let it run. Want proof? Add two lines of code:

    int count = 0;  //creates and initializes a counter
    do 
    { 
        result=a+b;
        print("Count = %i \n", count++);  //prints the counter and increments it
    } while (result <=7);

The values of a and b never change inside the loop, so it will add them together to get 5. The code will then run the test to see that it is less than 7 and run the loop again. Since a and b don't change, the result is again 5. The test repeats, passes, and the loop runs again and again, forever.

If this is an assignment, I suspect that you've misread the assignment. If you're supposed to use a loop to do something then the contents of the test condition variable are probably supposed to change within the loop.

Or, perhaps you're simply supposed to check if a condition has been met, in which case you'd use an IF statement to check it.

[EDIT: addition]

Is it possible that you're actually supposed to add a to b until b is 7???? In that case, you should be using something more like b = b + a; inside the loop. In mathematics, this wouldn't make much sense, but in programming, it is a standard way to take a value, add something to it, and store the result back in the original variable. Remember, "=" doesn't mean "equals" in programming. It means "assign whatever is on the right to what is on the left."

Also, unless you really need floats, use integers. Floats have an issue with inexact storage that you'll learn about later.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .