Best Industrial Training in C,C++,PHP,Dot Net,Java in Jalandhar

Tuesday, 25 February 2014

Ftell,Fseek,Rewind in C

 ftell()

Tells you where a particular file is about to read from or write to.
Prototypes
#include <stdio.h>

long ftell(FILE *stream);

Description
This function is the opposite of fseek(). It tells you where in the file the next file operation will occur relative to the beginning of the file.
It's useful if you want to remember where you are in the file, fseek() somewhere else, and then come back later. You can take the return value from ftell() and feed it back into fseek() (with whenceparameter set to SEEK_SET) when you want to return to your previous position.

Return Value

Returns the current offset in the file, or -1 on error.

Example

long pos;

// store the current position in variable "pos":
pos = ftell(fp);

// seek ahead 10 bytes:
fseek(fp, 10, SEEK_CUR);

// do some mysterious writes to the file
do_mysterious_writes_to_file(fp);

// and return to the starting position, stored in "pos":
fseek(fp, pos, SEEK_SET);


 fseek(), rewind()

Position the file pointer in anticipition of the next read or write.

Prototypes

#include <stdio.h>

int fseek(FILE *stream, long offset, int whence);
void rewind(FILE *stream);

Description

When doing reads and writes to a file, the OS keeps track of where you are in the file using a counter generically known as the file pointer. You can reposition the file pointer to a different point in the file using the fseek() call. Think of it as a way to randomly access you file.
The first argument is the file in question, obviously. offset argument is the position that you want to seek to, and whence is what that offset is relative to.
Of course, you probably like to think of the offset as being from the beginning of the file. I mean, "Seek to position 3490, that should be 3490 bytes from the beginning of the file." Well, it can be, but it doesn't have to be. Imagine the power you're wielding here. Try to command your enthusiasm.
You can set the value of whence to one of three things:

SEEK_SET

offset is relative to the beginning of the file. This is probably what you had in mind anyway, and is the most commonly used value for whence.
SEEK_CUR

offset is relative to the current file pointer position. So, in effect, you can say, "Move to my current position plus 30 bytes," or, "move to my current position minus 20 bytes."

SEEK_END

offset is relative to the end of the file. Just like SEEK_SET except from the other end of the file. Be sure to use negative values for offset if you want to back up from the end of the file, instead of going past the end into oblivion.
Speaking of seeking off the end of the file, can you do it? Sure thing. In fact, you can seek way off the end and then write a character; the file will be expanded to a size big enough to hold a bunch of zeros way out to that character.
Now that the complicated function is out of the way, what's this rewind() that I briefly mentioned? It repositions the file pointer at the beginning of the file:

fseek(fp, 0, SEEK_SET); // same as rewind()
rewind(fp);             // same as fseek(fp, 0, SEEK_SET)

Return Value

For fseek(), on success zero is returned; -1 is returned on failure.

The call to rewind() never fails.
Example
fseek(fp, 100, SEEK_SET); // seek to the 100th byte of the file
fseek(fp, -30, SEEK_CUR); // seek backward 30 bytes from the current pos
fseek(fp, -10, SEEK_END); // seek to the 10th byte before the end of file

fseek(fp, 0, SEEK_SET);   // seek to the beginning of the file
rewind(fp);               // seek to the beginning of the file

Error Handling in Files C

Error Handling

C language does not provide direct support for error handling. However few method and variable defined in error.h header file can be used to point out error using return value of the function call. In C language, a function return -1 or NULL value in case of any error and a global variable errno is set with the error code. So the return value can be used to check error while programming.
C language uses the following functions to represent error
  • perror() return string pass to it along with the textual represention of current errno value.
  • strerror() is defined in string.h library. This method returns a pointer to the string representation of the current errno value.

Example

#include< stdio.h>       
#include< errno.h>       
#include< stdlib.h>       
#include< string.h>       
 
extern int errno;
 
