Translate

Wednesday, June 24, 2015

Using linked list, write a C program, that will input some students' Id, Name, Department and CGPA respectively and print them.

millillion tech


#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>
#define SIZE 20


struct diu_cse
{
    int id;
    char name[SIZE];
    char department[SIZE];
    float cgpa;
    struct diu_cse *next;
};
struct diu_cse *head=NULL;
struct diu_cse *curr=NULL;

struct diu_cse* create_list(int id, char name[],char department[], float cgpa)
{
    struct diu_cse *ptr=(struct diu_cse*) malloc(sizeof(struct diu_cse));
    if(ptr==NULL)
    {
        printf("Node creation failed\n");
        return;
    }
    ptr->id = id;
    strcpy(ptr->name, name);
    strcpy(ptr->department, department);
    ptr->cgpa = cgpa;
    ptr->next=NULL;
    head=curr=ptr;
    return ptr;

}

struct diu_cse* add_to_list(int id, char name[], char department[], float cgpa)
{
    if(head==NULL)
    {
        return(create_list(id, name, department, cgpa));
    }
    struct diu_cse *ptr=( struct diu_cse*) malloc(sizeof(struct diu_cse));
    if(ptr==NULL)
    {
        printf("Node creation failed");
        return;
    }
    ptr->id = id;
    strcpy(ptr->name, name);
    strcpy(ptr->department, department);
    ptr->cgpa = cgpa;
    ptr->next=NULL;
    curr->next=ptr;
    curr=ptr;
    return ptr;
}
void print_list()
{
    struct diu_cse *ptr=head;
    while(ptr->next != NULL){
    printf("--------------------Printing List--------------------\n\n");
    printf(" %d  %s  %s  %.2f -> ", ptr->id, ptr->name, ptr->department, ptr->cgpa);
    ptr=ptr->next;
    }

    if(ptr->next == NULL)
        printf(" %d  %s  %s  %.2f ", ptr->id, ptr->name, ptr->department, ptr->cgpa);
        printf("\n\n");
}

int main()
{
    int id,i,n;
    char name[SIZE], department[SIZE];
    float cgpa;

    printf("How many node you want to create? ");
    scanf("%d", &n);
    printf("\nEnter the Id, Name, Department and CGPA of students\n");

    for(i=0;i<n;i++){
    scanf("%d", &id);
    fflush(stdin);
    gets(name);
    gets(department);
    scanf("%f", &cgpa);
    add_to_list(id, name, department, cgpa);
    }

    print_list();
    return 0;
}


millilliontech

Download source file

1 comments: