c++ code

Can anyone give me a C++ code that uses a while loop and if statements to find the middle number of the three integers by the users.

only if you can start it.
closed account (oGN8b7Xj)
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

#include <iostream>

#define N 3

int main()
{
  const int a[N] = {11, 2, 33};

  int i (0);

  do
  {
    const int i1 ((N + i - 1) % N);
    const int i2 ((i + 1) % N);
  
    if ( ((a[i] > a[i1]) && (a[i] < a[i2]))
       ||((a[i] < a[i1]) && (a[i] > a[i2]))
       )
    {
      std::cout << a[i] << std::endl;
    }
  } while (++i < N);

  return 0;
}

#include <iostream>
using namespace std;

int main(){
	int x, y, z;
	char ans;

	do{
	//ask the three numbers	
	cout << "Type 3 numbers: ";
	cin >> x >> y >> z;
	 
	//compare which of the three numbers is the smallest.   
	if(x < y && x < z){
	cout << endl << x << " is smallest";
}
	if (y < x && y < z){
	cout << endl << y << " is smallest";
}
	if (z < x && z < y){
	cout << endl << z << " is smallest";
}

    //compare which of the three numbers is the biggest.
    if(x > y && x > z){
	cout << endl << x << " is biggest";
}
	if(y > x && y > z){
	cout << endl << y << " is biggest";
}
	if(z > x && z > y){
	cout << endl << z << " is biggest";
}

    //compare which of the three numbers is the middle number.
    if(x > y && x < z){
    cout << endl << x << " is the middle number";
}
    if(y > x && y < z){
    cout << endl << y << " is the middle number";
}
    if(z > x && z < y){
    cout << endl << z << " is the middle number";
}
	    
    //ask if the user wants to repeat	
	cout << endl << "Repeat? [Type Y to repeat.]: ";
	cin >> ans;
	    
	}while(ans=='Y' || ans== 'y' || ans);
	
return 0;
}
closed account (48T7M4Gy)
Or,
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
#include <iostream>

using std::cout;
using std::endl;

int main()
{
	int trio[] = { 11, 2, 3 };
	int total = 0, min = trio[0], max = trio[0];


	int i = 0;
	while (i < sizeof(trio) / sizeof(int))
	{
		total += trio[i];
		if (trio[i] < min)
			min = trio[i];

		if (trio[i] > max)
			max = trio[i];
		i++;
	}

	cout << "Middle number: " << total - max - min << endl;

	return 0;
}


Middle number: 3
 
Exit code: 0 (normal program termination)
Last edited on
closed account (48T7M4Gy)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>

using std::cout;
using std::endl;

int main()
{
	int trio[] = { 11, 2, 3 };
	int total = 1, min = trio[0], max = trio[0];

	for (int i = 0; i < sizeof(trio)/sizeof(int); i++)
	{
		total *= trio[i];
		if (trio[i] < min)
			min = trio[i];
		
		if (trio[i] > max)
			max = trio[i];
	}

	cout << "Middle number: " << total / min / max << endl;
	return 0;
}

Middle number: 3
 
Exit code: 0 (normal program termination)

Multiplication seems to work too. It doesn't appear that signs are an issue.
Last edited on
Topic archived. No new replies allowed.