## Structure examples program in C language

Here we will see some structure example programs using C. You are most welcome if you have completed our all the previous topics of C tutorial especially C structure. So, let’s see some program of structure example here.

We recommend you to see our following guide if you don’t have any idea about them.

## Store data in a structures dynamically using C

In this program you will learn to store user input data by dynamic memory allocation. In C severally we need to store data in a structure dynamically. So, let’s have a look at the given C program.

``// code here``

### Output of structure example program: ## Calculate difference between two time periods using C structure

Here in this C program we will learn to calculate the difference between two time periods. Let’s try to write the code as bellow;

``````// C program to calculate difference between two time periods using C

#include <stdio.h>
struct time{
int sec;
int mins;
int hrs;
};

void diff_of_time_period(struct time start, struct time stop, struct time *diff){
while (stop.sec > start.sec){
--start.mins;
start.sec = start.mins + 60;
}

diff->sec = start.sec - stop.sec;

while (stop.mins > start.mins){
--start.hrs;
start.mins = start.mins + 60;
}

diff -> mins = start.mins - stop.mins;
diff -> hrs = start.hrs - stop.hrs;
}

int main(){
struct time time_start, time_stop, time_diff;

printf("Enter the starting time : \n");
printf("hour minute second : ");
scanf("%d %d %d", &time_start.hrs, &time_start.mins, &time_start.sec);

printf("Enter the stopping time : \n");
printf("hour minute second : ");
scanf("%d %d %d", &time_stop.hrs, &time_stop.mins, &time_stop.sec);

diff_of_time_period(time_start, time_stop, &time_diff);

printf("\nDifference of time is = %d:%d:%d\n", time_diff.hrs, time_diff.mins, time_diff.sec);

return 0;
}``````

Compile and run the program to get the output like this. ## C structure example to add two complex numbers

Here, we will write a C program to add two complex number. Let’s see the bellow structure example program;

``````// C program to add two complex number using structure

#include <stdio.h>
typedef struct complex_num{
float real;
float imag;
} comp;

comp add(comp n1, comp n2) {
comp temp;
temp.real = n1.real + n2.real;
temp.imag = n1.imag + n2.imag;
return (temp);
}

int main() {
comp first_num, second_num, sum;

printf("Enter real and imaginary parts of first number : \n");
scanf("%f %f", &first_num.real, &first_num.imag);

printf("Enter real and imaginary parts of second number : \n");
scanf("%f %f", &second_num.real, &second_num.imag);

sum = add(first_num, second_num);

printf("Sum = %.1f + %.1fi", sum.real, sum.imag);
return 0;
}``````

Output of this add two complex number program :

``````Enter real and imaginary parts of first number :
5.9 -3.88
Enter real and imaginary parts of second number :
2.8 3.9
Sum = 8.7 + 0.0i``````

Previous pageC union

Next pageC pointer