Nested Structure

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 5

NESTED STRUCTURE

#include <stdio.h>
#include <string.h>

struct student_college_detail
{
int college_id; //=71145
char college_name[50]; //=Anna University
};

struct student_detail
{
int id : 4;
char name[20]; //=RAJU
float percentage; //=90.5
// structure within structure
struct student_college_detail clg;
}stu;

int main()
{
Printf(“Enter student id “);
Scanf(“%d”,&stu.id);
Printf(“Enter College ID”);
Scanf(“%d”,&stu.clg.college_id);

printf(" Id is: %d \n", stu.id);


printf(" Name is: %s \n", stu.name);
printf(" Percentage is: %f \n\n", stu.percentage);

printf(" College Id is: %d \n",


stu.clg.college_id);
printf(" College Name is: %s \n",
stu.clg.college_name);
return 0;
}

PASSING STRUCTURE TO FUNCTION IN C:


It can be done in below 3 ways

1. Passing structure to a function by value


2. Passing structure to a function by address(reference)
3. No need to pass a structure – Declare structure variable as global

1
#include <stdio.h>
#include <string.h>

struct student
{
int id;
char name[20];
float percentage;
};

void func(struct student record); // void sum (int a )


int main()
{
struct student x;

x.id=1;
strcpy(x.name, "Raju");
x.percentage = 86.5;

func(x);
return 0;
}

void func(struct student record)


{
printf(" Id is: %d \n", record.id);
printf(" Name is: %s \n", record.name);
printf(" Percentage is: %f \n", record.percentage);
}

2
1 #include <stdio.h>
2 #include <string.h>
3
4 struct student
5{
6 int id;
7 char name[20];
8 float percentage;
9 };
10
11 void func(struct student *record);
12 int main()
13 {
14 struct student record;
15
16 record.id=1;
17 strcpy(record.name, "Raju");
18 record.percentage = 86.5;
19
20 func(&record);
21 return 0;
22 }
23
24 void func(struct student *record)
25 {
26 printf(" Id is: %d \n", record->id);
27 printf(" Name is: %s \n", record->name);
28 printf(" Percentage is: %f \n", record->percentage);
29 }
30

3
#include <stdio.h>
#include <string.h>

struct student
{
int id;
char name[20];
float percentage;
};
struct student record; // Global declaration of structure

void structure_demo();

int main()
{
record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;

structure_demo();
return 0;
}

void structure_demo()
{
printf(" Id is: %d \n", record.id);
printf(" Name is: %s \n", record.name);
printf(" Percentage is: %f \n", record.percentage);
}

Return struct from a function

#include <stdio.h>
struct student
{
char name[50];
int age;
};

// function prototype
struct student getInformation( ); // int sum();

int main()
{
struct student s;

s = getInformation();

printf("\nDisplaying information\n");
printf("Name: %s", s.name);
printf("\nRoll: %d", s.age);

return 0;
}
struct student getInformation()
{
struct student s1;

printf("Enter name: ");


scanf ("%s", s1.name);

printf("Enter age: ");


scanf("%d", &s1.age);

return s1;
}

You might also like