简体   繁体   中英

Most of the program works, but my array isn't printing the way it should

My array isn't printing out all the data, just whatever was last inputted. The data should print something like this For the student number, if not enough numbers are inputted, 0's are automaticaly put in.

/*
Name: 
Date: 10/06/2016
Workshop 4
*/
#include <stdio.h>

int main(void)
{
    int counter;
    int marks [40];
    float num_grades = 0;
    int row = 1;
    float sum = 0;
    float average = 0;
    int pass = 0;
    int fail = 0;
    float pass_sum = 0;
    float fail_sum = 0;
    float pass_average = 0;
    float fail_average = 0;
    float biggest = 0;
    float smallest = 0;

    //int grade[40];
    int student_num[40];

    printf("       ---=== IPC mark Analyser V2.0 ===---\n");

    printf("Please enter the number of students(between 3 and 40): ");
    scanf("%d", &counter);


    while (counter >40 || counter <3)
    {
        printf("Invalid number, enter a number between 3 and 40 inclusive: ");
        scanf("%d", &counter);

    }

    printf("Row   Std No Mrk\n");
    printf("--- --------- ---\n");

    num_grades = counter;
    while (counter > 0)
    {
        printf("%d ", row);
        printf("_____________ ___\r%3d ", row);
        scanf("%d", &student_num[40]);
        scanf("%d", &marks[40]);
        row++;
        counter--;
        sum += marks[40];
    }

    for (int i = 0; i < num_grades; i++)
    {
        printf("%03d %09d %3d\n", row, student_num[40], marks[40]);
    }


    average = sum / num_grades;

    printf("-----------------\n");
    printf("-----------------\n");
    printf("Marks Entered, printing results:\n");
    printf("Row   Std No Mrk\n");
    printf("--- --------- ---\n");


    printf("The average of all marks in this group is %.1f.\n", average);
    printf("Program Ended.\n");


    return 0;
}

You're always reading/writing index 40 in the student_num and marks arrays, so everything goes to the same place.

Actually, the valid indexes of an array of size 40 are 0 to 39, so you're actually reading/writing off the end of the array, causing undefined behavior .

You need to use the proper index in each place. In the printing loop, use i . In the reading loop, use a variable that starts at 0 goes up to counter .

num_grades = counter;
for (int i = 0; i < num_grades; i++)
{
    printf("%d ", i + 1);
    printf("_____________ ___\r%3d ", i + 1);
    scanf("%d", &student_num[i]);
    scanf("%d", &marks[i]);
    sum += marks[i];
}

for (int i = 0; i < num_grades; i++)
{
    printf("%03d %09d %3d\n", row, student_num[i], marks[i]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM