Looking for help ! ALGORITHM

Hello FFC Campers, someone can explain me those two algorithms code !

First :

FOR i FROM 0 TO N-1 STEP 2  DO
            sum := sum + tab[i];
        END_FOR

Second :

    WHILE (j < M) DO
            FOR j FROM 0 TO N  DO
                Write(i*j)
            END_FOR
            j := j+1;
        END_WHILE

You’ve posted a few of these and you’ve had a chance to get used to this syntax. What do you think they do? What parts confuse you?

We are here to help, but the help will be most useful if you tell us what parts of your homework are confusing for you and what you have tried so far.

2 Likes

Am not really understanding the syntax, it’s always the same, for example the first one i don’t understand the for i from 0 to n-1 step 2 do, and the second one i’m not understanding the for into the while

Let’s start small.

What do you know about for loops?

What value does i start at? What value does it stop at? How much does i increase by?

What might STEP change?

What is happening inside the body of the loop?

2 Likes

1- the for loop is a repetition statement, i start at 0 and stop at n, i increase i +
2- i don’t understand job of the step.
3- it will give us the sum of a table, exp : [4, 3, 5] if i = 2 the result will be 4+3+5

You are correct with 1, and you are mostly correct with 3.

For 2, lets do some research on ‘for loop step’.

https://duckduckgo.com/?t=lm&q=for+loop+step

The first result I get is this website: https://www.ozgrid.com/VBA/for-loop-step.htm

A For Loop is used to repeat a block of code a specified number of times. In this example we make use of the Step statement in 2 different ways. The first tell Excel to increment by 2 each loop, while the second tells Excel to count backwards from 10 to 1 and increment each time by -1.

Based on this search, what might STEP do?

3 Likes

the step statement tells the algorithm what to do, in our case it tell i to increase twice starting from 0 ending in N-1

What exactly do you mean by “increase twice”?

it’s i+2 instead of i++

Ok, so putting it all together, what does this code do?

if N = 10
the sum = sum + tab[2] + tab[4] + tab[6] + tab[8]

1 Like

doesn’t i start from 0?

2 Likes

Ah yes I start from 0 xD thank you @ilenia , and @JeremyLT thank you so much for your help and your explication and also your time!

1 Like