I am using Visual Studio 2010. while is keep repeating and I get an error when program stops.
It is just increasing the value of the array 700 times more than it should, and the "line" shows that it's just repeating the while loop more than it should (~700 times more)
Code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <iostream>
int main(){
int loop,loop2,loop3,usergirdi,random,linecounter,s,b,x;
int a[17];
printf("baslayarak \n");
scanf("%d",&usergirdi);
for (loop=1;loop<=16;loop++){
a[loop]=0; }
for (loop2=1;loop2<=15;loop2++){
if(loop2==usergirdi){
usergirdi=usergirdi;
a[usergirdi]+=1;
printf("%d ",a[usergirdi]); }
else
printf("%d ",a[loop2]);}
linecounter=0;
printf("\n");
while (a[1]<1||a[15]<1||a[2]<1||a[3]<1||a[4]<1||a[5]<1||a[6]<1||a[7]<1||a[8]<1||a[9]<1||a[10]<1||a[11]<1||a[12]<1||a[13]<1||a[14]<1){
linecounter++;
srand ( time(NULL) );
random=(rand()%15+1);
if (a[random-1]==0 && a[random+1]==0 && a[random]==0 ){}
else if (a[random-1]!=0 || a[random+1]!=0 )
{
a[random]+=1;
}
for (b=0;b<=14;b++){
printf("%d ",a[b]); }
printf("[line %d]\n",linecounter);
}}
Debug error:
Your code is subject to undefined behavior. You are accessing the array using an out of bound index in several places.
Before the start of the while
loop.
a[16] = 0;
Inside the while
loop.
a[16] = 0;
a[-1] = 0;
Again inside the while
loop
if (a[random-1]==0 && a[random+1]==0 && a[random]==0 ){}
// ^^ If random == 0
Again inside the while
loop
else if (a[random-1]!=0 || a[random+1]!=0 )
// ^^ If random == 0
You can remove those errors by:
Using
a[15] = 0;
Replacing the line
a[-1] = 0;
with
a[0] = 0;
Changing the line that generates random
to:
random=(rand()%14)+1;
The errors in logic can be removed by:
Moving the call to srand
outside the while loop.
Removing the a[0] < 1
check from the while
loop's conditional.