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

COMPUTER LAB REPORT

LABORATORY SESSION 7 –- Strings and pointers

Prakriti Thapa
07.19.2021
Roll no:23
Title: - Structure

Objective:

Theory:

Structure is a user defined data type available in C that allows combining


data items of different kinds. A structure creates a data type that can be
used to group items of possibly different types into a single type.The
structure is something similar to an array; the only difference is that an array
is used to store the same data types.

➢ ‘struct’ keyword is used to declare the structure in C.


➢ Variables inside the structure are called members of the structure.

Syntax:
struct structurename

{
datatype member1;
datatype member2;

……………………
datatype membern;
};

We have declared a person in struct type in the given example . When a struct
type is declared, no storage or memory is allocated. To allocate memory of a
given structure type and work with it, we need to create variables.

1
Access memory of a structure
There are two types of operators used for accessing members of a structure.
1. Member operator (.)
2. Structure pointer operator (->)

Keyword typedef
We use the typedef keyword to create an alias name for data types.
It is commonly used with structures to simplify the syntax of
declaring variables.
Code A

struct client{
int height;
float weight;
};

int main() {
struct client c1, c2;
}

Here , code A is equivalent to code B. So typedef makes it easier


while writing a struct type code.

2
Program 1
Title: Create a structure length to store length in feet & inches and read two lengths
and display their sum and difference.

Algorithm:
Step1: Start
Step 2:declare length

struct length
{
int feet;
float inch;
}l1,l2,sum,diff;

void main()
{
printf("For 1st person: \n");
printf("Enter feet: \0");
scanf("%d",&l1.feet);
printf("Enter inch: \0");
scanf("%f",&l1.inch);

printf("For 2nd person: \n");


printf("Enter feet: \0");
scanf("%d",&l2.feet);
printf("Enter inch: \0");
scanf("%f",&l2.inch);

Flowchart:

3
Source code:

#include <stdio.h>
#include <conio.h>
#include <math.h>

struct length
{
int feet;
float inch;
}l1,l2,sum,diff;

void main()
{
printf("For 1st person: \n");
printf("Enter feet: \0");
scanf("%d",&l1.feet);
printf("Enter inch: \0");
scanf("%f",&l1.inch);

4
printf("For 2nd person: \n");
printf("Enter feet: \0");
scanf("%d",&l2.feet);
printf("Enter inch: \0");
scanf("%f",&l2.inch);

sum.feet = l1.feet + l2.feet;


sum.inch = l1.inch + l2.inch;

diff.feet = l1.feet - l2.feet;


diff.inch = l1.inch - l2.inch;

if(diff.inch<0)
{
diff.feet = diff.feet -1;
diff.inch = diff.inch + 12;
}

while (sum.inch>=12)
{
sum.feet++;
sum.inch -= 12;
}

printf("\n Sum of distances=%d feet %.2f inch.",sum.feet,sum.inch);

printf("\n DIfference of distances= %d feet %.1f


inch.",abs(diff.feet),fabs(diff.inch));

getch();
}

Output:

5
6

You might also like