main( )
{
 
char *ptr = malloc( 1000000000UL);  //requesting to allocate 1gb memory space  

if ( ptr == NULL )        //if memory not available, it will return null  
{  
puts("malloc failed");
puts(strerror(errno));
exit(EXIT_FAILURE); //exit status failure       
}
else  //
{
free( ptr);
exit(EXIT_SUCCESS); //exit status Success       
}
}
Here exit function is used to indicate exit status. Its always a good practice to exit a program with a exit status. EXIT_SUCCESS and EXIT_FAILURE are two macro used to show exit status. In case of program coming out after a successful operation EXIT_SUCCESS is used to show successfull exit. It is defined as 0. EXIT_Failure is used in case of any failure in the program. It is defined as -1.

Monday, 24 February 2014

C program to copy files

C programming code

#include <stdio.h>
#include <stdlib.h>
 
int main()
{
   char ch, source_file[20], target_file[20];
   FILE *source, *target;
 
   printf("Enter name of file to copy\n");
   gets(source_file);
 
   source = fopen(source_file, "r");
 
   if( source == NULL )
   {
      printf("Press any key to exit...\n");
      exit(EXIT_FAILURE);
   }
 
   printf("Enter name of target file\n");
   gets(target_file);
 
   target = fopen(target_file, "w");
 
   if( target == NULL )
   {
      fclose(source);
      printf("Press any key to exit...\n");
      exit(EXIT_FAILURE);
   }
 
   while( ( ch = fgetc(source) ) != EOF )
      fputc(ch, target);
 
   printf("File copied successfully.\n");
 
   fclose(source);
   fclose(target);
 
   return 0;
}

Output of program:
copy file program

C program to merge two files

This c program merges two files and stores their contents in another file. The files which are to be merged are opened in read mode and the file which contains content of both the files is opened in write mode. To merge two files first we open a file and read it character by character and store the read contents in another file then we read the contents of another file and store it in file, we read two files until EOF (end of file) is reached.

C programming code

#include <stdio.h>
#include <stdlib.h>
 
int main()
{
   FILE *fs1, *fs2, *ft;
 
   char ch, file1[20], file2[20], file3[20];
 
   printf("Enter name of first file\n");
   gets(file1);
 
   printf("Enter name of second file\n");
   gets(file2);
 
   printf("Enter name of file which will store contents of two files\n");
   gets(file3);
 
   fs1 = fopen(file1,"r");
   fs2 = fopen(file2,"r");
 
   if( fs1 == NULL || fs2 == NULL )
   {
      perror("Error ");
      printf("Press any key to exit...\n");
      getch();
      exit(EXIT_FAILURE);
   }
 
   ft = fopen(file3,"w");
 
   if( ft == NULL )
   {
      perror("Error ");
      printf("Press any key to exit...\n");
      exit(EXIT_FAILURE);
   }
 
   while( ( ch = fgetc(fs1) ) != EOF )
      fputc(ch,ft);
 
   while( ( ch = fgetc(fs2) ) != EOF )
      fputc(ch,ft);
 
   printf("Two files were merged into %s file successfully.\n",file3);
 
   fclose(fs1);
   fclose(fs2);
   fclose(ft);
 
   return 0;
}


Output of program:
copy file program

C program to shutdown or turn off computer

C program to shutdown or turn off computer

C Program to shutdown your computer: This program turn off i.e shutdown your computer system. Firstly it will asks you to shutdown your computer if you press 'y' the your computer will shutdown in 30 seconds, system function of "stdlib.h" is used to run an executable file shutdown.exe which is present in C:\WINDOWS\system32 in Windows XP. You can use various options while executing shutdown.exe for example -s option shutdown the computer after 30 seconds, if you wish to shutdown immediately then you can write "shutdown -s -t 0" as an argument to system function. If you wish to restart your computer then you can write "shutdown -r".
If you are using Turbo C Compiler then execute your file from folder. Press F9 to build your executable file from source program. When you run from within the compiler by pressing Ctrl+F9 it may not work.

C programming code for Windows XP

