Need help with "for" loops

Here's what I'm trying to do in the following segment of code:

In the while loop, the user enters a series of numbers greater than zero, and the counter variable keeps track of how many numbers the user enters (I left out all the setup for this). Once the user enters a 0 or negative number, thereby indicating he's done entering numbers, it moves on to the for loop.

The for loop is where I have my problem. In the for loop, I want to carry out the sum, product and rsum operations defined therein, but as you can obviously see, the way I set it up makes no sense. b = user_entry(a) is my attempt at specifying a certain value of user_entry at the given point in the while loop (think of the notation y = f(x) to specify a certain value of y for a given x). But I know the way I wrote it isn't right. What do I have to do?

[php] while user_entry > 0;
counter = counter+1;
user_entry_str = input('Enter a number (0 or negative to end): ', 's');
user_entry = user_entry_str - '0';
end

for a = 1:counter;
b = user_entry(a);
sum = sum+b;
product = product*b;
rsum = rsum+1/b;
end [/php]

Thank you for any help you can provide.

Comments

  • kryystkryyst Ontario, Canada
    edited February 2011
    I know nothing about matlab. But just on basic programing it looks like you are trying to setup an array called user_entry that stores each number inputted. Then the For loop does a calculation based on each entry in that array. The problem to me doesn't look like your For loop is broken (though maybe it is). The problem to me looks like you while loop isn't assigning the input into array just constantly replacing the varriable user_entry.

    I think your code in the while loop should be user_entry(counter) = user_entry_str - '0';
  • shwaipshwaip bluffin' with my muffin Icrontian
    edited February 2011
    It looks like you're really close.

    You need to convert user_entry(a) from a char to a number before you can add it.
    b = str2num(user_entry(a));
    
    should be what you want
  • edited March 2011
    Thank you both, those suggestions made the damn thing finally work. :)
Sign In or Register to comment.