Simple homework code doesn't work

Hello, this is my first code I have writen but it doesn't work. The objective is to print out second smalest number from user input. My code doesn't work if user inputs more than 3 numbers and I don't know why. please help.

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
46
47
48
49
50
51
  int main()
{
using namespace std;
 int x;
 int y;
 int l;
 int n;
 int repeat;
do
{


 do
 {
 cout<<"How many numbers there will be?"<<endl; //needs atleat 2 numbers
 cin>>n;
 if(n<=1) cout<<"not enough numbers"<<endl;
 if (n>1)
 {
     cout<<"enter number"<<endl;    //first two entered numbers that will be changed later in the loop
     cin>>x;
     cout<<"enter number"<<endl;
     cin>>y;
 }
 }while(n<=1);

 n=n-2;

for(n>0; n--;)              // loop changes first two entered numbers so one is smallest and second one is second smallest n times 
{
cout<<"enter number"<<endl;
cin>>l;
if(x>y, l<x, l>y) x=l;
if(x>y, l<=y) x=y; y=l;
if(y>x, l<y, l>x) y=l;
if(y>x, l<=x) y=x, x=l;
if(x=y, l<x) l=x;




}

if(x>=y)cout<<"second smaleset number is  "<<x<<endl;     //prints second smalest number from user input
if(y>x) cout<<"second samlest number is  "<<y<<endl;
cout<<"do you want to repeat\n yes(1) \no(0)?"<<endl;
cin>>repeat;
}while(repeat==1);

return 0;
}
Last edited on
My code doesn't work if user inputs more than 3 numbers and I don't know why.
Well, x,y,l are your three numbers. if you want more you need more variables or an array.
Well, x,y,l are your three numbers. if you want more you need more variables or an array.

I disagree. Certainly an array is a vast overkill, it involves storing many numbers which are of no interest whatsoever.

The objective is to print out second smalest number from user input.


Here just three numbers are of interest:
• the latest number input by the user.
• the smallest number so far.
• the second smallest number so far.

I've not fully analysed the code, but a quick observation.

The if statements are not correct.
For example this line has two significant errors:
 
if(x>y, l<=y) x=y; y=l;

First, the separate conditions should be combined with the logical and operator &&
Second, if more than one statement is to be controlled by the if condition, they need to be grouped together using braces { }

1
2
3
4
5
if (x>y && l<=y)
{
    x=y; 
    y=l;
}


Those same errors occur throughout and need to be corrected as shown. There may still be logic errors - I didn't check - but the code will at least stand a chance of executing as intended.
Last edited on
line 20 is one input.
line 22 is another.

and line 32. but no more.
how many numbers will you put in? 7
n = 7

on line 18 if 7 > 1 then you get the two inputs but no more. It does not matter that n = 7 and should give 7 inputs.
Topic archived. No new replies allowed.