#include <stdio.h>
#include <stdlib.h>
 
main()
{
   char ch;
 
   printf("Do you want to shutdown your computer now (y/n)\n");
   scanf("%c",&ch);
 
   if (ch == 'y' || ch == 'Y')
      system("C:\\WINDOWS\\System32\\shutdown -s");
 
   return 0;
}

C programming code for Windows 7

#include <stdio.h>
#include <stdlib.h>
 
main()
{
   char ch;
 
   printf("Do you want to shutdown your computer now (y/n)\n");
   scanf("%c",&ch);
 
   if (ch == 'y' || ch == 'Y')
      system("C:\\WINDOWS\\System32\\shutdown /s");
 
   return 0;
}
To shutdown immediately use "C:\\WINDOWS\\System32\\ shutdown /s /t 0". To restart use /r instead of /s.

C programming code for Ubuntu Linux

#include <stdio.h>
 
int main() {
  system("shutdown -P now");
  return 0;
} 
You need to be logged in as root user for above program to execute otherwise you will get the message shutdown: Need to be rootnow specifies that you want to shutdown immediately. '-P' option specifies you want to power off your machine. You can specify minutes as:
shutdown -P "number of minutes"

Thursday, 20 February 2014

File Handling in C

What is a File?

Abstractly, a file is a collection of bytes stored on a secondary storage device, which is generally a disk of some kind. The collection of bytes may be interpreted, for example, as characters, words, lines, paragraphs and pages from a textual document; fields and records belonging to a database; or pixels from a graphical image. The meaning attached to a particular file is determined entirely by the data structures and operations used by a program to process the file. It is conceivable (and it sometimes happens) that a graphics file will be read and displayed by a program designed to process textual data. The result is that no meaningful output occurs (probably) and this is to be expected. A file is simply a machine decipherable storage media where programs and data are stored for machine usage.
Essentially there are two kinds of files that programmers deal with text files and binary files. These two classes of files will be discussed in the following sections.

ASCII Text files

A text file can be a stream of characters that a computer can process sequentially. It is not only processed sequentially but only in forward direction. For this reason a text file is usually opened for only one kind of operation (reading, writing, or appending) at any given time.
Similarly, since text files only process characters, they can only read or write data one character at a time. (In C Programming Language, Functions are provided that deal with lines of text, but these still essentially process data one character at a time.) A text stream in C is a special kind of file. Depending on the requirements of the operating system, newline characters may be converted to or from carriage-return/linefeed combinations depending on whether data is being written to, or read from, the file. Other character conversions may also occur to satisfy the storage requirements of the operating system. These translations occur transparently and they occur because the programmer has signalled the intention to process a text file.

Binary files

A binary file is no different to a text file. It is a collection of bytes. In C Programming Language a byte and a character are equivalent. Hence a binary file is also referred to as a character stream, but there are two essential differences.
  1. No special processing of the data occurs and each byte of data is transferred to or from the disk unprocessed.
  2. C Programming Language places no constructs on the file, and it may be read from, or written to, in any manner chosen by the programmer.
Binary files can be either processed sequentially or, depending on the needs of the application, they can be processed using random access techniques. In C Programming Language, processing a file using random access techniques involves moving the current file position to an appropriate place in the file before reading or writing data. This indicates a second characteristic of binary files.
They a generally processed using read and write operations simultaneously.
For example, a database file will be created and processed as a binary file. A record update operation will involve locating the appropriate record, reading the record into memory, modifying it in some way, and finally writing the record back to disk at its appropriate location in the file. These kinds of operations are common to many binary files, but are rarely found in applications that process text files.

Creating a file and output some data

