Setting an Array with Range-Based "for" - C++ Statement

C++ examples for Statement:for

Description

Setting an Array with Range-Based "for"

Demo Code

#include <iostream>
#include <cstdlib>
using namespace std;
#define SIZE_OF_ARRAY 5//www .  j  a  v a  2 s  .c  o m
int main()
{
  int arr[SIZE_OF_ARRAY];
  int total = 0;
  for (int& n : arr) {
    cout << "Enter array value: ";
    cin >> n;
    total += n;
  }
  cout << "Here are the values: ";
  // Print each element.
  //
  for (int n : arr) {
    cout << n << endl;
  }
  cout << "Total is: " << total << endl;
  cout << "Now, I'm going to zero out ";
  cout << "the values. " << endl;
  // Set each element to 0.
  //
  for (int& n : arr) {
    n = 0;
  }
  cout << "Here are the values: ";
  for (int n : arr) {
    cout << n << endl;
  }
  return 0;
}

Result


Related Tutorials