HELLO. This program counts the average height of n people, how should I make it count how many people are higher than 1.6meters? How hould I use IF statement? Inside or outside the loop? What should I compare 1.6m with? Thanks
1 2 3 4 5 6 7 8 9 10 11 12 13 14
float n,sum=0,avg,hg;
cin>>n; //number of people
for(int i=1;i<=n;i++){
cout<<"enter the height of the"<<i<<"person"<<endl;
cin>>hg;// height of one person
sum=sum+hg;
}
avg=sum/n;
cout<<"average:"<<avg;
It is also a good idea to give you variables names with meaning. What does n mean? If it is the number of people change the variable name to numOfPeople or something. It makes it easier to read and is good practice for when you are making more complicated things
If all you care about is the number of people who are taller than 1.6m, then you can use an if statement inside the loop.
To use an if statement outside your current loop you'd have to store all heights that are input and then process them with a second loop later.
Andy
PS n (or numOfPeople) should be an int variable, as you can't have fractions of a person!
PPS if you write a complete program (with main() and #includes) then the code tags will create a program that runs on C++ shell ( http://cpp.sh/ ) by clicking on the little cogwheel.