In order to create files we have to learn about File I/O i.e. how to write data into a file and how to read data from a file. We will start this section with an example of writing data to a file. We begin as before with the include statement for stdio.h, then define some variables for use in the example including a rather strange looking new type.
/* Program to create a file and write some data the file */
#include <stdio.h>
#include <stdio.h>
main( )
{
     FILE *fp;
     char stuff[25];
     int index;
     fp = fopen("TENLINES.TXT","w"); /* open for writing */
     strcpy(stuff,"This is an example line.");
     for (index = 1; index <= 10; index++)
      fprintf(fp,"%s Line number %d\n", stuff, index);
     fclose(fp); /* close the file before ending program */
}
The type FILE is used for a file variable and is defined in the stdio.h file. It is used to define a file pointer for use in file operations. Before we can write to a file, we must open it. What this really means is that we must tell the system that we want to write to a file and what the file name is. We do this with the fopen() function illustrated in the first line of the program. The file pointer, fp in our case, points to the file and two arguments are required in the parentheses, the file name first, followed by the file type.
The file name is any valid DOS file name, and can be expressed in upper or lower case letters, or even mixed if you so desire. It is enclosed in double quotes. For this example we have chosen the name TENLINES.TXT. This file should not exist on your disk at this time. If you have a file with this name, you should change its name or move it because when we execute this program, its contents will be erased. If you don’t have a file by this name, that is good because we will create one and put some data into it. You are permitted to include a directory with the file name.The directory must, of course, be a valid directory otherwise an error will occur. Also, because of the way C handles literal strings, the directory separation character ‘\’ must be written twice. For example, if the file is to be stored in the \PROJECTS sub directory then the file name should be entered as “\\PROJECTS\\TENLINES.TXT”. The second parameter is the file attribute and can be any of three letters, r, w, or a, and must be lower case.

Reading (r)

When an r is used, the file is opened for reading, a w is used to indicate a file to be used for writing, and an a indicates that you desire to append additional data to the data already in an existing file. Most C compilers have other file attributes available; check your Reference Manual for details. Using the r indicates that the file is assumed to be a text file. Opening a file for reading requires that the file already exist. If it does not exist, the file pointer will be set to NULL and can be checked by the program.
Here is a small program that reads a file and display its contents on screen.
/* Program to display the contents of a file on screen */
#include <stdio.h>
void main()
{
   FILE *fopen(), *fp;
   int c;
   fp = fopen("prog.c","r");
   c = getc(fp) ;
   while (c!= EOF)
   {
     putchar(c);
  c = getc(fp);
   }
   fclose(fp);
}

Writing (w)

When a file is opened for writing, it will be created if it does not already exist and it will be reset if it does, resulting in the deletion of any data already there. Using the w indicates that the file is assumed to be a text file.
Here is the program to create a file and write some data into the file.
#include <stdio.h>
int main()
{
 FILE *fp;
 file = fopen("file.txt","w");
 /*Create a file and add text*/
 fprintf(fp,"%s","This is just an example :)"); /*writes data to the file*/
 fclose(fp); /*done!*/
 return 0;
}

Appending (a)

When a file is opened for appending, it will be created if it does not already exist and it will be initially empty. If it does exist, the data input point will be positioned at the end of the present data so that any new data will be added to any data that already exists in the file. Using the a indicates that the file is assumed to be a text file.
Here is a program that will add text to a file which already exists and there is some text in the file.
#include <stdio.h>
int main()
{
    FILE *fp
    file = fopen("file.txt","a");
    fprintf(fp,"%s","This is just an example :)"); /*append some text*/
    fclose(fp);
    return 0;
}

Outputting to the file

The job of actually outputting to the file is nearly identical to the outputting we have already done to the standard output device. The only real differences are the new function names and the addition of the file pointer as one of the function arguments. In the example program, fprintf replaces our familiar printf function name, and the file pointer defined earlier is the first argument within the parentheses. The remainder of the statement looks like, and in fact is identical to, the printf statement.

Closing a file

