Week 7 Answers | Introduction To Programming In C
Q1. Create a database of students using structures, wherein each entry of the database will have the following fields:
- a name, which is a string with at most 128 characters
- their marks in physics which is an int between 0 and 100
- their marks in chemistry which is an int number between 0 and 100
- their marks in mathematics which is an int number between 0 and 100
Code:- Private case passed
#include<stdio.h>
struct student{
char name[128];
int p,c,m;
}s[100],t;
int main()
{
int i,n,j;
scanf("%d", &n);
for(i=0;i<n;i++)
{
scanf("%s%d%d%d", s[i].name, &s[i].p, &s[i].c, &s[i].m);
}
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if((s[i].p>s[j].p) || ((s[i].p==s[j].p) && (s[i].c>s[j].c)))
{
t = s[i];
s[i] = s[j];
s[j] = t;
}
}
}
for(i=0; i<n; i++)
{
printf("%s-%d-%d-%d\n",s[i].name,s[i].p,s[i].c,s[i].m);
}
return 0;
}
Q2. You are given a sequence of integers terminated with a -1. The -1 isnot part of the input sequence.
Next, you are given a positive number N.
You have to create a linked list with the input sequence of integersas entries. You can use the following structure.
struct node{ int data; struct node *next; };
Code:- Private case passed
#include<stdio.h>
#include<stdlib.h>
struct node {
int data;
struct node *next;
}*start = NULL;
int main() {
int n, N, count = 0;
struct node *newnode, *temp;
scanf("%d", &n);
while (n != -1)
{
newnode = (struct node *)malloc(sizeof(struct node));
newnode -> data = n;
newnode -> next = NULL;
if (start == NULL)
start = newnode;
else
{
temp = start;
while (temp -> next != NULL)
{
temp = temp -> next;
}
temp -> next = newnode;
}
count++;
scanf("%d", &n);
}
scanf("%d", &N);
if (N > count)
{
printf("-1");
return 0;
}
while (count > N)
{
start = start -> next;
count--;
}
temp = start;
while (temp != NULL)
{
printf("%d ", temp -> data);
temp = temp -> next;
}
return 0;
}