[Solved] Teaching Sum Of Elements with C++

Mrs. Anitha , our favourite Maths teacher wanted to teach her new batch of students to find the sum of a set of numbers. In their first attempt, all her students computed the sum wrongly but to her surprise she found that all the students have got the same answer. On analyzing the answer, she found that students are good in addition but they have neglected the negative sign present in front of some numbers. She taught them about positive and negative numbers and she again gave the same problem to the students. All the students did the problem correctly and Mrs. Anitha was happy.
 

Write a program to accept a set of n integers and to calculate the wrong sum and the correct sum using functions.

Input Format:
Input consists of n+1 integers. The first integer corresponds to ‘n’, the number of elements in the set. The next ‘n’ integers correspond to the elements in the set. Assume that the maximum value of n is 20.

Output Format:
Output consists of 2 integers. The first integer corresponds to the wrong sum and the second integer corresponds to the correct sum.

Note:

Please use the same prompt statements given in the sample input and output

Sample Input:

5
-1
2
-3
4
-5

Sample Output:

15
-3

PROBLEM REQUIREMENTS:
int wrongsetsum(int n, int * a)
int correctsetsum(int n, int * a)

Function Definitions:

int wrongsetsum (int n, int * a) 
int  correctsetsum (int n, int * a) 

Solution

#include <iostream>
using namespace std;

int wrongsetsum(int n, int * a)
{
    int sum = 0;
    for (int i = 0; i < n; i++)
    {
        sum += a[i];
    }
    return sum;
}


int correctsetsum(int n, int * a)
{
    int sum = 0;
    for (int i = 0; i < n; i++)
    {
        if (a[i] > 0)
        {
            sum += a[i];
        }
        else
        {
            sum -= a[i];
        }
    }
    return sum;
}

int main()
{
    int n;
    cin >> n;
    int *a = new int[n];
    for (int i = 0; i < n; i++)
    {
        cin >> a[i];
    }
    cout << correctsetsum(n, a)<<endl;
    cout << wrongsetsum(n, a);
    return 0;
}

Happy Learning – If you require any further information, feel free to contact me.

Share your love
Saurav Hathi

Saurav Hathi

I'm currently studying Bachelor of Computer Science at Lovely Professional University in Punjab.

📌 Nodejs and Android 😎
📌 Java

Articles: 444

Leave a Reply

Your email address will not be published. Required fields are marked *