Add

Top 3 Program to Using Structure in C Language


 

1.Store Information and Display it Using Structure.

#include <stdio.h>

struct student {

    char name[50];

    int roll;

    float marks;

} s;

int main() {

    printf("Enter information:\n");

    printf("Enter name: ");

    fgets(s.name, sizeof(s.name), stdin);

    printf("Enter roll number: ");

    scanf("%d", &s.roll);

    printf("Enter marks: ");

    scanf("%f", &s.marks);

    printf("Displaying Information:\n");

    printf("Name: ");

    printf("%s", s.name);

    printf("Roll number: %d\n", s.roll);

    printf("Marks: %.1f\n", s.marks);

    return 0;

}

In this program, a structure student is created. The structure has three members: name (string), roll (integer) and marks (float).

 

Then, a structure variable s is created to store information and display it on the screen.

2.C Program to Store Data in Structures Dynamically

In this example, you will learn to store the information entered by the user using dynamic memory allocation.

Demonstrate the Dynamic Memory Allocation for Structure

#include <stdio.h>

#include <stdlib.h>

struct course {

  int marks;

  char subject[30];

};

int main() {

  struct course *ptr;

  int noOfRecords;

  printf("Enter the number of records: ");

  scanf("%d", &noOfRecords);

  // Memory allocation for noOfRecords structures

  ptr = (struct course *)malloc(noOfRecords * sizeof(struct course));

  for (int i = 0; i < noOfRecords; ++i) {

    printf("Enter subject and marks:\n");

    scanf("%s %d", (ptr + i)->subject, &(ptr + i)->marks);

  }

  printf("Displaying Information:\n");

  for (int i = 0; i < noOfRecords; ++i) {

    printf("%s\t%d\n", (ptr + i)->subject, (ptr + i)->marks);

  }

  free(ptr);

  return 0;

}

This program asks the user to store the value of noOfRecords and allocates the memory for the noOfRecords structure variables dynamically using the malloc() function.

3.C Program to Find Largest Number Using Dynamic Memory Allocation

In this example, you will learn to find the largest number entered by the user in a dynamically allocated memory.

#include <stdio.h>

#include <stdlib.h>

int main() {

  int n;

  double *data;

  printf("Enter the total number of elements: ");

  scanf("%d", &n);

  // Allocating memory for n elements

  data = (double *)calloc(n, sizeof(double));

  if (data == NULL) {

  printf("Error!!! memory not allocated.");

  exit(0);

  }

  // Storing numbers entered by the user.

  for (int i = 0; i < n; ++i) {

  printf("Enter number%d: ", i + 1);

  scanf("%lf", data + i);

  }

  // Finding the largest number

  for (int i = 1; i < n; ++i) {

    if (*data < *(data + i)) {

      *data = *(data + i);

    }

  }

  printf("Largest number = %.2lf", *data);

  free(data);

  return 0;

}

 


Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.