开发者

Beginner to C. Starting a gradebook application

开发者 https://www.devze.com 2023-03-16 17:19 出处:网络
#include <stdio.h> int main(void) { int numStudents; int i = 0 ; printf(\"How many students are in your class? \\n\");
#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.


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

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


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消