Problem and Solution

Here, I'm posting problems and exercises I have solved.
Personal Blog: w9ahmed
For Algorithms and Data Structure posts, check Algostruc.
Follow me on Twitter @w9ahmed
Recent Tweets @w9ahmed

#ifndef DOUBLY_LINKED_LIST

#define DOUBLY_LINKED_LIST

template<class T>

class DLLNODE

{

public:

DLLNODE()

{ next = prev = 0; }

DLLNODE(const T& el, DLLNODE* n = 0, DLLNODE* p = 0)

{ info = el; next = n; prev = p; }

T info;

DLLNODE *next, *prev;

};

/* **** **** **** **** **** **** **** **** **** **** **** **** */

template<class T>

class DoublyLinkedList

{

public:

DoublyLinkedList()

{ head = tail = 0; }

void addToDLLTail(const T&);

void addToDLLHead(const T&);

T deleteFromDLLTail();

T deleteFromDLLHead();

void deleteNode(const T&);

protected:

DLLNODE<T> *head, *tail;

};

/* **** **** **** **** **** **** **** **** **** **** **** **** */

template<class T>

void DoublyLinkedList<T>::addToDLLTail(const T& el)

{

if(tail!=0) {

tail = new DLLNODE<T>(el, 0, tail);

tail->prev->next = tail;

}

else

head = tail = new DLLNODE<T>(el);

}

/* **** **** **** **** **** **** **** **** **** **** **** **** */

template<class T>

void DoublyLinkedList<T>::addToDLLHead(const T& el)

{

if(head!=0) {

head = new DLLNODE<T>(el, head);

head->next->prev = head;

}

else

head = tail = new DLLNODE<T>(el);

}

/* **** **** **** **** **** **** **** **** **** **** **** **** */

template<class T>

T DoublyLinkedList<T>::deleteFromDLLTail()

{

T el = tail->info;

if(head == tail)

{ delete head; head = tail = 0; }

else

{

tail = tail->prev;

delete tail->next;

tail->next = 0;

}

return el;

}

/* **** **** **** **** **** **** **** **** **** **** **** **** */

template<class T>

T DoublyLinkedList<T>::deleteFromDLLHead()

{

T el = head->info;

if(head == tail)

{ delete head; head = tail = 0; }

else

{

head = head->next;

delete head->prev;

head->prev = 0;

}

return el;

}

/* **** **** **** **** **** **** **** **** **** **** **** **** */

template<class T>

void DoublyLinkedList<T>::deleteNode(const T& el)

{

if(head == tail && head->info == el)

{ delete head; head = tail = 0; }

else {

DLLNODE<T> *tmp;

for(tmp = head; tmp->next!=0 && !(tmp->info==el); tmp = tmp->next);

if(tmp->prev==0)

{

head = tmp->next;

head->prev = 0;

delete tmp;

} //

else if(tmp->next==0)

{

tail = tmp->prev;

tail->next = 0;

delete tmp;

} //

else {

tmp->prev->next = tmp->next;

tmp->next->prev = tmp->prev;

}

}

}

/* **** **** **** **** **** **** **** **** **** **** **** **** */

#endif // !DOUBLY_LINKED_LIST

From Data Structures and Algorithms in C++ by Adam Drozdek,

Section 1.12, Programming Assignments:

Write a class Fraction that defines adding, subtracting  multiplying and dividing fractions by overloading standard operators for these operations. Write a function member for reducing factors and overload I?O operators to input and output fractions. 

Solution:

#include<iostream>

using namespace std;

class Fraction

{

private:

int num, den;

public:

Fraction(int n = 1, int d = 2) : num(n), den(d) { }

void show() { cout«num«”/”«den; }

Fraction operator+(Fraction f) const

{ return Fraction(num+f.num, den+f.den); }

Fraction operator-(Fraction f) const

{ return Fraction(num-f.num, den-f.den); }

Fraction operator*(Fraction f) const

{ return Fraction(num*f.num, den*f.den); }

Fraction operator/(Fraction f) const

{

int rNum = (f.den*num)/den;

return (rNum, f.num);

}

friend ostream& operator«(ostream& out, Fraction& f)

{ cout«f.num«”/”«f.den; return out; }

friend istream& operator»(istream& in, Fraction& f)

{ cout«”\nEnter Numerator: “; cin»f.num; cout«”Enter Denominator: “;

 cin»f.den; cout«f.num«”/”«f.den; return in; }

int ndMax()

{ return (num<=den) ? num:den; }

void reduce()

{

for(int i = 2; i<=ndMax(); i++)

if(num%i == 0 && den%i == 0)

{ num = num/i; den = den/i; i = 1; }

}

}; // 

