Problems with Loops

I’m doing a program where you ask the user to enter how many calories they burned the past five days. It looks like I have everything correct, however I can’t figure out how to make where it ask the user “What is your calorie count for Day (number of day)?:” I’m trying to make that sentence repeat five times. I could really use some help here.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include<iostream>
using namespace std;

double calPerDay;
float avg;

int main() 
{
	cout << "What is your calorie count?: ";
	cin >> calPerDay;
	int i;
	for(i = 1; i <= 7; i = i + 1)
{
    cout << "After Day " << i << ", " << i * calPerDay
    << " calories are consumed.\n" << endl;
       
	  
}
avg = i / calPerDay;
 cout << "Your average is: " << avg; 
  return 0;
}

Whenever you want to do something multiple times, you must either duplicate code or write a loop.

To get a list of calories consumed for each of five days:

1
2
3
4
5
6
7
8
9
int main()
{
  int calories[ 5 ];

  for (int day = 0; day < 5; day++)
  {
    cout << "What is your calorie count for day " << (day + 1) << "? ";
    cin >> calories[ day ];
  }

Now you have a list (an array) of the person’s calorie intake for five days.
You can sum and average it, or whatever you like.

 
  cout << "You ate " << calories[3] << " calories on day 4.\n";

(Since the array starts with 0 for day 1, day 4 is index 3.)

Notes:
  • watch your indentation
  • keep variables inside functions

Hope this helps.
Last edited on
Duthomhas, I appreciate it! Thanks!

This is my updated version of the program:

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
#include<iostream>
using namespace std;

int main()
{
	float calories[5];
	float calPerDay;
	float avg;
	int day;
	double sum;
	
  for (int day = 0; day < 5; day++)
  {
    cout << "What is your calorie count on Day " << (day + 1) << "? ";
    cin >> calories[day];
  }
  
  for (int day = 0; day < 5; day++)
  {
  	sum = sum + calories [day];
  }
  cout << endl;
  cout << "\nYour sum is: " << sum;
  cout << "\nYour average is: " << sum/5 << endl;
  
  return 0;
}
Topic archived. No new replies allowed.