Click here to Skip to main content
15,890,579 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
For example, I want
C++
int ar[2]{20, 5};
to be stored in a variable
C++
double result = 15;


What I have tried:

C++
for(int i = 0; i < 2; i++{
 result -= ar[i];
}
Posted
Updated 28-Oct-21 20:13pm
Comments
jeron1 28-Oct-21 18:15pm    
What is 'result' initialized to?
[no name] 28-Oct-21 23:48pm    
If you want the results to be 15, then you need to use {-20,5}

Besides the syntax errors, the only thing I see that is wrong with what you have is the types of the data do not agree. The array holds integers and the result is a double.

I try to avoid using literal values so I would define a constant value for the array size so your code could look something like this:
C++
const int ArraySize = 2;

int data[ArraySize] = { 20, 5 };
int result = 15;

for( int i = 0; i < ArraySize; ++i )
{
    result -= data[ i ];
}
 
Share this answer
 
Comments
CPallini 29-Oct-21 2:13am    
5.
Try also
C++
#include <iostream>
#include <array>
using namespace std;

int main()
{
  array<int,2> ar{20, 5};

  int result{15};

  for ( auto x : ar )
    result -= x;

  cout << "result = " << result << endl;
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900