HW3_P1 - Student list using array

Given a Student class, create a class with following characteristics:

The class name should be ClassRoom.

Private variable students array to maintain the list of Student objects.

Function addStudent with input parameter name (string) and rollNo(int) adds a new student in "students" list.

Method getAllStudents should return all the students in ClassRoom.


Input
Jack

1

Jones

2

Marry

3

where,

First & Second line represent a student’s name and roll number. And so on.

Output

1 - Jack

2 - Jones

3 - Marry

Assume that,

Maximum "students" count can be 10.

*Driver Class*

*Solution class*

import java.util.*;

class Student {
private String name;
private int rollNo;

public String getName() {}
public void setName(String name) {}
public int getRollNo() {}
public void setRollNo(int rollNo) {}
};

class ClassRoom {

private int i;
private Student[] students;

public void addStudent(String name, int rollNo) {}
public Student[] getAllStudents() {}
};

Respuesta :

Answer:

#include<iostream>

#include<cstring>

#include <algorithm>

using namespace std;

class Student{

public:

string name;

int rollNo;

Student(){

}

Student(string n, int r){

name = n;

rollNo = r;

}

};

class ClassRoom{

public:

Student stud[10];

int count;

ClassRoom(){

count = 0;

}

void addStudent(string str,int roll){

Student s(str,roll);

stud[count++] = s;

}

Student * getAllStudents(){

return stud;

}

};

int main()

{

string name;

char temp[20];

int rollNo, N, i;

Student * students;

ClassRoom classRoom;

i=0;

while(getline(cin, name) && cin.getline(temp,20)&&i<10){

rollNo = atoi(temp);

classRoom.addStudent(name, rollNo);

i++;

}

N = i;

students = classRoom.getAllStudents();

for(int i=0 ; i < N; i++){

cout << (students+i)->rollNo << " - " << (students+i)->name;

if(i<N-1)

cout<<endl;

}

return 0;

}

Explanation:

  • In the addStudent method, increment the counter and as the value of variable s to the the stud array.
  • In the getAllStudents method, return all the students.
  • Finally in the main method, display the name and roll no. of students.