1

I am having problems with the while function on the C programming language. It runs too many times, Ignoring the end condition.

#include <stdio.h>

int main()
{
    long long int lenX,lenY,cube,needX,needY,i,t = 0;
    scanf("%lld%lld%lld", &lenX,&lenY,&cube);
    while (needX <= lenX)
    {
        needX + cube;
        i++;
    }
    while (needY <= lenY)
    {
        needY + cube;
        t++;
    }
    printf("%lld\n",i*t);
    return 0;
}

When inputting 6 6 4(the answer should be 4) the output ranges from -8519971516809424873 to 0.

I'm sorry if I missed something obvious. I'm new to the C programming language

EDIT: It doesn't care about the numbers

#include <stdio.h>

int main()
{
    long long int lenX,lenY,cube,needX,needY;
    scanf("%lld%lld%lld", &lenX,&lenY,&cube);
    while (needX*cube <= lenX)
    {
        needX = 574973;
    }
    while (needY*cube <= lenY)
    {
        needY = 4057348;
    }
    printf("%lld %lld %lld\n",needX*needY,needX,needY);
    return 0;
} 

Still outputs:409600 100 4096

  • 1
    I can't see you updating `needX` anywhere. you are just adding value within the while block but not assigning it to anything. I guess you mean `needX += cube;` and same for the other block of while code. it essentially meant `needX = needX + cube`. This would actually update the value of `needX` and help you terminate the while loop. Also such questions should not be posted here, try to debug these in your ide or by adding some print statements to see where you're going wrong. Please have a look here https://ericlippert.com/2014/03/05/how-to-debug-small-programs/ – Saransh Aug 28 '22 at 20:52
  • 1
    somebodywhoisnotyou, Save time. Enable all warnings. – chux - Reinstate Monica Aug 28 '22 at 21:00
  • As mentioned in the answer you have not initializd the variables that you're printing explicitly. In c/C++ these will get assigned garbage value by default referring to whatever is stored in the memory at the time your program ran, hence the varying output ranges you saw. – Saransh Aug 28 '22 at 21:02

1 Answers1

0

These expression statements

    needX + cube;

and

    needY + cube;

have no effect.

It seems you mean

    needX += cube;

and

    needY += cube;

Pay attention to that the variables needX, needY i were not initialized that results in undefined behavior..

This declaration

long long int lenX,lenY,cube,needX,needY,i,t = 0;

initializes to zero only the variable t.

You need to rewrite the declaration at least like

long long int lenX,lenY,cube,needX = 0,needY = 0,i = 0,t = 0;
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335