N
N
noob noob2020-10-20 18:20:17
C++ / C#
noob noob, 2020-10-20 18:20:17

How to add all elements of an array without using a C++ loop?

There is such a code, you need to add all the elements of an array without using a loop. Help me please.

#include <stdio.h>
#include <iostream>
#include <cstdlib>
#include <math.h>
using namespace std; 

int main() { 
int sum;
int students[3] = {
    1,
    4,
    7
};

sum = ?????????????;

printf("answer = %d", sum); 
return 0; 
}

Answer the question

In order to leave comments, you need to log in

3 answer(s)
P
poniyur, 2020-10-21
@YashaWeb

#include <iostream>
#include <numeric>

int main (){
   const int arrayLength = 3; // раз уж вы пользуетесь массивом, то и длину точно знаете
   int students[arrayLength] = { 1, 4, 7 };   
   int sum = std::accumulate(students, students + arrayLength, 0);
   std::cout << "The array sum is " << sum << std::endl;
   return 0;
}

A
Alexander Ananiev, 2020-10-20
@SaNNy32

sum = students[0] + students[1] + students[2];

H
Helcurt, 2020-10-20
@Radia

If the array is of reasonable size, you can enumerate everything by hand sum = students[0] + students[1] + students[2] + ... + students[n]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question