Exiting do while loop

How do I exit the do while loop after k=3, so it won't exit after I type in an answer, but before that?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
  #include <iostream>
#include <math.h>
#include <iomanip>

//#include <stdlib.h>
using namespace std;

int main (){
	double x[3],sum;
	int k;
	char answer;

	k=0;

	do
	{

		k=k+1;

		cout<<"\n"<<k;
		cout<<"Type in value of x";
		cin>>x[k-1];
		cout<<"Try again?";
		cin>>answer;

		
	while((answer=='j') && (k<3));

	sum=0;
	for(int j=1; j<=k; j++){
		sum+=x[j-1];
	}
	cout<<sum;

	return 0;
}
Your while-loop executes once, then checks the value of the variable answer to see if it is equal to 'j' and to see if k less than three. The only way this will execute more than once is if you type in the letter 'j' for answer.

But what are you trying to do? It looks like you're trying to loop up to three times to see if the user enters a value into your double array. I can only guess.
Well I want the user to have the option of choosing a number three times which then will be added together. But after the loop has executed three times I still get the output "Try again" and no matter what I type I still get the final output of the three numbers added together. So the sum is correct, but it would just look more neat if the loop would stop executing after k=3. Hope it makes sense what I'm saying
I tried writing in the do-while loop if(k==3){break;} but that didn't work.
But what is the answer == 'h' business about?
I think you mean 'j'. But it is just j for yes. So the user has the option to write another x
I think you are missing a curly bracket next to your [while].
Figured it out

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
  
#include <iostream>
#include <math.h>
#include <iomanip>

//#include <stdlib.h>
using namespace std;

int main (){
	double x[3],sum;
	int k;
	char svar;

	k=0;

	do
	{

		k=k+1;

		cout<<"\n"<<k;
		cout<<"Write value of x";
		cin>>x[k-1];



		if(k==3){
			
		}

		else if(k<3){
			cout<<"Try again";
			cin>>svar;
		}
	}
	while((svar=='j') && (k<=2));

	sum=0;
	for(int j=1; j<=k; j++){
		sum+=x[j-1];
	}
	cout<<sum;

	return 0;
}
Last edited on
Topic archived. No new replies allowed.