Practice Array as Parameter

Dear Sciaku Learner you are not logged in or not enrolled in this course.

Please Click on login or enroll now button.

If you have any query feel free to chat us!

Happy Coding! Happy Learning!

Problem: Write a program that takes an array of integers as a parameter and calculates the sum of all the elements in the array. The program should include a function that performs the calculation.

cppCopy code

#include <iostream> // Function to calculate the sum of array elements int calculateSum(int arr[], int size) {    int sum = 0;    for (int i = 0; i < size; i++) {        sum += arr[i];    }    return sum; } int main() {    const int size = 5;    int arr[size] = {1, 2, 3, 4, 5};    int sum = calculateSum(arr, size);    std::cout << "The sum of the array elements is: " << sum << std::endl;    return 0; }

In this example, we define a function called calculateSum that takes an array arr and its size size as parameters. The function iterates through each element of the array using a for loop and adds them to the sum variable. The final sum is returned.

In the main function, we declare an integer array arr with a size of 5 and initialize it with some values. We then call the calculateSum function, passing the array and its size as arguments, and store the result in the sum variable.

Finally, we print the sum of the array elements using std::cout.

2. Essential C and Cpp Concepts

0 Comments

Start the conversation!

Be the first to share your thoughts

Frequently Asked Questions About Sciaku Courses & Services

Quick answers to common questions about our courses, quizzes, and learning platform

Didn't find what you're looking for?

help_center Contact Support