top of page
Writer's pictureD A Rosi Arsida Wardani

Loop

Introduction

Examples of algorithms in everyday life :

Example 1 : To finish eating a plate of rice (initial conditions)

Mouthfuls of a spoonful of rice (repetitive steps)

Stop eating when the food on the plate runs out (finished condition)

Example 2 : The amount of gasoline that comes out is 0 (initial conditions)

Liter by liter of gasoline out (step)

Does not come out in the 5th liter (finished condition)


 

Counter Concept



Assignment: i ← i + 1

The meaning of assignment : i on the left is the new value of i after the value of i on the right is added by 1. So, i = counter → every time the assignment statement is executed, the value of i increases by 1.


 

Total Concept



The difference between the total concept and the counter :

  • Counter, the element of the enhancer is 1

  • Total, the enhancer element is not equal to 1 (can be patterned or not)

Patterned additions :

example 1 : sum ← 0

for i ← 1 to n do

sum ← sum + i

example 2 : multiplication ← 1

for i ←1 to n do

multiplication ← multiplication * i


 

The Difference in Looping Statements



 

Sentinel

It is called sentinel when the number of inputs is unknown, but the nature of the data is known.


 


Recursive Function

The recursive function performs the looping process by calling itself. The difference with iterative functions is if iterative use iteration 'for', 'while', and 'repeat until', while recursive only uses 'if'.


//iterative
#include <iostream>
#include <string.h>
void turn (char *s){
	int i;
	for (i=strlen(s)-1; i>=0; i--)
		cout<<s[i];
}
main (){
	char *term="Algorithm";
	turn (term);
	return 0;
}

//recursive
#include <iostream>
#include <string.h>
void turn (char *s){
	if (*s != '/0'){
		turn (&s[1]);
		cout<<s[0];
	}
}
main (){
	char *term="Algorithm";
	turn (term);
	return 0;
}

 

Types of Recursion Methods

1. Going Down Recursion

The parameter decreases in value until the stop case is reached.

2. Going Up Recursion (upward recursion)

The parameter increases in value until the stop case is reached.

3. Two Half

It means, it is divided into two parts, where each part is also a recursion sub-program.

Recent Posts

See All

One-dimensional Arrays

One-dimensional arrays are data structures that contain data types of the same type. In the form of a group of related memories...

Subprogram dan Rekursi

metode : divide & conquer (dibagi-bagi menjadi bagian yang lebih kecil, lalu selesaikan masalah yang dihadapi) Prosedur Prosedur...

Comments


Post: Blog2_Post
bottom of page