int main()

{

Fraction f1(5, 6);

Fraction f2(80, 1001);

cout«f1«” and “«f2«endl;

Fraction f3 = f1/f2;

f3.reduce(); cout«f3;

cout«endl;

return 0;

}

#include<iostream>
using namespace std;

const int LEN = 80;

class Employee
{
private:
    char name[LEN];
    unsigned long number;
public:
    friend istream& operator» (istream& s, Employee& e)
    {
        cout«”\nEnter Last Name: “; cin»e.name;
        cout«”Enter Number: “; cin»e.number;
        return s;
    }

    friend ostream& operator« (ostream& s, Employee e)
    { cout«”\nName: “«e.name; cout«”\nNumber: “«e.number; return s; }
};

/* ***** ***** ***** ***** ***** ***** ***** ***** ***** */
/* ***** ***** ***** ***** ***** ***** ***** ***** ***** */

template <class Type>
struct Link
{ Type data; Link* next; };

template <class Type>
class LinkList
{
private:
    Link<Type>* first;
public:
    LinkList()
    { first = NULL; }

    void addItem(Type var)
    {
        Link<Type>* newlink = new Link<Type>;
        newlink->data = var; newlink->next = first;
        first = newlink;
    }

    void display()
    {
        Link<Type>* current = first;
        while(current!=NULL)
        {
            cout«endl«current->data;
            current = current->next;
        }
    }
};

/* ***** ***** ***** ***** ***** ***** ***** ***** ***** */
/* ***** ***** ***** ***** ***** ***** ***** ***** ***** */

int main()
{
    LinkList<Employee> emp;
    Employee empTemp;
    char ans;

    do
    {
        cin»empTemp;
        emp.addItem(empTemp);
        cout«”\nAdd another? (y/n): “; cin»ans;
    } while(ans == ‘y’);

    emp.display();
    cout«endl;

    return 0;
}

#include<iostream>
#include<fstream>
#include<typeinfo>
#include<process.h>
using namespace std;

const int LEN = 32;
const int MAXEM = 100;
enum employee_type {tmanager, tscientist, tlaborer};

//\////\////\////\////\////\////\////\////\////\////\////\////\////\////\////\////\//
//\////\////\////\////\////\////\////\////\////\////\////\////\////\////\////\////\//

class Employee
{
private:
    char name[LEN];
    unsigned long number;
    static int n;
    static Employee* arrap[];
public:
    virtual void getData()
    {
        cin.ignore(10, ‘\n’);
        cout«”Enter Name: “; cin»name;
        cout«”Enter Number: “; cin»number;
    }

    virtual void putData()
    {
        cout«”\nName: “«name;
        cout«”\nNumber: “«number;
    }

    virtual employee_type get_type();
    static void add();
    static void display();
    static void read();
    static void write();
};
//\////\////\////\////\////\////\////\////\////\////\////\////\////\////\////\////\//

int Employee::n;
Employee* Employee::arrap[MAXEM];

//\////\////\////\////\////\////\////\////\////\////\////\////\////\////\////\////\//
//\////\////\////\////\////\////\////\////\////\////\////\////\////\////\////\////\//

class Manager : public Employee
{
private:
    char title[LEN];
    double dues;
public:
    void getData()
    {
        Employee::getData();
        cout«”Enter Title: “; cin»title;
        cout«”Enter Dues: “; cin»dues;
    }

    void putData()
    {
        Employee::putData();
        cout«”\nTitle: “«title;
        cout«”\nDues: “«dues;
    }
};

//\////\////\////\////\////\////\////\////\////\////\////\////\////\////\////\////\//
//\////\////\////\////\////\////\////\////\////\////\////\////\////\////\////\////\//

