Aisulu Abdraimova
Aisulu Abdraimova

Reputation: 11

Why is the second of two while loops with identical condition not working?

I am taking CS50 Introduction to CS right now. I trying to solve Set 1, Credit. The program is not completed yet, I just wanted to make sure that it counts correctly. There is my code, it takes from the user input which is a positive number. 1st while loop counts every second-to-last digit and add them all together and gives output, 2nd while counts every last digit and adds as well.

Both while loops count correctly if I run them separately. In my case now it counts only the first while. I will appreciate your help!

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

int main(void)
{
    long credit;
    int multiply_by_two, sum_by_two = 0, sum = 0;
    do
    {
        credit = get_long("Number: ");
    }
    while (credit < 0);

    while (credit != 0)
    {
        long second_digit =  credit / 10;
        long last_digit = second_digit % 10;
        multiply_by_two = last_digit * 2;
        if (multiply_by_two > 9)
        {
            sum_by_two += multiply_by_two % 10 + multiply_by_two / 10;
        } else
        {
            sum_by_two += multiply_by_two;
        }
        credit = credit /100;
    }
    while (credit != 0)
    {
        long first_digit = credit % 10;
        sum += first_digit;
        credit = credit / 100;
    }
    printf("First total sum: %d\n", sum_by_two);
    printf("Second total sum: %d\n", sum);
}

Upvotes: 0

Views: 216

Answers (1)

Yunnosch
Yunnosch

Reputation: 26753

The first while (credit != 0) obviously ends with credit==0.
The second while (credit != 0) makes sure that the body is only executed when, you know, credit != 0.

You probably intend the second loop to work on a copy of the initial credit instead of something guaranteed to be 0.

(intentionally not providing a solution here, because of
How do I ask and answer homework questions?)

Upvotes: 1

Related Questions