Structures in C

Structures in C

Structures in C programming; Through this tutorial, you will learn structures in C programming with the help of examples.

Structures in C

  • Definition of Structures in C
  • Syntax of Structures In C
  • Define Structures in C
  • Example of Structures in C

Definition of Structures in C

Structure in c programming is a user-defined data type that stores the collection of different data types or heterogeneous types of data.

For example, if you want to store information about a customer: his/her name, citizenship number, and salary. You can create different variables name, city, and salary to store this information.

What if you need to store information of more than one customer? Now, you need to create different variables for each information per person: name1citNo1salary1name2citNo2salary2, etc.

A structure gives us a way to store the collection of that information in one unit under one name since all that information is related to the customer.

Note that:- A structure can store a collection of heterogeneous types of data.

Syntax of Structures In C

See the syntax of structures in c; as shown below:

struct structureName {
  dataType member1;
  dataType member2;
  ...
};

Define Structures in C

To define structures in c with data; as shown below:

struct Customer {
  char name[50];
  int citNo;
  float salary;
};

Example of Structures in C

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

// create struct with customer1 variable
struct Customer {
  char name[50];
  int citNo;
  float salary;
} customer1;

int main() {

  // assign value to name of customer1
  strcpy(customer1.name, "Shannon Vickery");

  // assign values to other customer1 variables
  customer1.citNo = 1984;
  customer1. salary = 2500;

  // print struct variables
  printf("Name: %s\n", customer1.name);
  printf("Citizenship No.: %d\n", customer1.citNo);
  printf("Salary: %.2f", customer1.salary);

  return 0;
}

Output of the above program:

Name: 
Shannon Vickery
Citizenship No.: 1984
Salary: 2500.00

In the above c program; create a structures named Customer. And created a variable of Customer named customer1. Then assigned values to the variables defined in Customer sturucturs for the customer1 object.

AuthorAdmin

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.

Leave a Reply

Your email address will not be published. Required fields are marked *