class Scientist : public Employee
{
private:
    int pubs;
public:
    void getData()
    {
        Employee::getData();
        cout«”Enter Pubs: “; cin»pubs;
    }

    void putData()
    {
        Employee::putData();
        cout«”\nPubs: “«pubs;
    }
};

//\////\////\////\////\////\////\////\////\////\////\////\////\////\////\////\////\//
//\////\////\////\////\////\////\////\////\////\////\////\////\////\////\////\////\//

class Laborer : public Employee
{ };

//\////\////\////\////\////\////\////\////\////\////\////\////\////\////\////\////\//
//\////\////\////\////\////\////\////\////\////\////\////\////\////\////\////\////\//
//\////\////\////\////\////\////\////\////\////\////\////\////\////\////\////\////\//
//\////\////\////\////\////\////\////\////\////\////\////\////\////\////\////\////\//

void Employee::add()
{
    char ch;
    cout«“‘m’ to add a manager”
        ”\n’s’ to add a scientist”
        ”\n’l’ to add a laborer”
        ”\nEnter selection: “; cin»ch;

    switch(ch)
    {
    case ‘m’: arrap[n] = new Manager; break;
    case ‘s’: arrap[n] = new Scientist; break;
    case ‘l’: arrap[n] = new Laborer; break;
    default: cout«”\nUnknown Employee type\n”; return;
    }

    arrap[n++]->getData();
}

//\////\////\////\////\////\////\////\////\////\////\////\////\////\////\////\////\//

void Employee::display()
{
    for(int i=0; i<n; i++)
    {
        cout«(i+1);
        switch(arrap[i]->get_type())
        {
        case tmanager: cout«”. Type: Manager”; break;
        case tscientist: cout«”. Type: Scientist”; break;
        case tlaborer: cout«”. Type: Laborer”; break;
        default: cout«”. Unknown Type”;
        }

        arrap[i]->putData();
        cout«endl;
    }
}

//\////\////\////\////\////\////\////\////\////\////\////\////\////\////\////\////\//

employee_type Employee::get_type()
{
    if(typeid(*this) == typeid(Manager))
        return tmanager;
    else if(typeid(*this) == typeid(Scientist))
        return tscientist;
    else if(typeid(*this) == typeid(Laborer))
        return tlaborer;
    else
    { cerr«”\nBad Employee Type”; exit(1); }

    return tmanager;
}

//\////\////\////\////\////\////\////\////\////\////\////\////\////\////\////\////\//

void Employee::write()
{
    int size; cout«”Writing “«n«” Employes.\n”;
    ofstream ouf;
    employee_type eType;

    ouf.open(“EMPLOY.DAT”, ios::trunc | ios::binary);
    if(!ouf)
    { cout«”\nCan’t open file\n”; return; }

    for(int j=0; j<n; j++)
    {
        eType = arrap[j]->get_type();
        ouf.write((char*)&eType, sizeof(eType));
        switch(eType)
        {
        case tmanager: size=sizeof(Manager); break;
        case tscientist: size=sizeof(Scientist); break;
        case tlaborer: size=sizeof(Laborer); break;
        }

        ouf.write((char*)(arrap[j]), size);
        if(!ouf)
        { cout«”\nCan’t write to file\n”; return; }
    }
}

//\////\////\////\////\////\////\////\////\////\////\////\////\////\////\////\////\//

void Employee::read()
{
    int size; employee_type eType;
    ifstream inf;
    inf.open(“EMPLOY.DAT”, ios::binary);
    if(!inf)
    { cout«”\nCan’t open file\n”; return; }

    n = 0;
    while(true)
    {
        inf.read((char*)&eType, sizeof(eType));
        if(inf.eof())
            break;
        if(!inf)
        { cout«”Can’t read type from file\n”; return; }
        switch(eType)
        {
        case tmanager: arrap[n] = new Manager; size = sizeof(Manager); break;
        case tscientist: arrap[n] = new Scientist; size = sizeof(Scientist); break;
        case tlaborer: arrap[n] = new Laborer; size = sizeof(Laborer); break;
        default: cout«”\nUnknwon type in file\n”; return;
        } //

        inf.read((char*)arrap[n], size);
        if(!inf)
        { cout«”\nCan’t read data from file\n”; return; }
        n++;
    } //

    cout«”Reading “«n«” Employees.”«endl;
}

