I have written a program in C++ that allows you to enter 3 numbers. The numbers can be entered one after the other, or all at ounce (as long as each value has a space between it). using a while(cin>>current). The numbers are then sorted with arrays and loops to give and the user is shown the entire process.
My issue is something I can't understand, when I enter 3 values such
as
1 2 3 4 5 6 7
Enter three integer values (followed by 'enter'): 16 10 11
// I get this in response
val1: 16 val2: 0 val3: 0
val1: 10 val2: 16 val3: 0
val1: 10 val2: 16 val3: 11
3 10 2
val1: 10 val2: 16 val3: 3
of course this isn't working properly, i want it to show me each instance of the array, and its suppose to fill as 10 11 16. and then show 2 3 10 for the next instance of letters. Example for everyone
// Bradley Latreille dd/mm/yy
// PPP Template for excersises in the early chapters
#include "std_lib_facilities.h" // needed up to Chapter 12
int main() {
try
{
cout << "Enter three integer values (followed by 'enter'): ";
int previous;
int values[3] = {0,0,0}; // our 3 values
int i = 0; // iteration count
int current;
// go into loop each iteration is 1 of the 3 values
while(cin>>current)
{
if(previous>current){
values[i-1] = current;
values[i] = previous;
}else{
values[i] = current;
}
cout << "val1: "
<< values[0] << " val2: "
<< values[1] << " val3: "
<< values[2] << '\n';
previous=current;
i++;
}
keep_window_open(); // for some windows(tm) setups
}
catch(runtime_error e) { // this code is to produce error messages
// *Explained in chapter 5*
cout << e.what() << '\n';
keep_window_open("~"); // for some Windows(tm) setups
}
}
Any help would be greatly appreciated :) For begginers who can't get my code to run just run this
It occurred to me that this method is clearly to advanced for my knowledge so I used the approach I was suppose to use and do all the checking individually.
#include <iostream>
#include <algorithm> // for std::swap
usingnamespace std ;
int main()
{
constint NVALUES = 10 ;
cout << "Enter " << NVALUES << " integer values (followed by 'enter'): ";
int values[NVALUES] = {};
for( int i = 0 ; i < NVALUES ; ++i ) cin >> values[i] ;
// bring the smallest value to the front,
// the next smallest value to the position one and so on
for( int i = 0 ; i < NVALUES ; ++i ) // repeat for each position in the array
{
// for each position j which is after position i
for( int j = i+1 ; j < NVALUES ; ++j ) // invariant: i < j
{
// if the value that is earlier in the array
// is greater than the value which is at a later position
if( values[i] > values[j] ) swap( values[i], values[j] ) ; // swap them
}
}
// print out the sorted values. we will use a rage-based loop for variety
// http://www.stroustrup.com/C++11FAQ.html#forfor( int v : values ) cout << v << ' ' ;
cout << '\n' ;
}