Gabriel Fregoso
Gabriel Fregoso

Reputation: 23

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 printf statement will execute but after that it closes my program not letting my while loop ask for anymore data until the user puts in -1 to stop my while loop.

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

//main begins
int
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);
    }

    displayLevels(playerLevels);
    return(0);
}
//main ends

//functions
void updateLevel(int playerPoints, int playerLevels[]){
    if(playerPoints >=50)
    playerLevels[6]++;
    else if (playerPoints >=40)
        playerLevels[5]++;
    else if (playerPoints >= 30)
        playerLevels[4]++;
    else if (playerPoints >= 20)
        playerLevels[3]++;
    else if (playerPoints >= 10)
        playerLevels[2]++;
    else
        playerLevels[1]++;

}

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]);
}

Upvotes: 1

Views: 48

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 310920

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)
playerLevels[6]++;

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

Upvotes: 1

Related Questions