//\////\////\////\////\////\////\////\////\////\////\////\////\////\////\////\////\//
//\////\////\////\////\////\////\////\////\////\////\////\////\////\////\////\////\//
//\////\////\////\////\////\////\////\////\////\////\////\////\////\////\////\////\//
//\////\////\////\////\////\////\////\////\////\////\////\////\////\////\////\////\//

int main()
{
    char ch;
    while(true)
    {
        cout«“‘a’ — add data for an employee”
            ”\n’d’ — display data for all employees”
            ”\n’w’ — write all employee data to file”
            ”\n’r’ — read all employee data from file”
            ”\n’x’ — exit” “\nEnter selection: “; cin»ch;
        switch(ch)
        {
        case ‘a’: Employee::add(); break;
        case ‘d’: Employee::display(); break;
        case ‘w’: Employee::write(); break;
        case ‘r’: Employee::read(); break;
        case ‘x’: exit(0);
        default: cout«”\nUnknown command.”;
        } //
    } //

    return 0;
}

//\////\////\////\////\////\////\////\////\////\////\////\////\////\////\////\////\//

From Problem #19, add a member function of type bool called isOversize() to the book and tape classes. Let’s say that a book with more than 800 pages or a tape with a playing time longer than 90 minutes is considered oversize. You can access this function from main() and display the string “oversize” for books and tapes when you display their other data. If book and tape objects are to be accessed using pointers to them that are stored in an array of type publication, what do you need to add to the publication base class? Can you instantiate members of this base class? “The answer to the last question is NO”

Solution:

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

class Publication
{
private:
    string title;
    float price;
public:
    void getName()
    {
        cout«”Enter Title: “; cin»title;
        cout«”Enter Price: $”; cin»price;
    }

    void putName()
    {
        cout«”\nTitle: “«title;
        cout«”, Price: $”«price;
    }

    virtual void getData() = 0;
    virtual bool isOversize() = 0;
};

class Book : public Publication
{
private:
    int pages;
public:
    void getData()
    {
        Publication::getName();
        cout«”Enter Pages: “; cin»pages;
    }

    void putData()
    {
        Publication::putName();
        cout«”, Pages: “«pages«endl;
    }

    bool isOversize()
    { return ((pages>800) ? true : false); }
};

class Tape : public Publication
{
private:
    float minutes;
public:
    void getData()
    {
        Publication::getName();
        cout«”Enter Minutes: “; cin»minutes;
    }

    void putData()
    {
        Publication::putName();
        cout«”, Minutes: “«minutes«endl;
    }

    bool isOversize()
    { return ((minutes>90) ? true : false); }
};

int main()
{
    Publication* ptrPub[100];
    int n = 0;
    char choice;

    do
    {
        cout«”Book or Tape? (b/t): “; cin»choice;
        if(choice == ‘b’)
        { ptrPub[n] = new Book; ptrPub[n]->getData(); }
        else
        { ptrPub[n] = new Tape; ptrPub[n]->getData(); }
        n++; cout«”Enter another? (y/n): “; cin»choice;
    } while(choice == ‘y’);

    for(int i=0; i<n; i++)
    {
        ptrPub[i]->putName();
        if(ptrPub[i]->isOversize())
            cout«” [OVERSIZE]”;
    }
  
    cout«endl;
    return 0;
}

#include<iostream>
using namespace std;

class Array
{
private:
    int* ptr;
    int size;
public:
    Array()
    { size = 0; ptr = NULL; }

    Array(int s)
    { size = s; ptr = new int[s]; }

    ~Array()
    { delete[] ptr; }

    int& operator[] (int j)
    { return *(ptr+j); }

    Array(Array& A) //copy-constructor
    {
        size = A.size;
        ptr = new int[size];
        for(int j=0; j<size; j++)
            *(ptr+j) = *(A.ptr+j);
    }

    Array operator= (Array& A)
    {
        delete[] ptr;
        size = A.size;
        ptr = new int[A.size];
        for(int j=0; j<size; j++)
            *(ptr+j) = *(A.ptr+j);

        return *this;
    }
};

