0

I have been trying to return value "a" to print it from while loop but can't find any ways so far.

#include <cs50.h>
#include <stdio.h>
#include <math.h>

int main(void)
{
    float f;
        do
    {
        f = get_float("Change:");
    }
    while (f < 0);

int c = round(f * 100);

    int a = 0;
    while (c > 25)
    {
        a = c - 25;
        return a;
    }
    printf("%i\n", a);

    return 0;
}
2

I think you have a misconception of how return works. A return statement acts like a short-circuit. It causes the currently executing function, or main, to immediately terminate processing and return control to the calling code. No code following the return statement within the same function, or main, will be executed.

When a return statement is in a function, it causes that function to immediately stop processing and return control to the code (main or another function) that called the function. If the return statement includes a variable name or a value, that var or value will be returned to the calling function.

If the return statement is in main() itself, it causes the program to immediately terminate and return the value to the operating system, or to whatever program caused main to be executed.

A return statement is NOT for returning a value from a loop.

If you want to preserve a value from a loop, that value needs to be stored in a variable that was created before the loop was started. This is more fully explained in the lecture on variable scope (which I'm assuming you haven't seen yet.)

You have two perfect examples in your code above. Values are stored in the a and f variables and used after the loops. Just remove the return a; statement and you should be able to do what you are trying to accomplish.

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

| improve this answer | |
  • Thank you for detailed answer. I watched the lecture but forgot this. So here a question: How to properly memorise information from lectures? Could you give a few tips? – San Antonik Jul 10 '19 at 13:55
  • Simple. Practice and repetition of using concepts and lots of coding. – Cliff B Jul 11 '19 at 2:10

You must log in to answer this question.

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