본문 바로가기
C and C++/C and C++ Examples

[C Examples] Struct과 포인터를 활용해서 입력한 점수 저장하고 출력하기: struct, pointer

by Henry Cho 2023. 12. 1.
728x90

Struct과 포인터를 활용해서 입력한 점수 저장하고 출력하기

포스트 난이도: HOO_Intern


# Example Code

이번 예제코드에서는 Struct과 Pointer를 활용해서 사용자가 입력한 점수를 저장하고 다시 출력하면서 평균값을 산출해 낼 수 있다. 코드의 내용 자체는 매우 간단하기에 이번 예제코드에서 중점적으로 봐야 하는 부분은 Struct과 포인터가 어떻게 사용되는지이다. 코드 자체에서 하고자 하는 프로세스 자체가 간단하기 때문에 각 함수의 역할들을 이해하기 수월하다.


#include <stdio.h>
#include <stdlib.h>

struct node {
    float value;
    struct node* next;
};

struct node* head = NULL;

void displayList() {
    struct node* nodePtr = head;
    while (nodePtr != NULL) {
        printf("%.2f  ", nodePtr->value);
        nodePtr = nodePtr->next;
    }
}

void insert_end(float num) {
    struct node* newNode = (struct node*)malloc(sizeof(struct node));
    newNode->value = num;
    newNode->next = NULL;

    if (head == NULL) {
        head = newNode;
    } else {
        struct node* last = head;
        while (last->next != NULL) {
            last = last->next;
        }
        last->next = newNode;
    }
}

float findAverage() {
    struct node* nodePtr = head;
    float sum = 0;
    int count = 0;

    while (nodePtr != NULL) {
        sum += nodePtr->value;
        count++;
        nodePtr = nodePtr->next;
    }

    if (count == 0) {
        return 0.0;
    }

    return sum / count;
}

int main() {
    int numExams=7;
    float examScore;

    printf("\nEnter seven exam scores for your class: \n");
    for (int i = 0; i < numExams; i++) {
        printf("Enter exam score #%d: ", i + 1);
        scanf("%f", &examScore);
        insert_end(examScore);
    }

    printf("\nHere are all the exam scores you have entered: \n");
    printf(" List of Exam Grades: ");
    displayList();

    printf("\n Class Average: %.2f\n", findAverage());

    return 0;
}

Figure 1. Result of example code

 


# github link

https://github.com/WhoisHOO/HOOAI/blob/main/C%20Examples/simple_struct_pointer_grade_average


 

728x90

댓글