To close a file you simply use the function fclose with the file pointer in the parentheses. Actually, in this simple program, it is not necessary to close the file because the system will close all open files before returning to DOS, but it is good programming practice for you to close all files in spite of the fact that they will be closed automatically, because that would act as a reminder to you of what files are open at the end of each program.
You can open a file for writing, close it, and reopen it for reading, then close it, and open it again for appending, etc. Each time you open it, you could use the same file pointer, or you could use a different one. The file pointer is simply a tool that you use to point to a file and you decide what file it will point to. Compile and run this program. When you run it, you will not get any output to the monitor because it doesn̢۪t generate any. After running it, look at your directory for a file named TENLINES.TXT and type it; that is where your output will be. Compare the output with that specified in the program; they should agree! Do not erase the file named TENLINES.TXT yet; we will use it in
some of the other examples in this section.
Reading from a text file
Now for our first program that reads from a file. This program begins with the familiar include, some data definitions, and the file opening statement which should require no explanation except for the fact that an r is used here because we want to read it.
#include <stdio.h>
   main( )
   {
     FILE *fp;
     char c;
     funny = fopen("TENLINES.TXT", "r");
     if (fp == NULL)
  printf("File doesn't exist\n");
     else {
      do {
       c = getc(fp); /* get one character from the file
       */
         putchar(c); /* display it on the monitor
       */
       } while (c != EOF); /* repeat until EOF (end of file)
     */
     }
    fclose(fp);
   }
In this program we check to see that the file exists, and if it does, we execute the main body of the program. If it doesn’t, we print a message and quit. If the file does not exist, the system will set the pointer equal to NULL which we can test. The main body of the program is one do while loop in which a single character is read from the file and output to the monitor until an EOF (end of file) is detected from the input file. The file is then closed and the program is terminated. At this point, we have the potential for one of the most common and most perplexing problems of programming in C. The variable returned from the getc function is a character, so we can use a char variable for this purpose. There is a problem that could develop here if we happened to use an unsigned char however, because C usually returns a minus one for an EOF – which an unsigned char type variable is not
capable of containing. An unsigned char type variable can only have the values of zero to 255, so it will return a 255 for a minus one in C. This is a very frustrating problem to try to find. The program can never find the EOF and will therefore never terminate the loop. This is easy to prevent: always have a char or int type variable for use in returning an EOF. There is another problem with this program but we will worry about it when we get to the next program and solve it with the one following that.
After you compile and run this program and are satisfied with the results, it would be a good exercise to change the name of TENLINES.TXT and run the program again to see that the NULL test actually works as stated. Be sure to change the name back because we are still not finished with TENLINES.TXT

Tuesday, 11 February 2014

Unions in C

A union is a special data type available in C that enables you to store different data types in the same memory location. You can define a union with many members, but only one member can contain a value at any given time. Unions provide an efficient way of using the same memory location for multi-purpose.

 Defining a Union

To define a union, you must use the union statement in very similar was as you did while defining structure. The union statement defines a new data type, with more than one member for your program. The format of the union statement is as follows:
union [union tag]
{
   member definition;
   member definition;
   ...
   member definition;
} [one or more union variables];  
The union tag is optional and each member definition is a normal variable definition, such as int i; or float f; or any other valid variable definition. At the end of the union's definition, before the final semicolon, you can specify one or more union variables but it is optional. Here is the way you would define a union type named Data which has the three members i, f, and str:
union Data
{
   int i;
   float f;
   char  str[20];
} data;  
Now, a variable of Data type can store an integer, a floating-point number, or a string of characters. This means that a single variable ie. same memory location can be used to store multiple types of data. You can use any built-in or user defined data types inside a union based on your requirement.
The memory occupied by a union will be large enough to hold the largest member of the union. For example, in above example Data type will occupy 20 bytes of memory space because this is the maximum space which can be occupied by character string. Following is the example which will display total memory size occupied by the above union:
#include <stdio.h>
#include <string.h>
 
union Data
{
   int i;
   float f;
   char  str[20];
};
 
int main( )
{
   union Data data;        

   printf( "Memory size occupied by data : %d\n", sizeof(data));

   return 0;
}
When the above code is compiled and executed, it produces the following result:
Memory size occupied by data : 20

Accessing Union Members

