What happens is that you overwrite your n value using std::cin in the loop. So as long as you keep entering a number smaller than 2, the loop will run infinitely. If you want to enter two integers, do this:
1 2 3
int n, m;
std::cin >> n;
std::cin >> m;
Or alternatively:
1 2
int n, m;
std::cin >> n >> m; //Chain std::cin togerther.
There is no need to make things complicated with a loop if you just need 2 numbers. If you would need 100 integers you would be better off making an array and then using a loop.
what if l want to enter 8 integers? actually l am trying to enter integers using loop. like i said if i want to enter 8 integers using while loop than what should i do?
constint MAX_INTEGERS = 8;
int counter = 0;
int n;
while (counter < MAX_INTEGERS)
{
std::cin >> n;
//Process value n, for example output it. Alternatively, you could store n in an array
std::cout << n << " ";
++counter;
}
The problem you had is that you used the same variable to count integers and to reveive input.
actually l am making a program with 4 functions like avg2, avg6, avg8, avg10. and these functions will get the value from user like avg2 will only accept 2 integers and avg6 will accept only 6 and so on.After getting the values than these functions will give back the average value of integers to the user using classes! and this is my assignment for the monday if you can help me it ill be thankful to you and if you can't than atleast tell me the logic how i can make this program. Thankyou :)
float avg2()
{
int x, y;
std::cin >> x >> y;
return ((float)x + (float)y) / 2; //Float conversion to avoid integer division
}
And so on for your avg4 and avg6 functions. But a way better way would be (you might be able to impress your teacher with that :)
1 2 3 4 5 6 7 8 9 10 11 12
float agv(int n) //n = the amount of numbers
{
int total;
int count = 0;
while (count < n)
{
int number;
std::cin >> number;
total += number;
}
return (float)total / n;
}
can you please write this code with main function? l got confused. Thank you so much :)
float agv(int n) //n = the amount of numbers
{
int total;
int count = 0;
while (count < n)
{
int number;
std::cin >> number;
total += number;
}
return (float)total / n;
}
float agv(int n) //n = the amount of numbers
{
int total;
int count = 0;
while (count < n)
{
int number;
std::cin >> number;
total += number;
}
return (float)total / n;
}
int main())
{
int count;
std::cout << "How many numbers do you want to enter? ";
std::cin >> count;
std::cout << avg(count);
}