-4

I am trying to count the number of odd values in the elements of the array. Is there a way to perform the below operation without declaring a variable inside the for loop? I am aware that the variable declared inside the loop cannot be accessed outside the loop and I want to know if there is a way that the following loop is performed and the value of oddValueCountKS could be accessed outside of the loop.

int arr[3] = {1004, -237890, 30022};
     
for (int i = 0; i < 3; i++) {
  int oddValueCountKS = 0;
         
  while (arr[i] != 0) {
    if (arr[i] % 2) {
      oddValueCountKS++;
    }
    arr[i] /= 10;
  }
}
rmlockerd
  • 3,776
  • 2
  • 15
  • 25
Kshitiz Sampang
  • 29
  • 1
  • 1
  • 12

2 Answers2

1
int arr[3] = {1004,-237890,30022};
int oddValueCountKS[3] = {0};
 
 for (int i = 0; i < 3; i++) {

     while (arr[i] != 0) {

         if (arr[i] % 2) {
             oddValueCountKS[i]++;
         }
         arr[i] /= 10;
        
     }
    
 }
Ok MrJin
  • 11
  • 3
0

Declare it outside the loop

int oddValueCountKS;
for (int i = 0; i < 3; i++) {
    oddValueCountKS = 0;
    //the rest of your code
}

this way you will be able to access it outside

Maz
  • 11
  • 4
  • This will only give access to the `oddValueCountKS` calculated for `i == 2` the information for `i<2` is lost, so those steps of the loop are kinda useless. – t.niese Oct 07 '20 at 07:15