programaholic
programaholic

Reputation: 1

Beginner to C. Starting a gradebook application

#include <stdio.h>

int main(void) {
    int numStudents;
    int i = 0 ;

    printf("How many students are in your class? \n");
    scanf("%d", &numStudents);

    int grade[numStudents];

    while ( i > numStudents ){
        scanf("%d", &grade[i]);
        printf("\n");
        i++;
    }
}

what i want it to do is just get the number of students and allow that many scanners to get grades. Thanks.

Upvotes: 0

Views: 1116

Answers (3)

phoxis
phoxis

Reputation: 61950

while ( i > numStudents ){
    scanf("%d", &grade[i]);
    printf("\n");
    i++;
}

i is 0 at first ansnumStudentsis greater than or equal to i therefore i > numStudents will be false at the first check, and the body will not be executed. The condition should be :

while ( i < numStudents ){
    scanf("%d", &grade[i]);
    printf("\n");
    i++;
}

Also you should allocate memory either at the beginning of the block or use malloc to allocate a block of memory of required size

Upvotes: 1

unpythonic
unpythonic

Reputation: 4070

Two main issues with your code. First, you either have to know the size of the array grade at compile time, or you have to allocate it once you know how much you want.

For example:

#define MAX_STUDENTS 100
    int grade[MAX_STUDENTS];

    scanf("%d", &numStudents);
    if ( numStudents > MAX_STUDENTS ) {
        printf("Sorry, cannot handle %d students, I can only handle %d\n",
               numStudents, MAX_STUDENTS);
        exit(1);
    }

Or:

    int *grade;
    grade = malloc(sizeof(int) * numStudents);
    if ( !grade ) {
        printf("Failed to allocate memory for grades\n");
        exit(1);
    }

The other problem is your while loop. You want to iterate while i < numStudents.

Upvotes: 1

sarnold
sarnold

Reputation: 104080

while ( i > numStudents ){
    scanf("%d", &grade[i]);
    printf("\n");
    i++;
}

Your while condition is backwards; the loop body will never execute.

Upvotes: 4

Related Questions