int main()
{
    const int ASIZE = 10;
    Array arr(ASIZE);

    cout«”Arr1: “;
    for(int j = 0; j<ASIZE; j++)
        arr[j] = j*j;

    for(int j = 0; j<ASIZE; j++)
        cout«arr[j]«” “;

    Array arr2(arr);
    cout«”\nArr2: “;
    for(int j = 0; j<ASIZE; j++)
        cout«arr2[j]«” “;

    Array arr3;
    arr3 = arr;
    cout«”\nArr3: “;
    for(int j = 0; j<ASIZE; j++)
        cout«arr3[j]«” “;

    cout«endl;
    return 0;
}

/////////////////////////////////

#include<iostream>
#include<string>
#include<cstdlib>
using namespace std;

int isFeet(string);

class Distance
{
private:
    int feet; float inches;
public:
    Distance() : feet(0), inches(0.0)
    { }

    Distance(int ft, float in) : feet(ft), inches(in)
    { }

    void showDist()
    { cout«feet«”'-“«inches«”"”; }

    void getDist();
};

void Distance::getDist()
{
    string instr;
    while(true)
    {
        cout«”\n\nEnter feet: “;
        cin.setf(ios::skipws);
        cin»instr;
        if(isFeet(instr))
        {
            //cin.ignore(10, ‘\n’);
            feet = atoi(instr.c_str());
            break;
        }

        //cin.ignore(10, ‘\n’);
        cout«”Feet must be an integer less than 1000\n”;
    } // end WHILE feet

    while(true)
    {
        cout«”Enter inches: “;
        cin.setf(ios::skipws);
        cin»inches;
        if(inches>=12.0 || inches<0.0)
        {
            cout«”Inches must be between 0.0 and 11.99\n”;
            cin.clear(ios::failbit);
        }
        if(cin.good())
        {
            cin.ignore(10, ‘\n’);
            break;
        }
        cin.clear();
        cin.ignore(10, ‘\n’);
        cout«”Incorrect inches input\n”;
    } // end WHILE inches
}

int isFeet(string str)
{
    int slen = str.size();
    if(slen == 0 || slen>5)
        return 0;
    for(int j = 0; j<slen; j++)
        if((str[j] < ‘0’ || str[j] > ‘9’) && str[j] != ‘-‘)
            return 0;
    double n = atof(str.c_str());
    if(n<-999.0 || n>999.0)
        return 0;

    return 1;
}

int main()
{
    Distance d;
    char ans;

    do
    {
        d.getDist();
        cout«”\nDistance= “;
        d.showDist(); cout«”\nDo another? (y/n) “;
        cin»ans;
        cin.ignore(10, ‘\n’);
    } while(ans != ‘n’);

    return 0;
}

In the program "To check if a number is prime," why is "n" not divided by two in the for loop: for(int i = 1; i<n; i++)?
codesolution codesolution Said:

Okay, here’s how I thought to solve this (I never tried another way so if you have another solution, please fill me in  ), a prime number is only divided by itself or by 1, so I check if the number is dividable by any other number; then it’s not prime.
Why n not divided by 2? because I could have an odd number which is not dividable by 2. so to check if n is divided by i, I go for the the modulo operation, it finds the remainder of division of one number by another.
if n mod i equals zero (which leaves a remainder of 0), then n is divided by i.

And actually there’s no need for the first if statement in the for loop, so I removed it:

int main()
{
    int n = 9; // the number we want to check
    bool isPrime = true;
    for(int i = 2; i<n; i++)
    {
         if(n%i==0)
         {
            isPrime = false;
            break;
         }
    }

    cout«n«((isPrime) ?” is prime” :” is not prime”)«endl;
    return 0;
}

I hope this answers your question

Asker ttendohv Asks:
Hi, there! I am currently in college right now, and just recently started gaining more and more interest for computer programming and I am aspiring to be a software engineer. I noticed your programs were in C++, what are all of the programming languages that you know? What are some tips you can give someone like me, wanting to go further with this? Thanks! I really appreciate it. :)
codesolution codesolution Said:

