Basic

Switch Case

Goto

Operators

if Statement

Nested if

While Loop

For Loop

Patterns

Array

2D Array

String Function Example

Pointers

Recursion Function

Structure

Excersises

Others


Functions in Structures in C Program


Write a C program using structures with functions. This example shows how to define a structure, pass it to a function, and display the data.

  • A Student structure is defined with fields for id, name, and marks.
  • Student data is collected from user input and stored in a student1 variable.
  • displayStudent() is used to print the student's information by passing the structure by value.
  • updateMarks() modifies the student's marks using a pointer to the structure, demonstrating pass-by-reference.
Example : pgm.c
#include <stdio.h>
#include <string.h>

// Define a structure
struct Student {
    int id;
    char name[50];
    float marks;
};

// Function to display student details
void displayStudent(struct Student s) {
    printf("\nStudent Details:\n");
    printf("ID: %d\n", s.id);
    printf("Name: %s\n", s.name);
    printf("Marks: %.2f\n", s.marks);
}

// Function to update marks
void updateMarks(struct Student *s, float newMarks) {
    s->marks = newMarks;
}

int main() {
    struct Student student1;

    // Input details
    printf("Enter ID: ");
    scanf("%d", &student1.id);

    printf("Enter name: ");
    scanf(" %[^\n]", student1.name);

    printf("Enter marks: ");
    scanf("%f", &student1.marks);

    // Display before update
    displayStudent(student1);

    // Update marks
    updateMarks(&student1, 95.0);

    // Display after update
    printf("\nAfter updating marks:\n");
    displayStudent(student1);

    return 0;
}

Output :

Enter ID: 101
Enter name: Alex
Enter marks: 88.5

Student Details:
ID: 101
Name: Alex
Marks: 88.50

After updating marks:

Student Details:
ID: 101
Name: Alex
Marks: 95.00