To access any member of a union, we use the member access operator (.). The member access operator is coded as a period between the union variable name and the union member that we wish to access. You would use union keyword to define variables of union type. Following is the example to explain usage of union:
#include <stdio.h>
#include <string.h>
 
union Data
{
   int i;
   float f;
   char  str[20];
};
 
int main( )
{
   union Data data;        

   data.i = 10;
   data.f = 220.5;
   strcpy( data.str, "C Programming");

   printf( "data.i : %d\n", data.i);
   printf( "data.f : %f\n", data.f);
   printf( "data.str : %s\n", data.str);

   return 0;
}
When the above code is compiled and executed, it produces the following result:
data.i : 1917853763
data.f : 4122360580327794860452759994368.000000
data.str : C Programming
Here, we can see that values of i and f members of union got corrupted because final value assigned to the variable has occupied the memory location and this is the reason that the value if str member is getting printed very well. Now let's look into the same example once again where we will use one variable at a time which is the main purpose of having union:
#include <stdio.h>
#include <string.h>
 
union Data
{
   int i;
   float f;
   char  str[20];
};
 
int main( )
{
   union Data data;        

   data.i = 10;
   printf( "data.i : %d\n", data.i);
   
   data.f = 220.5;
   printf( "data.f : %f\n", data.f);
   
   strcpy( data.str, "C Programming");
   printf( "data.str : %s\n", data.str);

   return 0;
}
When the above code is compiled and executed, it produces the following result:
data.i : 10
data.f : 220.500000
data.str : C Programming


Diffrence between structs and unions:
 


 

 

 

 

 

 

Structure

Union

1.The keyword  struct is used to define a structure
1. The keyword union is used to define a union.
2. When a variable is associated with a structure, the compiler allocates the memory for each member. The size of structure is greater than or equal to the sum of  sizes of its members. The smaller members may end with unused slack bytes.
2. When a variable is associated with a union, the  compiler allocates the  memory by considering the size of the largest memory. So, size of union is equal to the size of largest member.
3. Each member within a structure is assigned unique storage area of location.
3. Memory allocated is shared by individual members of union.
4. The address of each member will be in ascending order This indicates that memory for each member will start at different offset values.
4. The address is same for all the members of a union. This indicates that every member begins at the same offset value.
5 Altering the value of a member will not affect other members of the structure.
5. Altering the value of any of the member will alter other member values.
6. Individual member can be accessed at a time
6. Only one member can be accessed at a time.
7. Several members of a structure can initialize at once.
7. Only the first member of a union can be initialized.




Difference Between Stucture and Union :


Structure Union
i. Access Members     
We can access all the members of structure at anytime. Only one member of union can be accessed at anytime.
ii. Memory Allocation     
Memory is allocated for all variables. Allocates memory for variable which variable require more memory.
iii. Initialization     
All members of structure can be initialized Only the first member of a union can be initialized.
iv. Keyword     
'struct' keyword is used to declare structure. 'union' keyword is used to declare union.
v. Syntax     
struct struct_name
{
    structure element 1;
    structure element 2;
 ----------
 ----------
    structure element n;
}struct_var_nm;
union union_name
{
    union element 1;
    union element 2;
 ----------
 ----------
    union element n;
}union_var_nm;
vi. Example     
struct item_mst
{
    int rno;
    char nm[50];
}it;
union item_mst
{
    int rno;
    char nm[50];
}it;

Fig.: Difference between Structure and Union

Thursday, 6 February 2014

C – Passing struct to function

  • A structure can be passed to any function from main function or from any sub function.
  • Structure definition will be available within the function only.
  • It won’t be available to other functions unless it is passed to those functions by value or by address(reference).
  • Else, we have to declare structure variable as global variable. That means, structure variable should be declared outside the main function. So, this structure will be visible to all the functions in a C program.

Passing structure to function in C:

It can be done in below 3 ways.
    1. Passing structure to a function by value
    2. Passing structure to a function by address(reference)
    3. No need to pass a structure – Declare structure variable as global

