What is a Pseudocode
Pseudocode is a kind of structured english for describing algorithms. It allows the designer to focus on the logic of the algorithm without being distracted by details of language syntax. But in this post we will use the C style syntax when write write for loop pseudocode examples.
The For Loop
Loops can execute a block of code a number of times. A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.
On most programming languages(especially C based) uses the “for loop” statement as following:
1 2 3 4 5 |
for (statement1; statement2; statement3) { code block to be executed } |
The statement1 step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears.
Next, the statement2 is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and the flow of control jumps to the next statement just after the ‘for’ loop.
After the body of the ‘for’ loop executes, the flow of control jumps back up to the statement3. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the condition.
Pseudocode Example 1: Print Numbers from 1 to 20. (Pseudocode For Loop Example)
1 2 3 4 5 |
for(int i = 1; i <= 20; i++) { print i; } |
Pseudocode Example 2: Find Sum of Natural Numbers (1 to 100). (Pseudocode For Loop Example)
1 2 3 4 5 6 7 |
int sum=0; for(int i = 0; i <= 100; i++) { sum=sum+i; } print sum; |
Pseudocode Example 3: Read 50 numbers and find their sum and average. (Pseudocode For Loop Example)
1 2 3 4 5 6 7 8 9 10 |
int counter, sum=0, num; for(int i=1;i<=50;i++) { print "enter a number"; read num; sum=sum+num; } print sum; |
Pseudocode Example 4: Read 10 numbers and find sum of even numbers. (Pseudocode For Loop Example)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
int counter, sum=0, num; for(int counter=1; i<=10; i=i+1) { print "Enter a Number"; read num; if(num % 2 == 0) { sum=sum+num; } } print sum; |
Pseudocode Example 5: Find the sum of all elements of array. (Pseudocode For Loop Example)
1 2 3 4 5 6 7 8 9 10 11 |
int i=0, n=5, sum=0; array numbers=[65,45,10,7,125]; for(i=0;i<5;i=i+1) { sum = sum + numbers[i]; } print "Sum of numbers in the array" + sum; |