I am writing a C program to repeat a series of question specified times. I ask user to enter the number of attempts they want and then I run the following while loop based on their number, but the problem is the loop keeps repeating. It does not stop at the specified number of attempt. Here is the code:
#include <stdio.h>
int main(void){
int num1,num2,high,low,average,subtotal,total_aver;
printf("Enter number of tries you want:");
scanf("%d", &num1);
while (num1 < num1 + 1) {
printf("Try number: ");
scanf("%d", &num2);
printf("Enter high ");
scanf("%d", &high);
printf("Enter low ");
scanf("%d", &low);
subtotal = high + low;
total_aver = subtotal / 2;
printf("Average temperature is: %d", total_aver);
}
}
If user enters 3 for number of tries then the program should ask those question in inside the loop three times, but it keeps repeating without ending.
while (num1 < num1 + 1) // condition is never false
Well this is infinite loop . It will continue and continue.
Write loop like this if you want to iterate number of times -
int i=0;
while(i<num1){
// your code
i++;
}
Or without any extra variable -
while(num1>0){
// your code
num1--;
}
This happens because the condition in the while
is wrong. Infact, assigning to num1
to any value, it will exit when num1
will be equal to num1+1
. Is this impossibile, isn't it? You have to use another variable to take count of times you repeat the loop. Fix this way:
int count=0;
while(count<num+1){
//your code
count=count+1;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.