Display name of five students using structure in c.
if we do not use any loop in our file. then a programme will take more time and coding will be too long.
an example is following:-
#include <stdio.h>
#include <stdlib.h>
struct student
{
char name1[50];
char name2[50];
char name3[50];
char name4[50];
char name5[50];
}s;
int main()
{
printf("enter name of 1s students\n");
scanf("%s",s.name1);
printf("enter name of 2 students\n");
scanf("%s",s.name2);
printf("enter name of 3 students\n");
scanf("%s",s.name3);
printf("enter name of 4 students\n");
scanf("%s",s.name4);
printf("enter name of 5 students\n");
scanf("%s",s.name5);
// displaying name
printf("displaying name of five students \n");
printf("name of 1 student : \n");
puts(s.name1);
printf("name of 2 student : \n");
puts(s.name2);
printf("name of 3 student : \n");
puts(s.name3);
printf("name of 4 student : \n");
puts(s.name4);
printf("name of 5 student : \n");
puts(s.name5);
return 0;
}
But while we use a loop in a programme, then it makes it so simple and reduces time.
An example is following:-
#include<stdio.h>
struct student
{
char name[50];
}s[5];
int main()
{
int i;
//storing information in structure
for(i=1; i<=5; i++)
{
printf("enter name of students : %d\n",i);
scanf("%s",s[i].name);
}
//displaying information now
for(i=1; i<=5; i++)
{
printf("name of student :%d \n",i);
puts(s[i].name);
}
return 0;
}
an example is following:-
#include <stdio.h>
#include <stdlib.h>
struct student
{
char name1[50];
char name2[50];
char name3[50];
char name4[50];
char name5[50];
}s;
int main()
{
printf("enter name of 1s students\n");
scanf("%s",s.name1);
printf("enter name of 2 students\n");
scanf("%s",s.name2);
printf("enter name of 3 students\n");
scanf("%s",s.name3);
printf("enter name of 4 students\n");
scanf("%s",s.name4);
printf("enter name of 5 students\n");
scanf("%s",s.name5);
// displaying name
printf("displaying name of five students \n");
printf("name of 1 student : \n");
puts(s.name1);
printf("name of 2 student : \n");
puts(s.name2);
printf("name of 3 student : \n");
puts(s.name3);
printf("name of 4 student : \n");
puts(s.name4);
printf("name of 5 student : \n");
puts(s.name5);
return 0;
}
But while we use a loop in a programme, then it makes it so simple and reduces time.
An example is following:-
#include<stdio.h>
struct student
{
char name[50];
}s[5];
int main()
{
int i;
//storing information in structure
for(i=1; i<=5; i++)
{
printf("enter name of students : %d\n",i);
scanf("%s",s[i].name);
}
//displaying information now
for(i=1; i<=5; i++)
{
printf("name of student :%d \n",i);
puts(s[i].name);
}
return 0;
}
Comments
Post a Comment