Hello! I know C++, Java and C# and I’m planning to dive more into Python (which is a scripting language). I’ve just graduated from college this year and like you, I want to be a software engineer, I’ll tell what I do to go further with it:

  1. Books are very important, If you hate to read; you must force yourself because you don’t get everything from college,  learning never stops.
  2. Practice, find some problems to solve; when you get stuck with a problem: don’t give up, keep trying until you solve it.
  3. THIS IS A MUST: Algorithms & Data Structure
  4. Math is also important

I wish I’ve helped, and if you need any help, I’ll be glad to help :) Thanks!

Create a class called publication that stores the title (a string) and price (type float) of a publication.
From this class derive two classes: book, which adds a page count (type int); and a tape, which adds a playing time in minutes (type float). Each of the three classes should have a getData() function to get its data from the user at the keyboard and a putData() to display the data.
Write a main() program that creates an array of pointers to publication. In a loop, ask the user for data about a particular book or tape and use new to create an object of type book or tape to hold the data. Put the pointer to the object in the array. When the user finished entering the data for all books and tapes, display he resulting data for all the books and tapes entered, using a for loop and a single statement.

Solution:

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

class Publication
{
private:
    string title;
    float price;
public:
    void getName()
    {
        cout«”Enter Title: “; cin»title;
        cout«”Enter Price: $”; cin»price;
    }

    void putName()
    {
        cout«”\nTitle: “«title;
        cout«”, Price: $”«price;
    }

    virtual void getData() = 0;
};

class Book : public Publication
{
private:
    int pages;
public:
    void getData()
    {
        Publication::getName();
        cout«”Enter Pages: “; cin»pages;
    }

    void putData()
    {
        Publication::putName();
        cout«”, Pages: “«pages«endl;
    }
};

class Tape : public Publication
{
private:
    float minutes;
public:
    void getData()
    {
        Publication::getName();
        cout«”Enter Minutes: “; cin»minutes;
    }

    void putData()
    {
        Publication::putName();
        cout«”, Minutes: “«minutes«endl;
    }
};

int main()
{
    Publication* ptrPub[100];
    int n = 0;
    char choice;

    do
    {
        cout«”Book or Tape? (b/t): “; cin»choice;
        if(choice == ‘b’)
        { ptrPub[n] = new Book; ptrPub[n]->getData(); }
        else
        { ptrPub[n] = new Tape; ptrPub[n]->getData(); }
        n++; cout«”Enter another? (y/n): “; cin»choice;
    } while(choice == ‘y’);

    for(int i=0; i<n; i++)
        ptrPub[i]->putName();
   
    cout«endl;
    return 0;
}

#include<iostream>
using namespace std;

int main()
{
    int n = 29; // the number we want to check
    bool isPrime = true;
    for(int i = 1; i<n; i++)
    {
        if(n!=i && i!=1)
        {
            if(n%i==0)
            {
                isPrime = false;
                break;
            }
        }
    }

    cout«n«((isPrime) ? ” is prime” : ” is not prime”)«endl;
    return 0;
}

Problem 2 from Project Euler:

Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:

1, 2, 3, 5, 8, 13, 21, 34, 55, 89, …

By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

Solution:

#include<stdio.h>

int main()
{
    int num = 0, temp1 = 0, temp2 = 1;
    int result = 0;

    while(num<4000000)
    {
        num = temp1 + temp2;
        temp1 = temp2;
        temp2 = num;

        if(num%2 == 0)
            result+=num;
    }

    printf(“Result: %d\n”, result);
    return 0;
}

Problem 1 from Project Euler:

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

Find the sum of all the multiples of 3 or 5 below 1000.

Solution:

#include<stdio.h>

int main()
{
    int total = 0;

    for(int i=1; i<=999; i++)
        if(i%3 == 0 || i%5 == 0)
            total+=i;

    printf(“Sum: %d\n”, total);

    return 0;
}

Problem #15 is inelegant because each of the 10 int arrays is declared in a different program statement, using a different name. each of their addresses must also be obtained using a separate statement. You can simplify things by using new, which allows you to allocate the arrays in a loop and assign pointers to them at the same time:

for(int j=0; j<NUMARRAYS; j++) // allocate NUMARRAYS arrays
        *(aptr+j) = new int[MAXSIZE]; // each MAXSIZE ints long

