C Online Compiler
Example: Functions with Student Structures in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Functions with Student Structures #include <stdio.h> #include <string.h> // For strcpy // Step 1: Define the Student structure globally (or pass its definition) struct Student { int studentID; char name[50]; float gpa; }; // Function to print student details (pass by value) void printStudentDetails(struct Student s) { printf(" ID: %d\n", s.studentID); printf(" Name: %s\n", s.name); printf(" GPA: %.2f\n", s.gpa); } // Function to update GPA (pass by reference/pointer) void updateGPA(struct Student *s_ptr, float newGPA) { if (newGPA >= 0.0 && newGPA <= 4.0) { s_ptr->gpa = newGPA; // Use -> operator for pointer to struct printf(" GPA updated to %.2f for student ID %d\n", newGPA, s_ptr->studentID); } else { printf(" Invalid GPA value.\n"); } } int main() { // Step 2: Declare and initialize a student struct Student s1 = {101, "Alice Wonderland", 3.80}; printf("--- Original Student Details ---\n"); printStudentDetails(s1); // Call function by value printf("\n--- Updating GPA ---\n"); updateGPA(&s1, 3.95); // Call function by reference (pass address of s1) printf("\n--- Updated Student Details ---\n"); printStudentDetails(s1); // Print updated details // Example of another student struct Student s2 = {102, "Bob Builder", 3.10}; printf("\n--- Bob's Original Details ---\n"); printStudentDetails(s2); updateGPA(&s2, 2.50); printf("\n--- Bob's Updated Details ---\n"); printStudentDetails(s2); return 0; }
Output
Clear
ADVERTISEMENTS