Example program – passing structure to function in C by value:

           In this program, the whole structure is passed to another function by value. It means the whole structure is passed to another function with all members and their values. So, this structure can be accessed from called function. This concept is very useful while writing very big programs in C.

#include <stdio.h>
#include <string.h>

struct student
{
            int id;
            char name[20];
            float percentage;
};

void func(struct student record);

int main()
{
            struct student record;

            record.id=1;
            strcpy(record.name, "Raju");
            record.percentage = 86.5;

            func(record);
            return 0;
}

void func(struct student record)
{
            printf(" Id is: %d \n", record.id);
            printf(" Name is: %s \n", record.name);
            printf(" Percentage is: %f \n", record.percentage);
}

Output:

Id is: 1
Name is: Raju
Percentage is: 86.500000

Example program – Passing structure to function in C by address:

           In this program, the whole structure is passed to another function by address. It means only the address of the structure is passed to another function. The whole structure is not passed to another function with all members and their values. So, this structure can be accessed from called function by its address.
#include <stdio.h>
#include <string.h>

struct student
{
           int id;
           char name[20];
           float percentage;
};

void func(struct student *record);

int main()
{
          struct student record;

          record.id=1;
          strcpy(record.name, "Raju");
          record.percentage = 86.5;

          func(&record);
          return 0;
}

void func(struct student *record)
{
          printf(" Id is: %d \n", record->id);
          printf(" Name is: %s \n", record->name);
          printf(" Percentage is: %f \n", record->percentage);
}

Output:

Id is: 1
Name is: Raju
Percentage is: 86.500000

Example program to declare a structure variable as global in C:

           Structure variables also can be declared as global variables as we declare other variables in C. So, When a structure variable is declared as global, then it is visible to all the functions in a program. In this scenario, we don’t need to pass the structure to any function separately.

#include <stdio.h>
#include <string.h>

struct student
{
            int id;
            char name[20];
            float percentage;
};
struct student record; // Global declaration of structure

void structure_demo();

int main()
{
            record.id=1;
            strcpy(record.name, "Raju");
            record.percentage = 86.5;

            structure_demo();
            return 0;
}

void structure_demo()
{
            printf(" Id is: %d \n", record.id);
            printf(" Name is: %s \n", record.name);
            printf(" Percentage is: %f \n", record.percentage);
}

Output:

Id is: 1
Name is: Raju
Percentage is: 86.500000


C Program to Calculate Difference Between Two Time Period

#include <stdio.h>
struct TIME{
  int seconds;
  int minutes;
  int hours;
};
void Difference(struct TIME t1, struct TIME t2, struct TIME *diff);
int main(){
    struct TIME t1,t2,diff;
    printf("Enter start time: \n");
    printf("Enter hours, minutes and seconds respectively: ");
    scanf("%d%d%d",&t1.hours,&t1.minutes,&t1.seconds);
    printf("Enter stop time: \n");
    printf("Enter hours, minutes and seconds respectively: ");
    scanf("%d%d%d",&t2.hours,&t2.minutes,&t2.seconds);
    Difference(t1,t2,&diff);
    printf("\nTIME DIFFERENCE: %d:%d:%d - ",t1.hours,t1.minutes,t1.seconds);
    printf("%d:%d:%d ",t2.hours,t2.minutes,t2.seconds);
    printf("= %d:%d:%d\n",diff.hours,diff.minutes,diff.seconds);
    return 0;
}
void Difference(struct TIME t1, struct TIME t2, struct TIME *differ){
    if(t2.seconds>t1.seconds){
        --t1.minutes;
        t1.seconds+=60;
    }
    differ->seconds=t1.seconds-t2.seconds;
    if(t2.minutes>t1.minutes){
        --t1.hours;
        t1.minutes+=60;
    }
    differ->minutes=t1.minutes-t2.minutes;
    differ->hours=t1.hours-t2.hours;
}
Output
C program to calculate difference between two time period using structure