Skip to study material
← Question index

QUESTION 04

Explain initialisation and input/output of structure members.

5 marks

Answer in brief

Structure input and output operate on suitable members. A structure is not printed meaningfully by passing the whole object to an arbitrary format.

Algorithm

  1. Declare the structure type and an object.
  2. Read each member using its proper type and valid bounds.
  3. Reject failed input before relying on the member values.
  4. Display selected members with matching output formats.

Example

The sample reads a roll number and a double mark into one student record. %d matches int. scanf uses %lf with double *, while printf uses %f for the displayed double. The & operator supplies the destination address for each input conversion.

Initialisation

struct Student s = {0}; gives the first member zero and zero-initialises remaining members according to their types. This is different from an ordinary automatic object with no initialiser. Input validation is still necessary even when a safe starting value exists.

Text members

A character-array member needs enough capacity for its text and terminator. Whole-line input using fgets is suitable for names containing spaces. Mixing token-based numeric reads and line input needs deliberate handling of any remaining newline. Avoid unbounded %s or gets.

Correctness and cost

The example accepts only marks between 0 and 100 and a bounded positive roll number. These are sample constraints, not an institutional grading policy. Reading a fixed number of scalar members takes O(1) element operations; reading a variable-length text member also depends on its length.

Complete C example

main.c

Download main.c
/* CodeBhavya | Data Structures AR25 | Learning example */
#include <stdio.h>
struct Student { int roll; double marks; };

int main(void)
{
    struct Student s = {0};
    if (scanf("%d%lf", &s.roll, &s.marks) != 2 || s.roll < 1 || s.roll > 10000 || !(s.marks >= 0 && s.marks <= 100)) {
        puts("Invalid input"); return 1;
    }
    printf("Roll = %d, marks = %.1f\n", s.roll, s.marks);
    return 0;
}

Sample input and output

Input

101 87.5

Output

Roll = 101, marks = 87.5