writing an algorithm in pseudocode - Programmers Heaven

#### Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

#### Categories

Welcome to the new platform of Programmer's Heaven! We apologize for the inconvenience caused, if you visited us from a broken link of the previous version. The main reason to move to a new platform is to provide more effective and collaborative experience to you all. Please feel free to experience the new platform and use its exciting features. Contact us for any issue that you need to get clarified. We are more than happy to help you.

# writing an algorithm in pseudocode

Posts: 2Member
how to write an algorithm that outputs the largest and the second largest elemnts in a sequence s1....sn where s1 is the first element and sn is the last element.

• Posts: 438Member
[code]
start
read Largest [red]// algorithm assumes n >= 2[/red]
if Second > Largest [red]// swap[/red]
S = Largest
Largest = Second
Second = S
for i = 2 to n
if (S > Largest) and (S > Second)
Second = Largest
Largest + S
else if S > Second
Second = S
write Largest, Second
stop
[/code]
• Posts: 9Member
: [code]:
: start
: read Largest [red]// algorithm assumes n >= 2[/red]
: if Second > Largest [red]// swap[/red]
: S = Largest
: Largest = Second
: Second = S
: for i = 2 to n
: if (S > Largest) and (S > Second)
: Second = Largest
: Largest + S
: else if S > Second
: Second = S
: write Largest, Second
: stop
: [/code]:
:

The only thing I would change is remove the (S > Second) in the first part of the if statement since an invariant of the for loop is that Largest > Second.

• Posts: 438Member
: : [code]: :
: : start
: : read Largest [red]// algorithm assumes n >= 2[/red]
: : if Second > Largest [red]// swap[/red]
: : S = Largest
: : Largest = Second
: : Second = S
: : for i = 2 to n
: : if (S > Largest) and (S > Second)
: : Second = Largest
: : Largest + S
: : else if S > Second
: : Second = S
: : write Largest, Second
: : stop
: : [/code]: :
: :
:
: The only thing I would change is remove the (S > Second) in the
: first part of the if statement since an invariant of the for loop is
: that Largest > Second.
:
:
:
Right. And the line
[code]
Largest + S
[/code]
is a typo that should be
[code]
[red]Largest = S[/red]
[/code]