I managed to complete the program assignment but out of curiosity, I was wondering if I could transfer this double nested for loop into a nested while loop, I tried my best in doing it but I it is not displaying the similar result as before.
The first set of code is the assignment with the nested for loop, which is right. The second set of code, I am trying to do the same assignment but with a nested while loop, which is not producing the same results as the one with the for loop. Thank you very much.
Here is the assignment:
Write a program that uses nested loops to collect data and calculate the average rainfall
over a period of years. The program should first ask for the number of years. The outer
loop will iterate once for each year. The inner loop will iterate twelve times, once for
each month. Each iteration of the inner loop will ask the user for the inches of rainfall
for that month.
The one with the nested for loop which works.
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 28 29 30 31 32 33 34 35 36 37 38 39
|
#include <iostream>
using namespace std;
int main()
{
int years;
int inches;
int average_Rainfall;
int enter_Month;
int accum1 = 0;
int accum2 = 0;
int accum3 = 0;
cout << "We are going to calculate the average Rainfall over a period of years, please enter the year(s): ";
cin >> years;
while (years < 1)
{
cout << "Please enter the years again, can't be lower than 1! ";
cin >> years; /
}
for (int i = 1; i <= years; i++)
{
cout << "For years: " << i << endl;
for (int month = 1; month <= 12; month++)
{
cout << "Enter the rainfall for month: " << month << endl;
cin >> enter_Month;
accum2 += enter_Month;
}
}
cout << "The rainfall for these months is: " << accum2 << endl;
system ("pause");
}
|
The second set of code is doing this same assignment, but with a nested while loop. This one produces a different output on the compiler for some reason.
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 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
|
#include <iostream>
using namespace std;
int main()
{
int years;
int inches;
int average_Rainfall;
int enter_Month;
int accum1 = 0;
int accum2 = 0;
int accum3 = 0;
int i = 1;
int a = 12;
int month = 1;
cout << "We are going to calculate the average Rainfall over a period of years, please enter the year(s): ";
cin >> years;
while (years < 1)
{
cout << "Please enter the years again, can't be lower than 1! ";
cin >> years;
}
while (years >= i)
{
cout << "For years: " << i << endl;
i++;
while (a >= month)
{
cout << "Enter the rainfall for month: " << month << endl;
cin >> enter_Month;
month++;
accum2 += enter_Month;
}
}
cout << "Total Rainfall: " << accum2 << endl;
system ("pause");
}
|