Retrieve integers by looping through a NSMutableArray - objective-c

Can someone show me how to retrieve values by looping through a NSMutableArray? My code, which basically adds integer numbers to the array, is below :
NSMutableArray *ptr = [[NSMutableArray alloc] init];
[ptr addObject:[NSNumber numberWithInt:1]];
[ptr addObject:[NSNumber numberWithInt:2]];
[ptr addObject:[NSNumber numberWithInt:3]];
// How to retrieve them as integers?
I'm trying to retrieve each number from the array and sum them up to a total value.

Its actually pretty simple:
int totalValue = 0;
for(NSNumber *number in myArray) // Use fast enumeration to iterate through the array
{
totalValue += [number intValue];
}

I'm also a newbie so my answer may be wrong, but try this:
int sum = 0;
for (int i = 0, i < [ptr count], i++){
int value = [[ptr objectAtIndex:i] intValue] //you get the int, integerValue is applicable for NSInteger
sum = sum + value;//you adding values
}

Related

How to send values to Ivar in method

new to Objective-C and keeping it very very simple I'm looking to understand one thing at a time... I set up a very simple class called student all it does is add two numbers trying to see how things pass into and back from methods) **I rewrote the code ==>> look at end to see the version that works **
If I have a method that has
#property (nonatomic) int firstNum;
#property (nonatomic) int secondNum;
and I have an instance of my class called student I assign a value to firstNum like student.firstNum = 100; student.secondNum = 77; that is easy and the method adds them and sends the sum in a return
But in main I tried assigning it from an array and it did not work I tried
student.firstNum = [myIntegers objectAtIndex:0];
and
student.firstNum = [myIntegers objectAtIndex:i]; //using a for loop with i index
it says incompatible pointer to integer conversion
Here is the snippet from main I tried it's not complete it just is trying to set firstNum eventually I will also set up secondNum and send each pair to the method to get added together but for now I am stuck trying to get the firstNum assigned the value in myIntegers[i] to start
NSMutableArray *myIntegers = [NSMutableArray array];
for (NSInteger i= 0; i <= 10; i++) {
[myIntegers addObject:[NSNumber numberWithInteger:i]]; // this works up to here
student.firstNum = [myIntegers objectAtIndex:i]; // this does not work
}
I also tried [i].
Here is my method:
- (int)addNumbers {
int sum = self.firstNum + self.secondNum;
return sum;
}
HERE IS WHAT WORKS : assuming I have a student object
.m
(long)addNumbers:(NSNumber *)x :(NSNumber *)y {
long sum;
sum = [x integerValue] + [y integerValue];
return sum;
}
main
NSMutableArray *myIntegers1 = [NSMutableArray array];
NSMutableArray *myIntegers2 = [NSMutableArray array];
for (NSInteger i= 0; i <40; i++) {
[myIntegers1 addObject:[NSNumber numberWithInteger:i]];
[myIntegers2 addObject:[NSNumber numberWithInteger:i]];
long sum = [student addNumbers:[myIntegers1 objectAtIndex:i] :[myIntegers2 objectAtIndex:i]];
NSLog(#" The sum is %ld", sum);
}
You are creating a properties of type int, but in your for loop, you are trying to assign them an NSNumber.
NSNumber is a simple container for a c data item and can hold int, float, char, bool, etc.
Change your loop to be like that:
for (NSInteger i= 0; i <= 10; i++) {
[myIntegers addObject:[NSNumber numberWithInteger:i]];
student.firstNum = [[myIntegers objectAtIndex:i] intValue]; // this 'extracts' the int value from the NSNumber
}

Average of a NSArray and store value in a new NSArray

i would like to have the average of my NSArray element and store them in a new array in the following way.
NSArray* number;
NSMutableArray* Average;
[Average objectAtIndex:0]=[number objectAtIndex:0];
[Average objectAtIndex:1]=([number objectAtIndex:0] + [number objectAtIndex:1])/2;
[Average objectAtIndex:2]=([number objectAtIndex:0] + [number objectAtIndex:1] + [number objectAtIndex:2])/3;
i was thinking of doing it using 2 for loops
for (int i =0; i<[number count]; i++){
for (int j=0; j<i; j++){
temp+=[number objectAtIndex:j];
}
[Average addObject: temp/(i+1)];
}
can anyone help me with a more efficient way
thank you
You only need one loop:
NSArray *numbers = #[#(2.4), #(2.7), #(4.0)];
NSMutableArray *averages = [NSMutableArray array];
double total = 0.0;
for (int i = 0; i < [numbers count]; i++) {
total += [[numbers objectAtIndex:i] doubleValue];
[averages addObject:#(total / (i + 1))];
}
or, using fast enumeration:
__block double total = 0.0;
[numbers enumerateObjectsUsingBlock:^(NSNumber *number, NSUInteger idx, BOOL *stop) {
total += [number doubleValue];
[averages addObject:#(total / (idx + 1))];
}];
By the way, unrelated to your question, but if you simply wanted to average all the numbers in the numbers array, you could use KVC collection operator:
NSNumber *average = [numbers valueForKeyPath:#"#avg.self"];
Clearly that's only useful if you wanted to average all the numbers in the array, but it's a convenient shorthand in those situations.

how to get the index on numbers generated by int arc4random()

How do you get the index of the number appearing from the arc4rand method?. If 4,1,2,3 appear how do you index them . Example 4 would be 0 in the array.
int rand=((arc4random()%4)+1);
For getting random number, i did like this:
Suppose, i have a mutable array
NSMutableArray * myArray = [[NSMutableArray alloc] init];
and i kept 5 data in this myArray.
Now I have to generate random number index from myArray.
int randomIndex = (arc4random() % ([myArray count]));
Here randomIndex is random index of array
try this one. you need to put all that values into array.
NSMutableArray * array = [[NSMutableArray alloc] initWithCapacity:4];
[array insertObject:#"4" atIndex:0];
[array insertObject:#"1" atIndex:1];
[array insertObject:#"2" atIndex:2];
[array insertObject:#"3" atIndex:3];
using array to get index in ios to add all values in array like this
//convert int to nsstring and add array
NSArray *array=[NSArray arrayWithObjects:NSStringFromInt(4),NSStringFromInt(1),NSStringFromInt(2),NSStringFromInt(3), nil];
//reverse process to get int value
int value=[[array objectAtIndex:index]integerValue];
I'm just guessing, you might look for this...
NSMutableArray *_array = [NSMutableArray array];
for (int i = 0; i < 10; i++) {
[_array addObject:#((arc4random()%4)+1)];
}

Objective C - Array With Numbers

Is there a nicer way to fill an array with numbers than what I use?
It's crazy how much I got to write just to fill an array with numbers so they can be used for a calculation in a loop. This is easier in other C based languages like PHP, As3, or Java.
NSArray *myArray = [NSArray arrayWithObjects:
[NSNumber numberWithInt:1000],[NSNumber numberWithInt:237], [NSNumber numberWithInt:2673], nil];
int total = 0;
for(int i = 0; i < [myArray count]; i += 1 ){
total += [[myArray objectAtIndex: i]intValue];
NSLog(#"%i", total);
}
Hopefully there is a shorter way... I just want to fill an array with ints... cant be that hard
I guess you have to use NSNumber for an NSArray. If you want to use ints I guess you'd have to use a c array:
NSInteger myArray[20];
for (int i=0;i<20;i++) {
int num=myArray[i];
//do something
}
NSNumber though is I guess the better approach for this language.
At least you can do fast enumeration to shorten code a bit:
for (NSNumber *n in myArray) {
int num = [n intValue];
//do something....
}
EDIT:
The question has been asked 3 years ago. There have been new literals established to make it easier to create objects like NSNumbers or NSArrays:
NSNumber *n = #100;
or
NSArray *array = #[#100,#50,#10];
Nice short alternative for looping specific integers:
NSArray *numbers = [#"1000,237,2673" componentsSeparatedByString:#","];
for (NSString *i in numbers) {
[i intValue]; // Do something.
}
First start with a C array:
NSInteger myCArray = { 1000, 237, 2673 };
// calculate number of elements
NSUInteger myCArrayLength = sizeof(myCArray) / sizeof(NSInteger;
Second, if you need an NSArray loop through this array and create one:
NSMutableArray *myNSArray = [NSMutableArray arrayWithCapacity:myCArrayLength];
for(NSUInteger ix = 0; ix < myCArrayLength; ix++)
[myNSArray addObject:[NSNumber numberWithInteger:myCArray[ix]];
You can wrap the second piece of code up as a category on NSArray if you're doing it a lot.
too late. but u can do the following too.
int total = 0;
nsarray *myArray = #[#1.8,#100,#299.8];
for(nsnumber *num in myArray){
total+=num;
}

Populating array with integers

Let's say I want to populate NSarray with 50 integers. We know that NSarray accept only objects. So I have to do 50 times
NSNumber *num1 = [NSNumber numberWithInit:10];
NSNumber *num2 = [NSNumber numberWithInit:212];
......
NSNumber *num50 = [NSNumber numberWithInit:12];
Is there more elegant way to achieve that, beacause looks stupid 50 lines of code only for create number objects ?
try this...
NSMutableArray *array=[[NSMutableArray alloc]initWithCapacity:50 ];
for (int i=0; i<0; i++) {
NSNumber *number=[[NSNumber alloc] initWithInt:i];
[array addObject:number];
[number release];
}
//do anything with arrray and release the array later.
is this OK or you are seeking anything else.?
How about using NSMutableArray?
NSMutableArray* arr = [[NSMutableArray alloc] init];
int i = 0;
for(i=0; i<50; i++) {
NSNumber* num = [NSNumber numberWithInt:i]; // use i or random numbers
[arr addObject:num];
}
Your numbers do not seem to follow any particular pattern, so you might be better doing this by creating a C array first:
int myValues[] = { 10, 212, ..., 12 };
NSUInteger count = sizeof(myValues)/sizeof(int); // number of integers in myValues
// abstract the following into a function/method/category if doing more than once
NSMutableArray *objcValues = [NSMutableArray arrayWithCapacity:count];
for(NSUInteger ix = 0; ix < count; ix++)
[objcValues addObject:[NSNumber numberWithInt:myValues[ix]];