QUESTION 03
How is a structure member read with scanf?
2 marksAnswer
Pass the address of the selected member with a matching format, such as scanf("%d", &s.roll). Check the conversion result before use.
QUESTION 03
Pass the address of the selected member with a matching format, such as scanf("%d", &s.roll). Check the conversion result before use.
QUESTION 04
Structure input and output operate on suitable members. A structure is not printed meaningfully by passing the whole object to an arbitrary format.
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.
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.
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.
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.
/* 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;
}101 87.5Roll = 101, marks = 87.5