Programming with Passion

Make the best out of everything.

Monday, 21 March 2016

C++ Memory Management

C++ Memory Management

C++ Program to store GPA of n number of students and display it where n is the number of students entered by user.

#include <iostream>
#include <cstring>
using namespace std;

int main() {
    int n;
    cout << "Enter total number of students: ";
    cin >> n;
    float* ptr;
    
    ptr = new float[n];       // memory allocation for n number of floats

    cout << "Enter GPA of students." <<endl;
    for (int i = 0; i < n; ++i) {
        cout << "Student" << i+1 << ": ";
        cin >> *(ptr + i);
    }
    cout << "\nDisplaying GPA of students." << endl;
    for (int i = 0; i < n; ++i) {
        cout << "Student" << i+1 << " :" << *(ptr + i) << endl;
    }

    delete [] ptr;    // ptr memory is released

    return 0;
}
Output
Enter total number of students: 4
Enter GPA of students.
Student1: 3.6
Student2: 3.1
Student3: 3.9
Student4: 2.9

Displaying GPA of students.
Student1 :3.6
Student2 :3.1
Student3 :3.9
Student4 :2.9

No comments:

Post a Comment