English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

ur supposed to take the inetger that the user inputs and use a for loop so it starts from 2 keeps adding until it get to the intege rinputed. for example if the user inputs 5, the program should print out 14. (2+3+4+5) how would u write that using for loop? thanks in advance.

2007-10-04 09:37:20 · 4 answers · asked by sniper88gt 1 in Computers & Internet Programming & Design

4 answers

you need to know what number was provided

then run your for loop setting the initial variable to 2 and stopping when it reaches the number provided:

for(int i=2;i<=n;i++)

2007-10-04 09:47:13 · answer #1 · answered by Anonymous · 0 0

The for /next loop will start at 2 and continue executing the code contained within the loop until its variable reaches and exceeds the number input by the user

userValue = input an integer above 2
test userValue if less than 2 generate a warning message and ask user again

create a totalizer variable and initialize it to 0
total =0

create your for next loop

for x = 2 to userValue
'within this loop totalize the value of x every time this loop is executed

total = total + x

next x

print your answer here

print total

end of rogram

2007-10-04 16:55:34 · answer #2 · answered by MarkG 7 · 0 0

You didn't specify a language, but here's one way in Perl:

-------------
print "Please enter loop counter:";
chomp ($count = );

for ($x=2; $x <= $count; $x++) {
$total += $x;
# debug
}

print "Total = $total\n";
--------

If you want to track the progress of the adder through the loops you can add the following line where the #debug tag is above:

print "running total = $total this pass";

2007-10-04 17:08:34 · answer #3 · answered by StarXed 1 · 0 0

You didn't specify a language so here is a C Example

int index;
int count = 0;

for ( index = 2; index <= numInputed; index ++ ) {
count += index;
}

2007-10-04 16:47:34 · answer #4 · answered by JD 2 · 0 0

fedest.com, questions and answers