array and function

Dec 8, 2013 at 2:04pm
guys can anyone help me with this, i built a program that accepts two input from the user, using a array inside a loop, it is pass to a function inside a class which will display the two number, the problem is when the user is inputting a number and it is 1 the program continuously as the user to input a number, and when 2 is entered the program ask another number and end, but for example you entered 2 and 3. . . it will then outpu 2 and 4 (so 3 + 1 ) and always the last number is plus one. here is the code. thanks in advance.

main.cpp

#include <iostream>
#include "newclass.h"
using namespace std;
int main()
{
int array_variable_main[2];
for(int counter = 1; counter <= 2; counter=counter+1)
{
cout << "Enter a Number: " << endl;
cin >> array_variable_main[counter];
}
newclass sum_object;
sum_object.loop_function(array_variable_main, 2);
return 0;
}




newclass.cpp

#include "newclass.h"
#include <iostream>
using namespace std;
newclass::newclass()
{
}
void newclass::loop_function(int array_variable[], int arraysize)
{
cout << "The numbers that are stored in the array are: " << endl;
for(int counter = 1; counter <= arraysize; counter = counter+1)
{
cout << array_variable[counter] << endl;
}
}







newclass.h

#ifndef NEWCLASS_H
#define NEWCLASS_H
class newclass
{
public:
newclass();
void loop_function(int array_variable[], int arraysize);
};
#endif // NEWCLASS_H

Dec 8, 2013 at 3:12pm
@jcp

Without actually running your program, the main error I see is..
1
2
3
4
5
6
7
{
int array_variable_main[2];
for(int counter = 1; counter <= 2; counter=counter+1)
{
cout << "Enter a Number: " << endl;
cin >> array_variable_main[counter];
}


Arrays in C++ are zero based, so your array would be array_variable_main[0] and array_variable_main[1], but you are trying to put data into array_variable_main[1] and array_variable_main[2]. Try changing
 
for(int counter = 1; counter <= 2; counter=counter+1)

to
 
for(int counter = 0; counter < 2; counter++)

and see if that doesn't help.
Last edited on Dec 8, 2013 at 6:23pm
Dec 10, 2013 at 10:42am
OMG, I thought all guys here will just ignore me :(, tears in my eyes Sir, thank your very much for your reply I will try it then I will tell you how it goes, from the deepest of my heart thank you with love XD, bless you.
Dec 10, 2013 at 10:47am
Sir it did not solve the problem, any other suggestion?
Dec 10, 2013 at 1:14pm
I'm so sorry, sir it works, thank you very much! god bless
Dec 10, 2013 at 9:54pm
@jcp

Good to hear that your program now works.. And you're welcome.
Topic archived. No new replies allowed.