0
I want to make a program that reads 5 numbers and tells me the largest number, the smallest number and the sum of the numbers, in C++ using the loop for
.
I’ve tried and done so:
#include <iostream>
using namespace std;
int main()
{
int n, i, h, l, s;
cout<<"Digite 5 numeros:\n";
for (i=0; i<5; i++)
{
cin>>n;
s+=n;
if (n>l)
{
n=h;
}
else
{
n=l;
}
}
cout<<"O maior numero e "<<h<<", o menor e "<<l<<" e a soma e "<<s<<".\n";
return 0;
}
Use more intuitive variable names. This increases the readability of the code. Usually in this type of exercise the variable
menorvalor
starts receiving a very high value andmaiorvalor
gets -1. Then comparisons are made and if they meet the cases they are replaced.– Amzero
There are 3 problems with your code. 1) The s variable is not being initialized, so its initial value will be junk, not what you want. 2) You should pay attention to what to do in the first loop, because the variables h and l also have no value yet, only junk, so any comparison made between them and n will not have the expected result. 3) Check better which comparisons you have to make in each loop, and what action to take in each case. You will want to update the h and l variables inside if/Else, not n, as you are doing now.
– luislhl
using namespace std;

int main()
{
 int n, i, h=0, l=0, s=0;

 cout<<"Digite 5 numeros:\n";

 for (i=0; i<5; i++)
 {
 cin>>n;
 s+=n;
 
 if(i==0)
 {
 l=n;
 }

 if (n<l)
 {
 l=n;
 }
 if (n>h)
 {
 h=n;
 }
 }

 cout<<"O maior numero e "<<h<<", o menor e "<<l<<" e a soma e "<<s<<".\n";

 return 0;

}
– Jessika
Well, you have to check if the number typed
n
is greater thanh
(initialized as 0), if yes, you override the value ofh
(h=n); Qnd is the first loop (i==0), initializes the value ofl
equal to the number enteredn
; Check if the number typedn
is less thanl
(initialized as the first number entered), if yes, you override the value ofl
(l=n);– Jessika
@Jessika I got it, I did it the way you said it and it worked! Thank you!
– Akiyama