Wednesday, September 17, 2014

program that asks the user to input n number of records that he/she wants to enter by using malloc function, then display the user input values


Problem

Student structure contains the following contents:
Roll number (int), Name (string), Department (string), Course (string), Year of joining (string), cgpa (float)
Write a program that first prompts the user to input the n number of student records that he/she wants to input in that program. Then use malloc function to dynamically allocate memory that has n number of elements (type of each element is struct student). Then input records from user and display them on screen.
Hint:  p = (struct student*) malloc(sizeof (struct student) * n);

Solution - Code

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>
struct student
{
 char name[30];
 int roll_no;
 char department[30];
 char course[30];
 int year;
 float cgpa;
};
main()
{
 struct student *s;
 int i,how_many;

 printf ("Number of student data you want to enter");
 scanf ("%d",&how_many);

 s = (struct student*) malloc(sizeof(struct student) * how_many);

 for (i=0;i<how_many;i++)
 {
  fflush(stdin);
  printf ("enter name: ");
  gets(&s[i].name);

  printf ("Enter Roll no: ");
  scanf ("%d",&s[i].roll_no);

  fflush(stdin);
  printf ("enter department: ");
  gets (&s[i].department);

  fflush (stdin);
  printf ("enter course: ");
  gets (&s[i].course);

  printf ("enter year: ");
  scanf ("%d",&s[i].year);

  printf ("enter cgpa: ");
  scanf ("%f",&s[i].cgpa);
 }

 printf("\nAnd here is whhat you have entered\n\n");
 for (i=0;i<how_many;i++)
  printf("Name = %s\n\nRoll No. = %d\n\nDepartment = %s\n\nCopurse = %s\n\nYear = %d\n\n",s[i].name,s[i].roll_no,s[i].department,s[i].course,s[i].year);

 system("pause");
}

Sample Output


using malloc function

No comments :

Post a Comment

Note: Only a member of this blog may post a comment.

Copyright 2017. All Rights Reserved. Privacy Policy / Terms And Conditions / Sitemap / Contact