Looping a statement

Is there an easier way to write code so that it doesnt have a huge block of code that repeats over and over?
Last edited on
It seems like the functions should return the info collected on the number of employees and the number of days missed to the Main function rather than being void functions. Unless the assignment requires you to use void functions?

Since you'll know the number of employees from the first function, you can use a for loop to total the number of days missed for each employee, and then return that total to the main function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int GetNumberMissed(int numberofEmployees)
{
	int daysmissed=0;
	int totalmissed = 0;
	
	for (int i=1; i<=numberofEmployees; i++)
	{
		cout << "Enter number of days missed for employee " << i << ": ";
		cin >> daysmissed;
		totalmissed += daysmissed;
		cout << endl;
	}
	
	return totalmissed;
}
Last edited on
The assignment does require me to use them I believe. Although it does just say "use a function called by main". I had been trying to use a for loop before but I couldn't figure out how to make it work properly. It kept looping non-stop. Thank you so much though! So now I'm confused on getting the number of days missed to add together for a total so that I can find the average days missed for the employees?
If it's just a function called by main and not specifically a void function, I don't see why you couldn't use the function to return a value.

totalmissed += daysmissed;
This line in the for loop adds the value of the days missed for the current employee to the running total. So when you return totalmissed at the end of the function, it returns the total of all the days missed entered.
Okay I was confused but I understand now. So can I use the running total to find the average in another function?
You could have another function to calculate the average. You could pass it the number of employees and total number of days missed, and just have it return the average as a float.

So in Main you could do something like this
1
2
3
numEmployee=GetEmployeeAmount();
numMissed=GetNumberMissed(numEmployee);
cout << "The average number of days missed for " << numEmployee << " employees is " << CalculateAverage(numEmployee,numMissed) << endl;


In calculating the average, you can use a cast to get a float result rather than an integer.
static_cast<float>(numMissed)/numEmployee;
Last edited on
Topic archived. No new replies allowed.