Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

How can I reuse the inputted value for my second while loop?

+4 votes
asked Nov 18, 2021 by Lexus Guevara (1,010 points)
#include <stdio.h>

int main()
{
    int num1, num2, product = 0, quotient = 0, remainder = 0;
    
    printf("Input value for num1 : ");
    scanf("%d", &num1);
    printf("Input value for num2 : ");
    scanf("%d", &num2);
    
    while(num2){
        product += num1;
        num2--;
    }
    
    
    while(num1 >= num2){
        num1 = num1 - num2;
        quotient++;
    }
    
    printf("The product of %d and %d is : %d", num1, num2, product);
    printf("\nThe integer quotient of %d and %d is : %d", num1, num2, quotient);

    return 0;
}

1 Answer

0 votes
answered Nov 18, 2021 by ARTEMII KOZHEMIAK (540 points)
selected Nov 22, 2021 by Lexus Guevara
 
Best answer

As I see, you decrease num2 in the while loop. So if you want to reuse it, you have to not change it -- create a temporary variable that will store the value. 2 ways to do:

1) If you want to maintain your while loop: 

//add temp variable
int temp = num2;

while(temp){
        product += num1;
        temp--;
}

//if you want to save num1 as well
temp = num1;
while(temp >= num2){
        temp = temp - num2;
        quotient++;
}

2)I would suggest using for loops, since they allocate the variable on enter and deallocate on exit, thus less memory usage. Also more convenient:

//variable creation; boolean statement; changer

//our product
for(int temp = num2; temp; temp--){
    product += num1;
}

//our quotient
for(int temp = num1; temp>= num2; temp-=num2){//  temp -= <var> is equivalent to temp = temp - <var>
    quotient++;
}
    

commented Nov 19, 2021 by Lexus Guevara (1,010 points)
Thank you very much, I don't really understand the forloops that's why i used while loops. but atleast I understand now how to use the forloops. thankyou!
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...