Rewrite the program to use this approach. You can access the elements of the individual arrays using the same expression mentioned in Problem #15 or you can use pointer notation: *(*(aptr+j)+k). The two notations are equivalent.

Solution:

#include<iostream>
using namespace std;

const int MAXSIZE = 10;

int main()
{
    int* aptr[MAXSIZE];
    for(int j=0; j<MAXSIZE; j++)
        *(aptr+j) = new int[MAXSIZE];
    int m = 1;

    /* Populating */
    for(int j=0; j<MAXSIZE; j++)
    {
        for(int i =0; i<MAXSIZE; i++)
        {
            *(*(aptr+j)+i) = 10*m;
            m++;
        }
        m+=10;
    }

    /* Displaying */
    for(int j=0; j<MAXSIZE; j++)
    {
        cout«”Array[“«j+1«”]: “;
        for(int i =0; i<MAXSIZE; i++)
            cout«*(*(aptr+j)+i)«” “;
        cout«endl;
    }



    return 0;
}

Let’s say that you need to store 100 integers so that they’re easily accessible. However, let’s further assume that there’s a problem: The memory in your computer is so fragmented that the largest array that you can use holds only 10 integers. (Such problems actually arises, although usually with larger memory objects.) You can solve this problem by defining 10 separate int arrays of 10 integers each and an array of 10 pointers to these arrays. The int arrays can have names like a0, a1, a2, and so on. The address of each of these arrays can be stored in the pointer array of type int*, which can have a name like ap (for array of pointers). You can then access individual integers using expressions like ap[j][k], where j steps through the pointers in ap and k steps through individual integers in each array. This looks as if you’re accessing a two-dimensional array, but it’s really a group of one-dimensional arrays.

Fill such a group pf arrays with test data, then display the data to make sure it’s correct.

Solution:

#include<iostream>
using namespace std;

int main()
{
    int a1[10] = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100};
    int a2[10] = {110, 120, 130, 140, 150, 160, 170, 180, 190, 200};
    int a3[10] = {210, 220, 230, 240, 250, 260, 270, 280, 290, 300};
    int a4[10] = {310, 320, 330, 340, 350, 360, 370, 380, 390, 400};
    int a5[10] = {410, 420, 430, 440, 450, 460, 470, 480, 490, 500};
    int a6[10] = {510, 520, 530, 540, 550, 560, 570, 580, 590, 600};
    int a7[10] = {610, 620, 630, 640, 650, 660, 670, 680, 690, 700};
    int a8[10] = {710, 720, 730, 740, 750, 760, 770, 780, 790, 800};
    int a9[10] = {810, 820, 830, 840, 850, 860, 870, 880, 890, 900};
    int a10[10] = {910, 920, 930, 940, 950, 960, 970, 980, 990, 1000};

    int* aptr[10] = {a1, a2, a3, a4, a5, a6, a7, a8, a9 , a10};

    for(int i=0; i<10; i++)
    {
        cout«”Array[“«i«”]: “;
        for(int j=0; j<10; j++)
            cout«aptr[i][j]«”, “;
        cout«endl;
    }

    return 0;
}

In the other LinkedList I’ve posted earlier on this blog displays the output in inverse, so that if I entered: 25, 367, 49 and 64. The output will be 64, 49, 36, 25.

I’ve modified it so it displays the output as it is:

#include<iostream>
using namespace std;

struct link
{
    int data;
    link* next;
};

class LinkedList
{
private:
    link* first;
    link* firstOfFirst;
public:
    LinkedList()
    { first = NULL; }

    ~LinkedList()
    {
        link* current = firstOfFirst;
        while(current!=NULL)
        {
            link* temp = current;
            current = current->next;
        }
    }

    void addItem(int d)
    {
        link* newlink = new link;
        newlink->data = d;
        newlink->next = NULL;
        if(first!=NULL)
        { first->next = newlink; first = newlink; }

        else
        { first = newlink; firstOfFirst = newlink; }

    }

    void display()
    {
        link* current = firstOfFirst;
        while(current!=NULL)
        {
            cout«current->data«endl;
            current = current->next;
        }
    }
};

int main()
{
    LinkedList li;
    li.addItem(25);
    li.addItem(36);
    li.addItem(49);
    li.addItem(64);
    li.display();
    return 0;
}