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

Second Semester 2022-23

Computer Programming (CS F111)


LAB – 13
Topics to be covered: Structures and Union

Lab notes
➢ Structures help to organize complicated data, particularly in large program, because
they permit a group of related variables as a unit.
➢ Declaration:
struct <struct name>{
data_type member1;
data_type member2;
...
};

Structure variable:
struct <struct name> var-name1, var-name2,...;
➢ Structure members: <structure var-name>.<member-name> or

struct <struct name> var-name1 = {member’s values};


➢ Union: It is a variable that hold object of different types and sizes with compiler
keeping track of size and alignment requirements.
➢ Declaration:
Union <union name>{
data_type member1;
data_type member2;
...
};

Union variable:
struct <struct name> var-name1, var-name2,...;

1
Exercises
1. Following C program is to create a structure named Date. The structure should have day,
month and year as inputs. Store the current date in the structure. Take inputs ‘x’ from the
user where x is the number of days. Add x to current date and display the final date.
Task: Modify the practice program-1 (above) to read any date and the ‘x’ (number of days)
to print the final date.

2
Sample Input:
The Current Date: 16/01/2023
Please enter the number of days (>0) to add: 7
Sample Ouput:
The Final Date: 23/01/2023
3
2. Program on arrays of structures. Run the below program and find out the output for the test
input:
Enter details of the student 1
Enter name: Vikas
Enter id no: 2022A3PS0076H
Enter marks: 80
Enter marks: 70

Enter details of the student 2


Enter name: Smita
Enter id no: 2022AAPS0123H
Enter marks: 60
Enter marks: 40

4
3. Passing structures through pointers. Find out the output of the following code:

4. Run the below program to see the output. Why 345.00 is output?
• Task1: If you alternate the positions of line numbers 8 and 10 in the above code,
i.e. writing 10 in place of 8, and 8 in place of 10, and print ‘a’ first and then ‘n’ what
would be the output. Find out a reason for the answer.
• Task2: Find out what is the output of the below change that you make to the above
code after line no:7 and write down a correct explanation for the answer.
strcpy(d1.a, “ABABABABABABABABABABAB”);
d1.n = 345;
printf(“%s”, d1.a);
printf(“%f”, d1.n);
return 0;
}

You might also like