Home > OS >  do-while function not returning value
do-while function not returning value

Time:01-26

#include <stdio.h>
#include <cs50.h>
int counter(int n,int x, int y);
int main (void){
    //prompt for start and end year;
    int start;
    do{
        start = get_int("starting population no: ");
    }
    while( start < 9);
    int end;
    do {
        end = get_int("ending population no: ");
    }
    while (end < start);
    // calculate number of years until we reach threshold
    int years = 0;
    counter(years, start, end);
}
int counter(int n, int x, int y){
    do {
        x = x   x / 3 - x / 4;
        n  ;
    }
    while(x < y);
    return n;
    printf("years: %i", n);
}

below function counter is supposed to return the value that'll our year. but its in not returning that value idk what is not working and if my while condition is working well cuz it is not returning anything. pls tell where im wrong.

CodePudding user response:

It is returning a value, but you do nothing with it.

counter(years, start, end);

Should be

int n = counter(years, start, end);
printf("years: %i", n);

You do have a statement that attempts to print the value, but it's not reachable since it's after a return. Always enable your compiler's warnings. It would have caught this error. (With gcc, I use -Wall -Wextra -pedantic -Werror.)

CodePudding user response:

You probably want something like this:

    ...
    // calculate number of years until we reach threshold
    int years = counter(0, start, end);
    printf("years: %i", years);
}

int counter(int n, int x, int y){
    do {
        x = x   x / 3 - x / 4;
        n  ;
    }
    while(x < y);
    return n;
    // don't printf n here, it's pointless
}

There may be more errors elsewhere, I didn't check.

  • Related