is this code valid ?

#include<iostream>
using namespace std;
int readHours()
{
int sumhours=0;
while(hours!=-99)
sumhours+=hours;
return sumhours;
}
int main()
{
int hours;
cout<<"Enter hours";
cin>>hours;
readhours();
cout<<sumhours;
cout<<"Enter hours";
cin>>hours;
readhours();
cout<<sumhours;
cout<<"Enter Hours";
cin>>hours;
readhours();
cout<<sumhours;
return 0;
}
Last edited on
at a glance it looks like you will be in an infinite loop if you call that function.

while(hours!=-99)
sumhours+-hours;

sumhours is set to 0;

user inputs 5 hours lets say. You then call readhours();
sumhours now is 5.
but hours not -99, so the while loops will run its body again, and its body is sumhours+=hours.
after it adds 5 again, because hours is still set to 5 from when the user input 5. sumhours is now 10, and hours is still not -99. so the loops will run its body again. you see the pattern, yo will never exit the while loop.

ALSO
i believe you want your function to look like this
int readHours(int hours)
{
int sumhours=0;
while(hours!=-99)
sumhours+=hours;
return sumhours;
}

i added a parameter to your function. i added 'int hours'. when you call the function in main you would pass your variable hours into that function.
so in main you would call it like this readhours(hours);
but of course you still have that infinite loop so once you fix that loop i assume you want the final product to look like this.





#include<iostream>
using namespace std;
int readHours(int hours); // declaring function so main will know about it
int sumhours=0; //making sumhours a globel variable so main and readhours have access.

int main()
{
int hours;
cout<<"Enter hours";
cin>>hours;
readhours(hours); //sending in the hours the user entered into the function
cout<<sumhours << endl;
cout<<"Enter hours";
cin>>hours;
readhours(hours);
cout<<sumhours << endl; //endl starts on the next line
cout<<"Enter Hours";
cin>>hours;
readhours(hours);
cout<<sumhours;
return 0;
}

int readhours(int hours)
{
sumhours+=hours;
return sumhours;
}
Topic archived. No new replies allowed.