Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

Could you guys tell me why this piece of code returns 0 instead of looking for user input? C++

0 votes
asked Mar 29, 2018 by SavageMango (310 points)
#include <iostream>

using namespace std;

int add(int arr[], int size) {
cout<<"How many numbers do you want to add?"<<endl;
cin >> size ;
for(int x=0;x<size;x++){
    cout<<"Please enter a number that you wish to have in your sum"<<endl;
    cin >> arr[x] ;
    int sum=0;
    sum+=arr[x] ;
    return sum ;
}
}
 int main(){
     int add();
}

2 Answers

0 votes
answered Mar 29, 2018 by John Gabriel (310 points)
You made a lot of mistakes. Study the following code to see your mistakes.

#include <iostream>

using namespace std;

int addf(int arr[], int size)
{
    int sum=0;
    cout<<"How many numbers do you want to add?"<<endl;
    cin >> size ;
    for(int x=0;x<size;x++)
    {
       cout<<"Please enter a number that you wish to have in your sum"<<endl;
       cin >> arr[x] ;
       sum+=arr[x] ;
    }
    return sum ;
}

 int main(){
     int A[5];
     int r = addf(A, sizeof(A));
     cout<<"Sum is "<<r;
}
commented Mar 29, 2018 by anonymous
Thank you! So basically my method was correct but my approach was flawed
commented Mar 29, 2018 by anonymous
Why do you need int A[5]
0 votes
answered Apr 6, 2018 by kodathalasudarshan reddy (340 points)

actually you have written int add(); complier treats as declaration of a function. so main didn't call any function.

Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...