Iterate through array C++ -
this question has answer here:
newbie question
c++ array as
class app1{ int end = 3; public: int list[end]; void app1::addinput(){ for(int i=0; i<end; i++){ cout << endl << "enter elements in array: " << endl; cin >> n; list[i] = n; } } void app1::display(){ cout << endl << "display elements: " <<endl; for(int i=0; i<sizeof(list) / sizeof(list[1]); i++){ cout << << end; cout << list[i]; } cout << endl; } }
but not display array contents
you have few errors in code. have answered them in line comments can read through sequentially:
class app1 { private: int end = 3; // hsould either declared in explicit public section made, or explicit private section. public: // indent bro /* can't declare array in class because * size end not known @ compile time , compiler * needs know how many bytes allocate it. if * constant number, it. */ // int list[3]; // fine int* list_ptr = new int[end]; // better; uses heap compiler ok not knowing value of end @ compile time. however, have remember free when you're done. void addinput(){ // had app1:addinput here. namespace declaration needed if implementing method outside enclosing {} braces of class definition. in case, because implementing within `class app1{ implementation }`, not add namespace before function for(int i=0; i<end; i++){ cout << endl << "enter elements in array: " << endl; int n; // need declare n before can read it. cin >> n; list_ptr[i] = n; } } void display(){ cout << endl << "display elements: " <<endl; for(int i=0; i< end; i++){ // won't work way want; use variable end cout << "elem " << << " is: " << list_ptr[i] << endl; // youa accidentally wrote << end instead of << endl; } cout << endl; } }; // need end class declaration semicolon
Comments
Post a Comment