for loop

Im a total beginner. I have to count how many flowers will be after 'n' days if every day 3 times more flowers appear than yesterday.. but this code isnt good



1
2
3
4
5
6
7
8
9
10
11
12
13

  int n,f,s;
f=1;
s=1;
cin>>n;
for(int i=2;i<=n;i++)
    f=f*3;
s=s+f;
cout<<s;
return 0;

}
Start by having sensible variable names. You're not being charged by the letter. I should be able to look at your code and have an idea of what variables are for. n, f and s are not informative names.

Use braces around your for loop block, so I know what you actually mean to be inside the for loop.

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
int numberOfDays;
int totalNumberOfFlowers;
int numberOfFlowersThatAppearedYesterday;

cout << "How many days?" << endl;
cin >> numberOfDays;

cout << "How many flowers appear on day 1?" << endl;
cin >> numberOfFlowersThatAppearedYesterday;

totalNumberOfFlowers = numberOfFlowersThatAppearedYesterday;

// we now have the number of flowers at the end of day 1.
// Need to calculate for the rest of the days

for (int currentDay = 1; currentDay < numberOfDays; currentDay++)
{
  int numberOfFlowersThatAppearedToday = 3 * numberOfFlowersThatAppearedYesterday;
  totalNumberOfFlowers = totalNumberOfFlowers + numberOfFlowersThatAppearedToday;

  // set up numberOfFlowersThatAppearedYesterday for tomorrow
  numberOfFlowersThatAppearedYesterday = numberOfFlowersThatAppearedToday;
}

cout << "Total number of flowers : " << totalNumberOfFlowers;


This code you can read and understand the logic of. You can see what it's trying to do. if there are bugs, you'll be able to find them just by looking at what's going on.



Last edited on
Topic archived. No new replies allowed.