In: Computer Science
When I run this C++ program that asks the user to enter the population of 4 cities and produce the bar graph
- it runs but ends with a Debug Error - run time check failure 2 stack around variable population was corrupted - any help would be appreciated
#include <iostream>
using namespace std;
int main()
{
int population[4],k;
int i=1,n=5;
do
{
cout<<"Enter the population of city "<<i<<":"<<endl;
cin>>population[i];
if(population[i]<0)
cout<<"population cannot be negative,Reenter\n";
else
i++;
} while (i<n);
cout<<"\n\n\t\tPOPULATION\n\t (each * = 1000 people)\n";
for(int i=1;i<n;i++)
{
cout<<"\nCity "<<i<<":";
k=population[i]/1000;
for(int j=0;j<k;j++)
cout<<"*";
}
return 0;
}
Program code to copy:-
#include <iostream>
using namespace std;
int main()
{
long population[4];
int i=0,n=4, k;
do
{
//Prompt & read population of
each city from user
cout<<"Enter the population of city
"<<(i+1)<<":"<<endl;
cin>>population[i];
//Checking for validity of input
if(population[i]<0)
cout<<"population
cannot be negative,Reenter\n";
else
i++;
}while(i<n);
cout<<"\n\n\t\tPOPULATION\n\t (each * = 1000
people)\n";
//Displaying bar graph
for(int i=0;i<n;i++)
{
cout<<"\nCity
"<<(i+1)<<":";
k=population[i]/1000;
for(int j=0;j<k;j++)
cout<<"*";
}
return 0;
}
Screenshot of output:-
Changes made in the program:-
The changes made in the program is bold.
- The array location starts with index value 0, so variable 'i' at the time of declaration should be initialized with value 0 instead of 1 and value of n should be initialized with 4.
For storing population of four cities the array location will be 0 to 3.
int i=0, n=4
- The population array is declared to be of type long to hold the bigger value.