facebook like button

28 May, 2011

program 49: scanning and accessing structure in C

The need: 
      This is a program to demonstrate the use of structure in C program. This shows how a struct keyword can be used to define a structure form a collection of several variables of different (or may be same) type and how individual members of any struct type variable can be accessed and modified.

The code: 
--------------------------------------------
#include<stdio.h>
#include<string.h>
struct student        //defining structure
{
  char name[20];
  int age,roll_no;
  char gender;
};

int main()
{
  struct student st;     //creation of new structure variable st which is like student in its structure
  char z;
  printf("Enter the student name=>\t");
  gets(st.name);
  printf("Enter the student roll number=>\t");
  scanf("%d",&st.roll_no);
  printf("Enter the student age=>\t");
  scanf("%d",&st.age);
  printf("Enter the student gender 'm' or 'f'=>\t");
  z=getchar();        //dummy char varible to swallow previous inputs
  st.gender=getchar();
  printf("\nYou entered\n");
  printf("roll_no\tname\tage\tgender\n");
  printf("%d\t%s\t%d\t%c\n",st.roll_no,st.name,st.age,st.gender);
  return 0;
}

--------------------------------------------

The approach: 
First of all copy, paste, compile and run the program. This is a simple program just to show how we can access and scan individual components of a structure unlike previous program where all the values were directly assigned to structure component variables. This program is different from previous program in only one way that is scanning the component variables. Once the memory is allocated all component variables can be accessed by adding the structure variable name as prefix separated with a dot(.). Ex. 
st.name has been used to access name variable in the structure st.
After that these can be used normal variables.

No comments:

Post a Comment

feel free to ask your doubts... if any
you can post your doubts on
www.facebook.com/programsimply