0

In the below code, I want to calculate the net sum of intensity at the end of the loop, but the objective C calls zsum undeclared variable in the NSlog. How do I calculate Sum at the end off loop and pass it outside the loop.

NSMutableArray *arr = [[NSMutableArray alloc] init];
for (int x = 1; x < 20; x++) {
    double zsum = 0;
    NSMutableArray *row = [NSMutableArray new];
    for (int y = 1; y < 20; y++) {  
        uchar intensity= curFrame.at<uchar>(cvPoint(y, x));
        double zebra = double (intensity)/255;
        zsum+= zebra;
        [row addObject:[NSNumber numberWithChar:intensity]];
    }

   // NSLog(@"%d", x);

    //NSLog(@"%f",d);
    [arr addObject:[NSNumber numberWithInt:zsum]];
 //   [matrix addObject:row];
}
NSLog(@“%f",zsum);
2
  • Your trying to access the variable out side the scope of the for loop that's why zsum is undefined. Commented Dec 25, 2016 at 1:30
  • If that is the problem just initialize zsum above the scope of that for loop. Commented Dec 25, 2016 at 1:34

1 Answer 1

1

So move the decaration of zsum outside of the for loop, after the declaration of arr and just before the for loop:

NSMutableArray *arr = [[NSMutableArray alloc] init];
double zsum = 0;
for (int x = 1; x < 20; x++) {
   //The rest of your for loop code goes here.
}

In Objective-C, any time code is enclosed in braces ({ and }) that defines a new scope. Any variables declared inside those braces only exist inside those braces. When you exit the braces, the variables "go out of scope" and no longer exist. Variables defined in an outer scope are visible to more deeply nested levels of scope, but not outside.

{
  int a;
  {
    //a is visible
    int b;
    //a and b are both visible
  }
  //b is no longer visible
  {
    //int c
    //a and c are visible
    {
      int d;
      //a, c, and d are visible
    }
    //a and c are visible, d is no longer visible.
  }
  //only a is visible
}
//None of the vars are visible

The code above is quite contrived, but valid. You would not likely have braces that only define levels of scope, but you could. More likely they would enclose blocks, the bodies of if statments, functions, etc.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.