Showing posts with label Structures. Show all posts
Showing posts with label Structures. Show all posts

Tuesday, 12 February 2013

C Programming: Structures

We know that array is a collection of data that represent same data type. We cannot make array that has data with different types using a single name. Fortunately, C supports a constructed data type called structures a mechanism for packing data of different types. A structure is a convenient tool for handling a group of logically related data items. For example, it can be used to represent a set of attributes, such as student_name, roll_number and marks. The concept of a structure is analogous to that of a ‘record’ in many other languages.
Defining a structure
Unlike arrays, structures must be defined first for their format they may be used later to declare structure variable. structure definition is the template of structure variable. The general format of a structure definition is
struct tag_name
{
   data_type    member1;
   data_type    member 2;
   - - - - -    - - - - 
};
Declaring structure variable
After defining a structure format you can declare variables of that type. A structure variable declaration is similar to the declaration of variable of any other types. It includes the following elements:


  • The keyword struct
  • The structure tag name
  • List of variable names separated by commas.
  • A terminating semicolon
The general syntax is 
struct tag_name variable1, variable2, variable3,...,variableN;


Example
  1: struct student{
  2:    char name[10];
  3:    int roll_no;
  4:    float marks;
  5: };
  6: 
  7: struct student student1;

In this example line numbers 1-5 is structure definition. A structure is defined with tag_name student having members name, roll_no and marks. This is only template for structure variable. Remember members themselves are not variables. They do no occupy any memory until they are associated with the structure variables such as student1 in above example. Till line 7 no variable is created and structure definition cannot do anything without variable. Line 7 declares a structure variable student1 which has fields name, roll_no and marks. If you declare another variable like student2 then it also includes those fields(members). 

Accessing structure members

We can access and assign values to the members of a structure in a number of ways. As mentioned earlier, the members themselves are not variables. They should be linked to the structure variables in order to make them meaningful members. The link between a member and a variable is established using the member operator ‘.’which is also known as ‘dot operator’ or ‘period operator’. For example, student1.marks is the variable representing the marks of student1 and can be treated like any other ordinary variables.

Electricity Billing System using Structures in C

This example illustrates the concept of structures discussed in previous post. Here structure variable bill is declared which has structure template Bill and members firstName, lastName, Address, previousUnit and presentUnit. The structure represents the information of a customer and the program calculates the cost by checking previous and present unit. After you understand the code you will have the knowledge of following things:
  1. Defining Structure
  2. Declaring Structure variable
  3. Accessing members of structure
  4. Passing structure in function
  5. Returning structure from function
The source code and output is given here…
Source Code
//generating electricity bill using structure in C
#include<stdio.h>
/** This block defines the structure Bill having
    fields for first name, last name, address,
    previous unit and present unit. The structure
    must be defined before main function */
struct Bill{
    char firstName[10];
    char lastName[10];
    char Address[20];
    float previousUnit;
    float presentUnit;
};
/** This is the function definition that
    calculates the cost. Here structure is passed
    as an argument */
float generateBill(struct Bill temp){
    float diff;
    diff = temp.presentUnit - temp.previousUnit;
    if(diff > 20){
        return diff*4.75;
    }else{
        return 20*4.75+(diff-20)*7.75;
    }
}
int main(){
    struct Bill bill; /*Declaration of structure variable*/
    printf("Fill up the following: \n");
    printf("First Name: ");
    gets(bill.firstName); //accessing member
    printf("Last Name: ");
    gets(bill.lastName);
    printf("Address: ");
    gets(bill.Address);
    printf("Previous Unit: ");
    scanf("%f",&bill.previousUnit);
    printf("Present Unit: ");
    scanf("%f",&bill.presentUnit);
    printf("\a\n\n***********Electricity Bill***************\n\n\a");
    printf("Name: %s %s",bill.firstName,bill.lastName);
    printf("\nAddress: %s",bill.Address);
    printf("\nPrevious Unit: %.3f       Current Unit: %.3f",bill.previousUnit,bill.presentUnit);
    printf("\nCost: %.3f\n\n", generateBill(bill));
    return 0;
}

Output

struct

Adding two complex numbers using Structure in C

Simple algebraic addition do no work in the case of Complex Number. Because they have two parts, Real and Imaginary. To add two complex numbers, real part of one number must be added with real part of other and imaginary part one must be added with imaginary part of other. The concept of complex number can be viewed as structure having two members real and imaginary. So to add two complex numbers we use structure addition. If complex1 and complex2 be two structure variables and complex3 be their sum then
complex3.real = complex1.real + complex2.real;
complex3.imag = complex1.imag + complex2.imag;

In this way, we can add two complex numbers. The source code and output of the program is given here…
Source Code:
#include<stdio.h>
struct comp{
    float real;
    float imag;
};
struct comp comp1,comp2;
struct comp sum_complex(struct comp complex1,struct comp complex2){
    struct comp temp;
    temp.real = complex1.real + complex2.real;
    temp.imag = complex1.imag + complex2.imag;
    return temp;
}
int main(){
    struct comp result;
    printf("Enter Complex Number 1: ");
    scanf("%f%f",&comp1.real, &comp1.imag);
    printf("Enter Complex Number 2: ");
    scanf("%f%f",&comp2.real,&comp2.imag);
    result = sum_complex(comp1,comp2);
    printf("The sum is %.2f + i%.2f\n\n", result.real,result.imag);
    return 0;
}

Output

complex

Difference between Arrays and Structures in C

Both the arrays and structures are classified as structured data types as they provide a mechanism that enable us to access and manipulate data in a relatively easy manner. But they differ in a number of ways listed in table below:
Arrays
Structures
1. An array is a collection of related data elements of same type. 1. Structure can have elements of different  types
2. An array is a derived data type 2. A structure is a programmer-defined data type
3. Any array behaves like a built-in data types. All we have to do is to declare an array variable and use it. 3. But in the case of structure, first we have to design and declare a data structure before the variable of that type are declared and used.