Wednesday, 8 January 2014

C Programming Language Tutorial XIV – Structure

 Structure
-   A structure is a set of elements of different types.
-   A structure is a collection of variables under a single name.
-   These variables can be of different types.
-   Structure is a convenient way of grouping several pieces of related information together.
-   By using structure we can create user defined table consists of number of rows and columns in memory.
-   Records stored under structure are in tabular format.
-   Once structure is created and numbers of records are stored then we easily perform all types of database operations such as add new record, list all records, search record, update record and delete record.
Declaring a Structure
                                    Struct <structre-name>
{
   Declaration of structures data members;
};
Accessing structure elements
In order to access the elements of a structure, first create an instant variable of structure and then you can access elements through this variable.
struct <structre-name>
{
Declaration of structures data members;
}structure-variable;
or
struct <structre-name>
{
Declaration of structures data members;
};
struct structure-name structure-variable;
as mention above, whenever structure is declared then in memory one user define table is created that consists of rows and columns let us see it:
Example:
            struct Book
            {
                        int bcode;
                        char name[20];
                        int price;
            };
            struct Book b[5];
This structure locate memory in tabular format. It allocates 5 rows and 3 columns.
bcode               bname              price
101                   Java                 450
102                   Cpp                  210
103                   Flash                200
104                   C                      180
105                   VB                    250
That is whenever you put the records then rows are the actual records and columns are fields.
In following program the structure of book is created.
//prog to create structure of n books
#include<stdio.h>
#include<conio.h>
void main()
{
int n;
struct Book
{
int bno;
char name[10];
int price;
char author[10];
};  //declaration of structure
struct Book b[50];  //declaration of structure variable having maximum 50 record size
int i,totprice=0;
clrscr();
printf("How many books\n");
scanf("%d",&n);
for(i=0;i<n;i++)  //scan one by one record according to index starts from 0 till n-1
{
printf("Enter book no\n");
scanf("%d",&b[i].bno);   
printf("Enter book name\n");
scanf("%s",&b[i].name);
printf("Enter book price\n");
scanf("%d",&b[i].price);
printf("Enter book author name\n");
scanf("%s",&b[i].author);
}
printf("Records are\n");
printf("Bookno\t Name\t Price\t Author\n");
printf("-------------------------------------\n");
for(i=0;i<n;i++)  //print one by one record
{
printf("%d\t %s\t %d\t %s\n",b[i].bno,b[i].name,b[i].price,b[i].author);
totprice=totprice+b[i].price;
}
printf("Total price = %d\n",totprice);
getch();
}
Output:
How many books
3
Enter book no
1
Enter book name
Java
Enter book price
450
Enter book author name
Macs
Enter book no
2
Enter book name
VB6
Enter book price
210
Enter book author name
Wills
Enter book no
3
Enter book name
Cpp
Enter book price
200
Enter book author name
Swamy
Records are
Bookno   Name    Price   Author
-------------------------------------
1        Java    450     Macs
2        VB6     210     Wills
3        Cpp     200     Swamy
Total price = 860
In above program you have only scan and print records. Now in the following program let us add code for searching record. Here sequential searching is possible i.e. start searching from zero till n-1 records.
After printing total price add following code:
printf(“\nEnter book code for searching”);
scanf(“%d”,&tbcode);
for(i=0;i<n;i++)  //start searching from 0 to n-1
{
  if(b[i].bcode==tbcode)  //If this condition is true then print details and no need to search more
  {
    printf(“\nRecord found details are…”);
    printf("%d\t %s\t %d\t %s\n",b[i].bno,b[i].name,b[i].price,b[i].author);
    break; //exit from loop
  }
}
if(i==n)  //If record does not exist then at the end I and n become equal
printf(“\nRecord not found…”);
//program to create structure of Bank and perform searching and transaction
#define p printf   //defined shortkey for printf() and scanf()
#define s scanf
#include<stdio.h>
#include<conio.h>
void main()
{
struct Bank
{
int acno;
char name[10];
int bal;
char actype[10];
}b[50];
int i=0,j,tacno,amt,choice,flag;
char trans,ans='y';
clrscr();
while(1)  //infinite loop
{
p("****************SSBI BANK*****************\n");
//display the choices(menu) to user
p("1. Open new account\n");
p("2. List all accounts\n");
p("3. Search account details\n");
p("4. Transaction\n");
p("5. Exit\n");
p("Enter your choice(1-5)\n");
s("%d",&choice); //scan the value of menu currently selected by user
switch(choice)
{
case 1:
{
while(ans=='y')  //initially this loop is true because ans variable is declared with ‘y’ value
{
p("Enter account number\n");
s("%d",&b[i].acno);
p("Enter account holder name\n");
s("%s",&b[i].name);
p("Enter account opening balance\n");
s("%d",&b[i].bal);
p("Enter account type\n");
s("%s",&b[i].actype);
i++;  //i starts from zero till user enter ‘y’ value
p("Enter more records? \n");
flushall();
s("%c",&ans);
}
break;  //case break
}
case 2:
{
p("Records are\n");
p("Accountno\t Name\t Balance\t Accounttype\n");
p("-----------------------------------------------\n");
for(j=0;j<i;j++) //In above case records are stored from 0 till I so read records from j=0 to i
{
p("%4d\t\t %-12s\t %3d\t %-8s\n",b[j].acno,b[j].name,b[j].bal,b[j].actype);
}
break;
}
case 3:
{
p("Enter account no for search\n");
s("%d",&tacno);
for(j=0;j<i;j++)
{
if(tacno==b[j].acno)
{
p("Record found...\n");
p("%d\t %s\t %d\t %s\n",b[j].acno,b[j].name,b[j].bal,b[j].actype);
break;
}
}
if(j==i)
p("Record not found...\n");
break;
}
case 4:
{
p("Enter account no for transaction\n"); //For transaction you need to search record
s("%d",&tacno);
for(j=0;j<i;j++)
{
if(tacno==b[j].acno)
{
p("Record found...\n");
p("%d\t %s\t %d\t %s\n",b[j].acno,b[j].name,b[j].bal,b[j].actype);
p("Enter amount for transaction\n");
s("%d",&amt); //scan amount fro transaction
p("Enter type of transaction(D/W)\n");
flushall();
s("%c",&trans);  //scan type of transaction whether it is D(deposit) or w(withdraw)
if(trans=='D')
{
b[j].bal=b[j].bal+amt; //Add given amount to balance
p("Account is debited...\n");
}
else
if(trans=='W')
{
if(b[j].bal>amt)  //Check whether sufficient balance is available or not
{
b[j].bal=b[j].bal-amt;  //Deduct given amount from balance
p("Account is credited...\n");
}
else
p("Balance is not sufficient\n");
}
break;
}
}
if(j==i)
p("Record not found...\n");
break;
}
case 5:
{
exit(0);  //to terminate program
}
}
}
getch();
}
Output:
****************SSBI BANK*****************
1. Open new account
2. List all accounts
3. Search account details
4. Transaction
5. Exit
Enter your choice(1-5)
1
Enter account number
1
Enter account holder name
John
Enter account opening balance
10000
Enter account type
saving
Enter more records?
y
Enter account number
2
Enter account holder name
Rima
Enter account opening balance
8700
Enter account type
current
Enter more records?
n
****************SSBI BANK*****************
1. Open new account
2. List all accounts
3. Search account details
4. Transaction
5. Exit
Enter your choice(1-5)
2
Records are
Accountno        Name    Balance         Accounttype
-----------------------------------------------
   1             John            10000   saving
   2             Rima            8700    current
