I made C codebut there has a problem Even though I check fo
I made C ++ code,but there has a problem!
Even though I check for valid input, I don\'t do anything about it - so if a user entered 200,it would still work!!
please help me to solve this problem! :)
//Chapter5-#3: OceanLevel
#include <iostream>
 #include <iomanip>
using name space std;
 int main()
 {
   int nyears, year = 2016;
    double risinglevel = 0;
    cout << \"Enter n of years to predict :\";
    cin >> nyears;
   if (nyears > 0 && nyears<150)
    {
        cout << \"Year\\t\\tRisingLevel\ \";
        cout << \"---------------------------\ \";
   }
    else
        cout << \"Error:Invalid Input Value of years.\ \";
   for (int i = 1; i <= nyears; i++)
        {
                risinglevel += 1.5;
                cout << ++year << \"\\t\\t\" << fixed << setprecision(1) << risinglevel << endl;
        }
           
    system(\"pause\");
    return 0;
 }
Solution
Its because the loop that you have applied is incorrect. Hence it is working for value 200 as well.
YOur code is as follows:
if (nyears > 0 && nyears<150)
    {
        cout << \"Year\\t\\tRisingLevel\ \";
        cout << \"---------------------------\ \";
   }
    else
        cout << \"Error:Invalid Input Value of years.\ \";
//Here it will go to else and print the value but then it will go to the for loop as well and execute it.
   for (int i = 1; i <= nyears; i++)
        {
                risinglevel += 1.5;
                cout << ++year << \"\\t\\t\" << fixed << setprecision(1) << risinglevel << endl;
        }
           
    system(\"pause\");
    return 0;
 }
The correct solution is to the write the for loop inside if as follows:
#include <iostream>
 #include <iomanip>
 using name space std;
 int main()
 {
 int nyears, year = 2016;
 double risinglevel = 0;
cout << \"Enter n of years to predict :\";
 cin >> nyears;
 if (nyears > 0 && nyears<150)
 {
 cout << \"Year\\t\\tRisingLevel\ \";
 cout << \"---------------------------\ \";
        for (int i = 1; i <= nyears; i++)
 {
 risinglevel += 1.5;
 cout << ++year << \"\\t\\t\" << fixed << setprecision(1) << risinglevel << endl;
 }
 }
 else
 cout << \"Error:Invalid Input Value of years.\ \";
   
   
 system(\"pause\");
 return 0;
 }


