I have a question | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

I have a question

The question is Write a program that reads the names and the age of each student in a class of 7. Find and display the oldest and the youngest using array concept https://code.sololearn.com/c6k6rM5o0pWa/? ref=app How can I have an output like The Oldest is Alen 76 The youngest is Gary 26

8th Nov 2021, 4:17 PM
Shilla 🇷🇼
Shilla 🇷🇼 - avatar
3 Answers
+ 4
Take another variables for those name's index store . Then you can get it. edit: #include <stdio.h> struct students{ char names[10]; int age; }s[7]; int main() //use int main { int a,old,young, oldi=0,youngi=0; //2 more valuable s for(a=0;a<7;a++){ printf("Name %d\n",a+1); scanf("%s",s[a].names); printf("Age %d\n",a+1); scanf("%d",&s[a].age); } old=s[0].age; for(a=0;a<7;a++){ if(old<s[a].age){ old=s[a].age; oldi=a; //saving index } } printf("The oldest is %s %d\n",s[oldi].names,old); young=s[0].age; for(a=0;a<7;a++){ if(young>s[a].age){ young=s[a].age; youngi=a; //saving index } } printf("The youngest is %s %d",s[youngi].names, young); return 0; } //better to reduced code to use less loop, for fair better readability.. use block separation. //hope it helps..
8th Nov 2021, 6:11 PM
Jayakrishna 🇮🇳
+ 2
Jayakrishna🇮🇳 I was trying to solve like you did but why there is error? Edited: Ok got it s is a structure so we need to access name with s[index].names. https://code.sololearn.com/ccW3yt4LGnyd/?ref=app Shilla 🇷🇼 Indent your code so it would be easy to understand. Working here: https://code.sololearn.com/cx2RPHq30gJf/?ref=app
8th Nov 2021, 8:12 PM
A͢J - avatar
+ 1
Shilla 🇷🇼 note that there are errors. Declare main() as int main(). In line 10 remove the & from s[a].names. Jayakrishna🇮🇳 shows you a good way to get the name, which is by saving the index. Since the index also indicates where age is stored, you could save only the index in old and young. Also you could reduce processing. Get the input, check for oldest, check for youngest all in the same loop. #include <stdio.h> struct students{ char names[10]; int age; } s[7]; int main() { int old = 0, young = 0; for (int a = 0; a<7; a++) { printf("Name %d\n", a+1); scanf("%s", s[a].names); printf("Age %d\n", a+1); scanf("%d", &s[a].age); if (s[old].age<s[a].age) { old = a; } if (s[young].age>s[a].age) { young = a; } } printf("The oldest is %s %d\n", s[old].names, s[old].age); printf("The youngest is %s %d\n", s[young].names, s[young].age); return 0; }
8th Nov 2021, 7:19 PM
Brian - avatar