Reputation: 11
I am printing scorecard using global variables. For some reason the loop is getting terminated after 9 iterations even with an infinite loop.
Here is my code:
int runs1[12]={7,128,143,213,2,102,5,1,0,0,0,9};
int balls1[12]={13,221,362,267,15,160,14,5,0,0,0,0};
int minutes1[12]={17,313,501,386,19,191,10,1,0,0,0,0};
int fours1[12]={1,11,14,17,0,8,0,0,0,0,0,0};
int sixes1[12]={0,1,0,2,0,1,0,0,0,0,0,0};
int runs2[12]={23,155,23,243,1,65,4,9,5,0,0,8};
int balls2[12]={35,267,39,287,5,102,16,19,4,0,0,0};
int minutes2[12]={47,350,47,447,6,129,38,28,20,0,0,0};
int fours2[12]={4,13,4,25,0,7,0,1,1,0,0,0};
int sixes2[12]={0,0,0,0,0,2,0,0,0,0,0,0};
char names[12][10] = {"KL Rahul","M Vijaya","CA Pujara","V Kohli","AM Rahane","RG Sharma","R Ashwin","WP Sharma","RP Jadeja","UT Yadav","I Sharma","Extra Runs"};
void displayScorecard(){
int i = 0;
int sr;
printf("\nScorecard 1:");
printf("\nPlayer name\tRuns\tBalls faced\tMinutes spend\t4's\t6's\tStrike rate");
for( i = 0 ; i < 11 ; i++ ){
printf("\n%d",i);
sr = runs1[i]*100/balls1[i];
if( i == 3 ){
printf("\n%s\t\t%d\t%d\t\t%d\t\t%d\t%d\t%d",names[i],runs1[i],balls1[i],minutes1[i],fours1[i],sixes1[i],sr);
continue;
}
printf("\n%s\t%d\t%d\t\t%d\t\t%d\t%d\t%d",names[i],runs1[i],balls1[i],minutes1[i],fours1[i],sixes1[i],sr);
}
printf("\nScorecard 2:");
printf("\nPlayer name\tRuns\tBalls faced\tMinutes spend\t4's\t6's\tStrike rate");
for( i = 0 ; i < 11 ; i++ ){
sr = (runs2[i]*100/balls2[i]);
if( i == 3 ){
printf("\n%s\t\t%d\t%d\t\t%d\t\t%d\t%d\t%d",names[i],runs2[i],balls2[i],minutes2[i],fours2[i],sixes2[i],sr);
continue;
}
printf("\n%s\t%d\t%d\t\t%d\t\t%d\t%d\t%d",names[i],runs2[i],balls2[i],minutes2[i],fours2[i],sixes2[i],sr);
}
}
Upvotes: 0
Views: 78
Reputation: 51815
On the 9th run through your for
loops, you are attempting an integer "divide-by-zero" operation (in both loops), as the balls1[i]
and balls2[i]
values when i
is 8
(or more) are zero. An integer divide-by-zero causes undefined behaviour, which could include crashing the program: C Integer Behavior: Dividing by Zero.
To fix this, add a conditional calculation for your sr
value; the following assigns zero to sr
if the balls1[i]
value is zero:
for (i = 0; i < 11; i++) {
printf("\n%d", i);
if (balls1[i] == 0) sr = 0;
else sr = runs1[i] * 100 / balls1[i];
//...
And a similar modification for the balls2[]
loop...
for (i = 0; i < 11; i++) {
if (balls2[i] == 0) sr = 0;
else sr = (runs2[i] * 100 / balls2[i]);
//...
Note: As mentioned in the comments, some of your names
strings have more than 10 characters (don't forget to count the terminating nul
character); you should thus increase the size of those strings:
char names[12][12] = { "KL Rahul", "M Vijaya", "CA Pujara", "V Kohli", "AM Rahane", "RG Sharma", "R Ashwin",
"WP Sharma", "RP Jadeja", "UT Yadav", "I Sharma", "Extra Runs" };
Upvotes: 3