****************SSBI BANK*****************
1. Open new account
2. List all accounts
3. Search account details
4. Transaction
5. Exit
Enter your choice(1-5)
4
Enter account no for transaction
1
Record found...
1        John    10000   saving
Enter amount for transaction
200
Enter type of transaction(D/W)
D
Account is debited...
****************SSBI BANK*****************
1. Open new account
2. List all accounts
3. Search account details
4. Transaction
5. Exit
Enter your choice(1-5)
2
Records are
Accountno        Name    Balance         Accounttype
-----------------------------------------------
   1             John            10200   saving
   2             Rima            8700    current
****************SSBI BANK*****************
1. Open new account
2. List all accounts
3. Search account details
4. Transaction
5. Exit
Enter your choice(1-5)
5
Structure to Function
A structure can be passed to a function just like any other variable. In case of structure function is call by reference.
Nested Structure
Structure within a structure is called the nesting of structure.
//prog to structure of friend
#include<stdio.h>
#include<conio.h>
void main()
{
 struct friends
 {
  long phno;
  char fname[30];
  struct bdate    //Nested structure
  {
    int dd,mm,yy;
  }b[5];  //variable of inner structure
  }f[5];  // variable of outer structure
  int i;
  clrscr();
  for(i=0;i<5;i++)
  {
  printf("Enter contact no.\n");
  scanf("%ld",&f[i].phno);
  printf("Enter name\n");
  scanf("%s",&f[i].fname);
  printf("Enter birth date in form of dd mm yy\n");
  scanf("%d%d%d",&f[i].b[i].dd,&f[i].b[i].mm,&f[i].b[i].yy); //refer data of inner structure by using index of outer as well inner structure
  }
  printf("Record of friends\n");
  printf(" Contact No. \t Name\t     Birth Date\n");
  printf("---------------------------------------------------------\n”);
  for(i=0;i<5;i++)
  {
   printf("%d\t   %s\t     %d-%d-%d\n",f[i].phno,f[i].fname,f[i].b[i].dd,f[i].b[i].mm,f[i].b[i].yy);
  }
getch();
}
You can see output same as simple structure
Union
Like a structure, union is a set of different type of data.
In a union, every member is allocated the same piece of storage. This can save memory, if you have a group of data where only one of the types is used at a time. So, only one member of a union can be initialized at any one type. The size of a union is equal to the size of its largest data member.

No comments:

Post a Comment