Gabriel Fregoso Gabriel Fregoso - 1 year ago 88
C Question

My program wont run my while loop before it closes

So there is no syntax error in my program it's a logic error. My problem is when I try to run it only my

statement will execute but after that it closes my program not letting my
while loop
ask for anymore data until the user puts in
to stop my while loop.

#include <stdio.h>
// prototypes
void updateLevel(int PlayerPoints, int playerLevels[]);
void displayLevels(int ArrayName[]);

//main begins
main (void){
//arrays and varibles
int playerLevels[6] = {0};
int playerPoints = 0;

printf("Player points (-1 to quit) ");
scanf("%d" , &playerPoints);
//while loop to process input data
while(playerPoints =! -1){
scanf("Player points (-1 to quit) %d" , &playerPoints);
updateLevel(playerPoints, playerLevels);

//main ends

void updateLevel(int playerPoints, int playerLevels[]){
if(playerPoints >=50)
else if (playerPoints >=40)
else if (playerPoints >= 30)
else if (playerPoints >= 20)
else if (playerPoints >= 10)


void displayLevels(int playerLevels[]){
printf("T O T A L S\n");
printf("Level 1 %d\n", playerLevels[1]);
printf("Level 2 %d\n", playerLevels[2]);
printf("Level 3 %d\n", playerLevels[3]);
printf("Level 4 %d\n", playerLevels[4]);
printf("Level 5 %d\n", playerLevels[5]);
printf("Level 6 %d\n", playerLevels[6]);

Answer Source

For starters instead of this

while(playerPoints =! -1){

there must be

while(playerPoints != -1){

The original statement is equivalent to

while(playerPoints = 0){

so the loop is not executed.

Nevertheless the program has undefined behavior because you defined an array of 6 elements

int playerLevels[6] = {0};

but you are trying to access memory beyond the array

if(playerPoints >=50)

The valid range of indices for the array is [0, 5] Indices start from 0.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download