Home > Back-end >  why i am not able to print data with for loop in c/c ?
why i am not able to print data with for loop in c/c ?

Time:12-28

I updated my code still it is not working. i am using simple c .

#include<iostream>
using namespace std;
class A
{
public:
    void put_data()
    {
        cout<<"hello\n";
    }
};
int main()
{
A a[3];

//working
a[0].put_data();
a[1].put_data();
a[2].put_data();

//Not working
for (int k=0;k<3;k  )
{
    cout<<a[k].put_data();
}

return 0;
}

whe i try to access object array with directly it works well, but when i try to access it with for loop not working.

CodePudding user response:

This is unnecessary:

cout<<a[k].put_data();

when the put_data() method has the cout contained inside it. It's also invalid because put_data() is void and doesn't return anything that cout could work with.

You probably mean to do just:

a[k].put_data();

CodePudding user response:

You shouldn't even be able to compile this program. The expression cout << a[k].put_data() should give you a compilation error because put_data has void as its return type. Surely your compiler showed you that error message somewhere; make sure you know how to read compiler errors.

  •  Tags:  
  • c
  • Related